How to end Swing program with always-on-top dialog? - java

How to finish the program? I mean that after executing it and closing the dialog the Java process does not finish. It can be viewed in Eclipse so the red icon is still active and the program does not finish.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(
frame, "test info", "test header", JOptionPane.INFORMATION_MESSAGE);
}
}

Dispose the frame after the dialog is set visible.
import javax.swing.*;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(
frame, "test info", "test header", JOptionPane.INFORMATION_MESSAGE);
// When a frame is disposed, the exit action will be called.
frame.dispose();
}
}

You can use following close the process. But it is little bit hard.
System.exit(0);

Because you did not call method like:
frame.show(); or frame.setVisible(true);
If you call one of the methods then the frame will show up and then if you close the frame, it will stop to run.
code update:
private static void createAndShowGUI() {
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
frame.setSize(200, 200);
frame.setVisible(true);
JOptionPane.showMessageDialog(frame, "test info", "test header", JOptionPane.INFORMATION_MESSAGE);
}

Related

why is there problem without windowClosing

I know that this program needs window Closing function to close the frame but I don't know why
explanation would be helpful
public class NoLayoutDemo {
public static void main(String[] args) {
Frame frame= new Frame("no layout teset");
frame.setLayout(null);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
According to java documentation
WINDOW_CLOSING:
If the program doesn't explicitly hide or dispose the window while processing this
event, the window close operation is canceled.
Then you have to do the close operation yourself, otherwise the close operation has no effect.
Hope this helps
Maybe like this?
public class NoLayoutDemo {
public static void main(String[] args) {
Frame frame = new Frame("no layout teset");
frame.setLayout(null);
frame.setSize(200, 300);
frame.show();
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent evt) {
frame.dispose();
}
});
}
}

How to make JFrame active (focused)?

When dialog window displayed it does not focused if other window is active (i.e. you need to focus it by mouse pointer to be able to deal with it). How can I make a focus to displayed dialog?
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class GuiTest {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(frame, "test info", "test header",
JOptionPane.INFORMATION_MESSAGE);
//frame.toFront();
//frame.requestFocus();
frame.dispose(); // When a frame is disposed, the exit action will be
// called.
}
}
JOptionPane.showMessageDialog stops the EDT (Event Dispatching Thread) until the dialog is closed.
You could instead use another JFrame instead of a JOptionPane
package util;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class GuiTest {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiTest window = new GuiTest();
window.frame.setVisible(true);
Dialog d = new Dialog();
d.show();
window.frame.requestFocus();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GuiTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Dialog extends JFrame {
private JFrame frame;
public void show() {
if (frame == null) {
frame = new JFrame();
frame.setTitle("Dialog");
frame.setBounds(100, 100, 450, 300);
frame.add(new JTextField("Hello"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
frame.setVisible(true);
}
}
try to run it and right after that make any other window active
Once a window loses focus you need to either:
click on the window to give it focus
Use the desktop manager to access the application. In Windows this is done by using Alt+Tab to cycle through open applications.
The problem is that only a JFrame is added to the desktop manager so if you want the ability to use Alt+Tab then you need to make the frame visible BEFORE showing the option pane.
Of course the JFrame will now be visible on the screen so you can use the setLocation(...) method with a negative value to hide the frame from the visible desktop.

Swing : Exit application actionListener

I am trying to figure out how can we exit the application with button click.
The problem i faced which makes me unable to exit the application is because i am using "extend JFRame" from the main class.
For an example,
app.class
public class app{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame frame = new MainFrame("Exercise one");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
.. .. ..
frame.setVisible(true);
})
}
}
MainFrame.java
public class MainFrame extends JFrame(){
public MainFrame(String title){
super(title)
//set layout manager
setLayout(new BorderLayout());
//swing components
JButton exit = new JButton("Exit");
//add container
Container container = getContentPane();
container.add(exit);
//create actionlist logic
exit.addActionListener(new ActionListener()){
#Override
public void actionPerformed(ActionEvent arg0){
// on click , this logic will end the application
}
}
}
}
I fully understand how i can cancel the application from app class.But in scenarios where i want to cancel the application from MainFrame.Can it be done ?
Thank you in advance.
The defaultCloseOperation is only processed by the frame when it encounters a WINDOW_CLOSING event, neither setVisible or dispose trigger this event, which means the the defaultCloseOperation won't be processed
The only way to ensure that this operation is triggered is to manually dispatch a WINDOW_CLOSING event
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
One of the main reasons for wanting to follow this path is that it ensures the application is following the configured defaultCloseOperation and making up it's own mind (like calling System.exit manually)
The following demonstrates hiding, disposing and dispatching approaches. Only the dispatch approach will close the window and terminate the JVM
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import static javax.swing.Action.NAME;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
frame.add(new JButton(new HideAction(frame)), gbc);
frame.add(new JButton(new DisposeAction(frame)), gbc);
frame.add(new JButton(new DispatchAction(frame)), gbc);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.out.println("Closing");
}
#Override
public void windowClosed(WindowEvent e) {
System.out.println("Closed");
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class HideAction extends AbstractAction {
private JFrame frame;
public HideAction(JFrame frame) {
this.frame = frame;
putValue(NAME, "Hide");
}
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
}
public class DisposeAction extends AbstractAction {
private JFrame frame;
public DisposeAction(JFrame frame) {
this.frame = frame;
putValue(NAME, "Dispose");
}
#Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
}
public class DispatchAction extends AbstractAction {
private JFrame frame;
public DispatchAction(JFrame frame) {
this.frame = frame;
putValue(NAME, "Dispatch");
}
#Override
public void actionPerformed(ActionEvent e) {
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
}
}
If I run this in my IDE, unless I use the dispatch option, the JVM is left running and I have to terminate the session to close it fully.
I also noted that calling dispose only triggers the WINDOW_CLOSED event, while the dispatch method will trigger the WINDOW_CLOSING event
Problem solved.
Credits to #XtremeBaumer.
Basically, when using "classname" extend JFRame.
We can input dispose() which will kill the application completely. This will causes the JFrame window to be destroyed and cleaned up by the operating system. :)
Indeed, dispose() is the right solution. I also suggest to add a pack() call so the UI shows up properly:
public class MainFrame extends JFrame {
public MainFrame(String title) {
super(title);
...
// create actionlist logic
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("--> closing app programmatically");
MainFrame.this.dispose();
}
});
this.pack();
}
}
You can test the events with a WindowListener on the MainFrame. They are invoked as if the user pressed the close button:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new MainFrame("Exercise one");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
// .. .. ..
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("--> closing...");
}
public void windowClosed(WindowEvent e) {
System.out.println("--> closed...");
}
});
}
});
}

