How to close child jFrames automatically when i close the parent? - java

I have a parent JFrame and two 'child' JFrames in package JFrame. Imagine I open parent JFrame and then it's child JFrames - currently all 3 forms are open. Now I close parent JFrame.
What should I do to close all child frames automatically after close their parent JFrame?
Here is my code:
class Parent:
public class Parent extends JFrame {
public Parent() {
JButton child1 = new JButton("child1");
child1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Child1().setVisible(true);;
}
});
JButton child2 = new JButton("child2");
child2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Child2().setVisible(true);
}
});
JButton closeAllJframe = new JButton("closeAllJframe");
closeAllJframe.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
this.setBounds(500, 200, 400, 200);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
dispose();
}
});
JPanel jPanel = new JPanel();
jPanel.add(child1);
jPanel.add(child2);
jPanel.add(closeAllJframe);
this.add(jPanel);
}
#Override
public void dispose() {
super.dispose();
}
public static void main(String[] args) {
new Parent().setVisible(true);
}}
class Child1:
public class Child1 extends JFrame {
public Child1() {
this.setBounds(200, 300, 300, 200);
this.setTitle("child 1");
}}
class Child2:
public class Child2 extends JFrame {
public Child2() {
this.setBounds(200, 300, 300, 200);
this.setTitle("child 1");
}}

Add an window listener to the frame then implements the windowClosed(WindowEvent e) method Javadoc about WindowListener

Related

setDefaultCloseOperation doesn't work for JButton

I have created three classes:
public class Gui extends JFrame {
private final JButton buttonClose = new JButton("Close");
private final MyButtonListener buttonListener = new MyButtonListener(this);
private final MyWindowListener windowListener = new MyWindowListener();
public SwitchGuiExtListeners() {
super("Switch");
setSize(200, 150);
setLayout(new BorderLayout());
add(buttonClose, BorderLayout.EAST);
buttonClose.addActionListener(this.buttonListener);
this.addWindowListener(this.windowListener);
setVisible(true);
}
public JButton getButtonClose() {
return buttonClose;
}
}
public class SwitchGuiWindowListener implements WindowListener{
...
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
...
}
public class MyButtonListener implements ActionListener {
private final Gui gui;
public MyButtonListener (final Gui gui) {
this.gui = gui;
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == gui.getButtonClose()){
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//System.exit(0);
}
}
}
If I use the gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); my frame doesn't close. But when I use the System.exit(0) it works. Why can't I use the setDefaultCloseOperation(..)?
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); does not close a JFrame. It simply tells that the JFrame must exit when the close button on top-right corner of a window is clicked i.e., just sets the behavior but does trigger an exit.
To close a JFrame, use something like this:
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
Source: https://stackoverflow.com/a/1235994/1866196

AWT: Components disappear after minimizing the frame or after moving another window on top

I'm using webcam-capture libraries and AWT to develop a simple interface for taking pictures from a webcam. The buttons and the combobox in my JFrame disappear after minimizing the window or after moving another window on top of it. Moving the pointer over the frame restores the components' visibility. I'm not skilled with Java UI, I can't figure out what's wrong with my code.
#SuppressWarnings("serial")
public class ImageCaptureManager extends JFrame {
private class SkipCapture extends AbstractAction {
public SkipCapture() {
super(“Skip”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class SnapMeAction extends AbstractAction {
public SnapMeAction() {
super(“Snap”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class captureCompleted extends AbstractAction {
public captureCompleted() {
super(“Completed”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class saveImage extends AbstractAction {
public saveImage() {
super(“Save”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class deleteImage extends AbstractAction {
public deleteImage() {
super(“Delete”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class StartAction extends AbstractAction implements Runnable {
public StartAction() {
super(“Start”);
}
#Override
public void actionPerformed(ActionEvent e) {
btStart.setEnabled(false);
btSnapMe.setEnabled(true);
executor.execute(this);
}
#Override
public void run() {
panel.start();
}
}
private Executor executor = Executors.newSingleThreadExecutor();
private Dimension captureSize = new Dimension(640, 480);
private Dimension displaySize = new Dimension(640, 480);
private Webcam webcam = Webcam.getDefault();
private WebcamPanel panel;
private JButton btSnapMe = new JButton(new SnapMeAction());
private JButton btStart = new JButton(new StartAction());
private JButton btComplete = new JButton(new captureCompleted());
private JButton btSave = new JButton(new saveImage());
private JButton btDelete = new JButton(new deleteImage());
private JButton btSkip = new JButton(new SkipCapture());
private JComboBox comboBox = new JComboBox();
public ImageCaptureManager() {
super(“Frame”);
this.addWindowListener( new WindowAdapter()
{
#Override
public void windowDeiconified(WindowEvent arg0) {
}
public void windowClosing(WindowEvent e)
{
}
});
List<Webcam> webcams = Webcam.getWebcams();
for (Webcam webcam : webcams) {
System.out.println(webcam.getName());
if (webcam.getName().startsWith("USB2.0 Camera 1")) {
this.webcam = webcam;
break;
}
}
panel = new WebcamPanel(webcam, displaySize, false);
webcam.setViewSize(captureSize);
panel.setFPSDisplayed(true);
panel.setFillArea(true);
btSnapMe.setEnabled(false);
btSave.setEnabled(false);
btDelete.setEnabled(false);
setLayout(new FlowLayout());
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(10, 1));
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSnapMe);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSave);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btDelete);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btComplete);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSkip);
JLabel label1 = new JLabel("Test");
label1.setText(“Bla bla bla”);
JLabel label2 = new JLabel("Test");
label2.setText(" ");
Panel captionAndWebcamPanel = new Panel();
captionAndWebcamPanel.add(label1);
captionAndWebcamPanel.add(label2);
captionAndWebcamPanel.add(panel);
captionAndWebcamPanel.add(label2);
captionAndWebcamPanel.add(comboBox);
captionAndWebcamPanel.setLayout(new BoxLayout(captionAndWebcamPanel, BoxLayout.Y_AXIS));
add(captionAndWebcamPanel);
add(buttonPanel);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
btStart.doClick();
setSize(900,600);
}
}
You are mixing AWT and Swing components.
"Historically, in the Java language, mixing heavyweight and lightweight components in the same container has been problematic."
http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html
I suggest you try using JPanels instead of Panels for captionAndWebcamPanel and buttonPanel, I'd also set layout to captionAndWebcamPanel before adding components.

Java: WindowAdapter windowClosed method not running

I'm currently running this in a class that extends a JFrame. When I close the window, I don't see RAN EVENT HANDLER in the console. This is not the main window, and more than one instance of this window can exist at the same time.
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
}
});
This method is inside a method called initialiseEventHandlers() which is called in the constructor, so I'm sure the code is running.
What am I doing wrong?
Thank you!
EDIT: Here's the full (summarised) code:
public class RacesWindow extends JFrame {
private JPanel mainPanel;
private JLabel lblRaceName;
private JTable races;
private DefaultTableModel racesModel;
public RacesWindow() {
this.lblRaceName = new JLabel("<html><strong>Race: " + race.toString()
+ "</strong></html>");
initialiseComponents();
this.setMinimumSize(new Dimension(500, 300));
this.setMaximumSize(new Dimension(500, 300));
initialiseEventHandlers();
formatWindow();
pack();
setVisible(true);
}
public void initialiseComponents() {
mainPanel = new JPanel(new BorderLayout());
races = new JTable();
racesModel = new DefaultTableModel();
races.setModel(racesModel);
}
public void initialiseEventHandlers() {
System.out.println("EVENTHANDLER CODE IS CALLED"); //for debugging
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
appManager.removeOpenWindow(race.toString());
}
});
}}
public void formatWindow() {
mainPanel.add(lblRaceName, BorderLayout.NORTH);
mainPanel.add(new JScrollPane(races), BorderLayout.CENTER);
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
this.add(mainPanel);
}
}
I found out I was using the wrong method: windowClosed(). I should use windowClosing()!
This should work
this.addWindowListener(new WindowListener() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
}
});
Add this to your constructor.
setDefaultCloseOperation(EXIT_ON_CLOSE);
The code below worked for me.
// parent class {
// constructor {
...
this.addWindowListener(new GUIFrameListener());
...
}
class GUIFrameListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("Window Closed");
}
}
} // end of parent class

