英文:
JLabel setLocation and setBounds methods not working
问题
首先,我非常清楚布局管理器的存在,只是在这种情况下我不想使用它。
我正在为我的应用程序编写一个简单的主菜单,但无论我做什么,图像(JLabel
)始终设置在屏幕的左上角。我已经尝试过使用setLocation
和setBounds
这两种方法,但没有任何区别。
我确定这是一个愚蠢的错误,但我似乎找不出问题所在。
这是我的代码:
import javax.swing.*;
public class Main extends JFrame{
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
Main() {
ImageIcon image1=createImageIcon("/monopoly.jpg","");
JLabel image1l=new JLabel(image1);
image1l.setLocation(200,200);
image1l.setBounds(330, 300, 140, 60);
add(image1l);
}
public static void main(String[] args) {
Main f=new Main();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.pack();
f.setTitle("Monopoly");
f.setSize(800,800);
f.setLocationRelativeTo(null);
f.setLayout(null);
}
}
英文:
First of all, I am well aware of the existence of Layout Managers, I just don't want to use it in this case.
I'm writing a simple main menu for my application, but no matter what I do the Image (JLabel
) always sets itself in left upper corner of screen. I've tried using both methods (setLocation
, setBounds
), but it does not make any difference.
I'm sure it is some stupid mistake, but I can't seem to figure it out.
Here's my code:
import javax.swing.*;
public class Main extends JFrame{
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
Main() {
ImageIcon image1=createImageIcon("/monopoly.jpg","");
JLabel image1l=new JLabel(image1);
image1l.setLocation(200,200);
image1l.setBounds(330, 300, 140, 60);
add(image1l);
}
public static void main(String[] args) {
Main f=new Main();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.pack();
f.setTitle("Monopoly");
f.setSize(800,800);
f.setLocationRelativeTo(null);
f.setLayout(null);
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论