Close JFrame in actionPerformed-method (JFrame is private static void createGUI())

I have copied most of my Code from an oracle-example, so I think at least the code I did not add should be correct and I donĀ“t like to change that. But in the oracle-code I can not implement this line to properly close my JFrame: frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
private static void createGUI() {
JFrame frame = new JFrame("NameChooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==skipButton){
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); WindowEvent.WINDOW_CLOSING)); // does not work ofc
}
}
How can I close my JFrame in the actionPerformed-method without destroying this correct way of opening a JFrame ?
Or is this oracle-code just suitable for examples and not for real applications ?
You should make frame an instance field like this:
private static JFrame frame;
private static void createGUI()
{
frame = new JFrame( "NameChooser" );
...
}

JFrame size is too small

i have created a JFrame in netbeans. But when i run the program, the Jframe size is too small.
here is my code.
import javax.swing.JFrame;
public class Window {
private static void demo()
{
JFrame frame =new JFrame();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run()
{
demo();
}
});
}
}
You can use frame.setSize(width, height) in order to set its size or frame.setBounds(x, y, width, height) for setting both the location and size.
A better choice would be to call frame.pack() after you add some components to its content pane.
Try this way...
Use the setSize(width, height) method of JFrame.
public class Myframe extends JFrame{
public Myframe(){
this.setSize(300,300);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
Myframe f = new Myframe("Frame");
f.setVisible(true);
}
});
}
}
If you want to maximize it you could try
this.setVisible(false);
this.setExtendedState(MAXIMIZED_BOTH);
this.setVisible(true);
this.setResizable(false);
Else for some specific size use
this.setSize(width,height);
You just need to add one line line so that you can give your frame a size.The line is
frame.setSize(300,300);
Here is the full code:
import javax.swing.JFrame;
public class Window {
private static void demo()
{
JFrame frame =new JFrame();
frame.setSize(300,300);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run()
{
demo();
}
});
}
}
You must have a public component method like
public gestion_name_of_class() {
initComponents();
}

Categories

Resources