这是我的代码的缩短版本:
JPanel card1 = new JPanel();
JLabel switch1 = new JLabel(new ImageIcon("switch1.jpg"));
switch1.setLocation(TOPSWITCH, LEFTSWITCH1);
JLabel switch2 = new JLabel(new ImageIcon("switch1.jpg"));
switch2.setLocation(TOPSWITCH, LEFTSWITCH2);
JLabel switch3 = new JLabel(new ImageIcon("switch1.jpg"));
switch3.setLocation(TOPSWITCH, LEFTSWITCH3);
card1.add(switch1);
card1.add(switch2);
card1.add(switch3);
card1.setBackground(Color.BLACK);
/* JButton goToRoom = new JButton("TEST");
goToRoom.setLocation(180, 270);
card1.add(goToRoom); */
card1
使用 my_frame.setSize(400, 300);
添加到大小为 JFrame 中。
上面的代码按预期工作。但是,当我取消注释代码段时,JButton
出现在图像(JLabel
)的右侧,而不是出现在图像下方。可能是什么问题?
其他信息:
final static int TOPSWITCH = 150;
final static int LEFTSWITCH1 = 65 ;
final static int LEFTSWITCH2 = 155;
final static int LEFTSWITCH3 = 245;
switch1.jpg
尺寸为 91 x 150
注意:我想在不添加更多 JPanels
的情况下执行此操作。
最佳答案
What could be the problem?
- 想要设置明确的位置。
- 与布局管理器对抗。
Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作,在不同的语言环境中使用不同的 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them以及 white space 的布局填充和边框.
关于java - JButton 上的 setLocation 似乎没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30779844/