Create a shortcut in JFrame

public final class UserPage extends JFrame{
public UserPage() {
this.addKeyListener(new myclass());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000, 600);
this.setLocation(300, 60);
this.setResizable(false);
this.setVisible(true);
}
.
.
.
public class myclass extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
System.out.println("Key \"Delete\" Pressed");
}
}
}
}
But, when i press delete button, not see the "Key \"Delete\" Pressed" message!
JFrame (all Top-Level Containers) by default never to react to KeyEvents, have to use this Listener for JComponent they are to consume Focus, or is possible to flag it with setFocusable()
don't to use low_level KeyListener for Swing JComponents, if is possible then to use hight level abstraction, to use KeyBindings instead
JRootPane + KeyBindings(As #mKorbel has already said)
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
Also check out: JMenuItem#setAccelerator(...)
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
SSCCE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UserPageTest {
public static JMenuBar makeMenuBar() {
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Test");
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
menu.add(item);
bar.add(menu);
return bar;
}
public static Action action = new AbstractAction("UserPage?") {
#Override public void actionPerformed(ActionEvent e) {
System.out.println("UserPage Action");
}
};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() { createAndShowGUI(); }
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setJMenuBar(makeMenuBar());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

JavaFX 2.2 : How to forward mouse event to a Swing component under a JFXPanel in a JLayeredPane?

In my application, I want to have a Swing panel with JavaFX control over it. For that, I use a JLayeredPane in which I insert a JPanel and a JFXPanel with a Scene that is not filled (aka setFill(null)). But no event passes through transparent areas of the JFXPanel to the Swing panel.
Is there any solution to this problem ?
Thanks
Here an example :
public class TestJavaFX
{
private static JButton button;
private static JFXPanel javafxPanel;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
initAndShowGUI();
}
});
}
public static void initAndShowGUI()
{
JFrame frame = new JFrame("Swing application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
javafxPanel = new JFXPanel();
button = new JButton("Swing - Push me");
JLayeredPane pane = new JLayeredPane();
pane.add(button, JLayeredPane.DEFAULT_LAYER);
pane.add(javafxPanel, JLayeredPane.PALETTE_LAYER);
pane.addComponentListener(new ComponentListener()
{
#Override
public void componentShown(ComponentEvent e)
{
}
#Override
public void componentResized(ComponentEvent e)
{
button.setBounds(20, 50, 150, 30);
javafxPanel.setBounds(0, 0, e.getComponent().getWidth(), e.getComponent().getHeight());
}
#Override
public void componentMoved(ComponentEvent e)
{
}
#Override
public void componentHidden(ComponentEvent e)
{
}
});
frame.getContentPane().add(pane, BorderLayout.CENTER);
Platform.runLater(new Runnable()
{
public void run()
{
createScene();
}
});
// Show frame.
frame.setSize(600, 400);
frame.setVisible(true);
}
private static void createScene()
{
Button btn = new Button();
btn.setText("JavaFX - Push me");
VBox pane = new VBox();
pane.getChildren().add(btn);
Scene scene = new Scene(pane);
scene.setFill(null);
javafxPanel.setScene(scene);
}
}

Categories

Resources