Here is my shortened version of my code:
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
is added to a JFrame of sized using my_frame.setSize(400, 300);
.
The above code works as expected. But when I uncomment the comment piece of code, the JButton
appears to the right side of the images(JLabel
s) instead of appearing below the images. What could be the problem?
Additional information:
final static int TOPSWITCH = 150;
final static int LEFTSWITCH1 = 65 ;
final static int LEFTSWITCH2 = 155;
final static int LEFTSWITCH3 = 245;
switch1.jpg
is of dimensions 91 x 150
Note: I want to do this without adding more JPanels
.
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.