Java : Swing : Hide frame after button pressed

后端 未结 4 614
闹比i
闹比i 2021-01-14 17:37

I have a button in a java frame that when pressed it reads a value from a text field and uses that string as a port name attempting to connect to a serial device.

If

4条回答
  •  遥遥无期
    2021-01-14 18:11

    Your code would be much more readable if you named JFrame instances xxxFrame, and JPanel instances xxxPanel. Naming JPanel instances xxxFrame makes things very confusing.

    It would also help if you pasted the stack trace of the exception.

    I suspect the problem comes from the fact that frame is null. This is due to the fact that the frame field is only initialized in the createAndShowGUI method, but this method doesn't display the current connection panel, but a new one, which thus have a null frame field:

    ConnectionFrame firstPanel = new ConnectionFrame();
    // The firstPanel's frame field is null
    firstPanel.createAndShowGUI();
    // the firstPanel's frame field is now not null, but
    // the above call opens a JFrame containing another, new ConnectionFrame, 
    // which has a null frame field
    

    The code of createAndShowGUI should contain

    frame.add(this);
    

    rather than

    frame.add(new ConnectionFrame());
    

提交回复
热议问题