Server is a class I made that extends JFrame.
Server serverApp = new Server(TITLE, WIDTH, HEIGHT, true, false);
I’ve effectively removed almost all the other code but the problem still remains!
c = getContentPane();
c.setLayout(new BorderLayout());
//Components /***AHHHHH***/
lblEnterMessage = new JLabel("Enter Message ");
txtEnterMessage = new JTextField(50);
txtEnterMessage.addActionListener(this);
btnSend = new JButton("Send");
btnSend.addActionListener(this);
taDisplay = new JTextArea("Test, test test.", 10, 0);
taDisplay.setEditable(false);
JScrollPane jspDisplay = new JScrollPane(taDisplay);
pnlChatTop = new JPanel(new FlowLayout());
pnlChatTop.add(lblEnterMessage);
pnlChatTop.add(txtEnterMessage);
pnlChatTop.add(btnSend);
pnlChat = new JPanel(new BorderLayout());
pnlChat.add(pnlChatTop, BorderLayout.CENTER);
pnlChat.add(jspDisplay, BorderLayout.SOUTH);
c.add(pnlChat, BorderLayout.CENTER);
Oh dang, it just suddenly WORKED… And I was about to remove this question but I ran it again a few times it and just randomly WORKS and doesn’t WORK at times.
I’ve just remembered having this problem before with other ‘projects’ and my solution was to make the window resizable. Whenever I simply resized it, the components would display.
This time, I’m making a game and I don’t want it to be resizable… and I wanna know how to fix this problem for good and in the proper way anyway.
Help! Does anyone know why this is happening?
Thanks.
Edit:
public Server(String title, int sizeW, int sizeH, boolean visibility, boolean resizability) {
/* Initialization */
//JFrame settings
setTitle(title);
setSize(sizeW, sizeH);
setVisible(visibility);
setResizable(resizability);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
Will that help?
The problem is not apparent from the code you have provided.
It sounds like you want some combination of the pack(), setSize(int,int), setExtendedState(int) and/or setResizable(boolean) methods prior to calling setVisible(true).
Edit:
There is a race condition in this code. Sometimes the main thread will get the components into the correct state to be painted before the frame displays; sometimes the frame wins and starts painting before everything is ready.
The thing about using Swing is that you are automatically working with multi-threaded code. Although it is generally safe to initialize controls on the main thread, once you cause the event dispatch thread to start (as
setVisible(true)will surely do), all bets are off.Delay calling
setVisible(true)as long as possible. Preferably, don’t call it from within yourJFrameconstructor.If you need to modify Swing controls after you’ve kicked off your application, you’ll need to do it via the event dispatch thread (see the
invokeLaterandinvokeAndWaitmethods in SwingUtilities, among others).