Wednesday 29 November 2017

java - Swing - Dispose a frame

First, it's not a good practice to name classes with a
lowercase, so try renaming to something like MakeGUI instead of
makeGUI.


The problem with your
commented code is that it creates a new instance of makeGUI
every time the button is clicked and the action listener is
invoked. The result is that when you click on the close button, a new frame is created,
then an inner one and this inner one gets immediately closed. The only thing you'd be
doing is creating more and more frames. You should keep the instance as a state, for
instance as a class member:


class MakeGUI
{
JFrame smallframe;
JButton close = new JButton("CLOSE
ME");
MakeGUI() {
frame f1 = new frame();
smallframe =
new JFrame(); //want to close this one
JPanel jp = new JPanel(new
FlowLayout());
smallframe.setSize(300, 300);

smallframe.setLocationRelativeTo(null);

smallframe.setDefaultCloseOperation(smallframe.DISPOSE_ON_CLOSE);

close.addActionListener(new action());
jp.add(close);

smallframe.add(jp);
smallframe.setVisible(true);
}

class action implements ActionListener {
public void
actionPerformed(ActionEvent e) {
if (e.getSource() == close) {
//
use this instead of dispose
smallframe.dispatchEvent(new
WindowEvent(smallframe, WindowEvent.WINDOW_CLOSING));

System.out.println("gotcha");
}
}

}
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...