I've got a piece of code that sometimes runs fine and sometimes doesn't. I'm literally not changing anything but sometimes the text field will appear and sometimes it won't appear. How can code possibly run differently every time? It makes no sense to me. I'm reasonably new to java but I certainly didn't think this was possible...
If anyone can help me, could you include the fix, but also why this is happening? Because I'd like to understand the problem fully.
Here is my code:
import javax.swing.*;
public class Window {
JFrame frame;
JPanel panel;
public Window(int x, int y, String t, boolean isHomePage){
int xSize = x;
int ySize = y;
String title = t;
frame = new JFrame();
frame.setSize(xSize, ySize);
frame.setLocationRelativeTo(null);
frame.setTitle(title);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
panel.setVisible(true);
if (isHomePage){
homePage();
}
}
public void homePage(){
JLabel usernameLabel = new JLabel();
usernameLabel.setText("Please enter your username:");
usernameLabel.setBounds(0,100,300,20);
panel.add(usernameLabel);
usernameLabel.setVisible(true);
JTextField textbox = new JTextField();
textbox.setVisible(true);
textbox.setBounds(280,100,400,20);
panel.add(textbox);
}
}
As Reimeus states --
setBounds()
might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.setVisible(true)
on the JFrame after adding all components to the GUI, not before.Note that you're confused on how setVisible(true) works. Yes, you're calling it on your sub components, but they've already get their visible property as true by default, and so calling this on the sub components has no effect. Your problem is when you're calling setVisible on the JFrame. You're calling it before adding the JPanel with the text field on it, and so this will cause it to appear occasionally. Prove it for yourself. Minimize and restore your GUI if the texzt field isn't visible, and it should now show.
Myself, if I wanted to swap views as you're trying to do above, I'd use a CardLayout.