In my Swing chat application I have a logout button which is used to logout the user and it works fine. Now I need to logout the user when I close the Swing application window.
I did this in web application when closing browser using JavaScript, but now I need to do this in Swing application.
How can I achieve this?
Call JFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
Add a WindowListener to the frame.
Override the appropriate method of the listener to call your closing method, then set the frame invisible and dispose of it.
E.G.
import java.awt.*;
import java.awt.event.*;
import java.net.URI;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class CheckExit {
public static void doSomething() {
try {
// do something irritating..
URI uri = new URI(
"http://stackoverflow.com/users/418556/andrew-thompson");
Desktop.getDesktop().browse(uri);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout());
gui.setPreferredSize(new Dimension(400, 100));
gui.setBackground(Color.WHITE);
final JFrame f = new JFrame("Demo");
f.setLocationByPlatform(true);
f.add(gui);
// Tell the frame to 'do nothing'.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
WindowListener listener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent we) {
int result = JOptionPane.showConfirmDialog(
f, "Close the application");
if (result==JOptionPane.OK_OPTION) {
doSomething();
f.setVisible(false);
f.dispose();
}
}
};
f.addWindowListener(listener);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Use the window events on your JFrame, there you have the Methods you might need (windowclosed();) for example. it´s the WindowListener
edit :
you can say
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
but your Windowlistener still works if you push the X (close button)
there you override the method windowClosing, with this code
public void windowClosing(WindowEvent e) {
int i = JOptionPane.showConfirmDialog(TestFrame.this, "do you really want to close?","test",JOptionPane.YES_NO_OPTION);
if(i == 0) {
System.exit(0);
}
}
this will do the work
Related
I am fairly new to coding and have encountered this issue within my code.
I create a button using the Java AWT import. I then check for a response using a while loop and wish to create another button after, however .add() seems to no longer function.
import java.awt.*;
import java.awt.event.*;
public class Main1
{
public static void main(String[] args)
{
Frame f = new Frame();
f.setSize(500, 500);
f.setVisible(true);
ButtonPanel bp = new ButtonPanel(f);
bp.x = null;
while (bp.x == null)
{
}
System.out.println(bp.x);
//THE ISSUE- THIS WILL NOT APPEAR AFTER BUTTON PRESS
f.add("South", new Button("REEE"));
}
}
class ButtonPanel extends Panel implements ActionListener
{
volatile String x;
public ButtonPanel(Frame f)
{
Button b = new Button("Hi");
b.addActionListener(this);
f.add("North", b);
}
public void actionPerformed(ActionEvent e)
{
x = e.getActionCommand();
}
}
I have been trying solutions for this for the last day or so and nothing seems to be working. I've seen in other posts people have said to use Wait/Notify however I am not too sure how those work and I would like to know explicitly what is going wrong in my program (though I am still open to using Wait/Notify in my solution).
Any help would be appreciated, thank you very much
So, they're a number of issues at play here.
The first is the fact that layout managers are generally lazy. This means that you can add and/or remove a number of components quickly and then do a single layout and paint pass.
To do this, you need to revalidate the Container which was updated.
Next, AWT (and Swing by extension) is based on Model-View-Controller concept, one aspect of this is the "observer pattern". This is basically a callback concept that allows you to be notified when something of interest happens.
Button makes use of an ActionListener to generate events when the button is "actioned". This is the "observer pattern" in action.
Why is this important? You really want to think about what information is needed to be passed where and who's actually responsible for doing what.
For example, is it really the ButtonPanel's responsibility to update the frame? Is giving ButtonPanel unfettered control over the frame really a good idea?
Instead, ButtonPanel "should" be providing some kind of notification when some action has occurred and then any interested parties should be able to do what ever they need to.
As a "basic" example...
import java.awt.Button;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventListener;
import javax.swing.event.EventListenerList;
public class Test {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
public Test() {
Frame f = new Frame();
f.setPreferredSize(new Dimension(500, 500));
f.pack();
ButtonPanel bp = new ButtonPanel(f);
bp.addObsever(new Observer() {
#Override
public void hiWasPerformed() {
f.add("South", new Button("REEE"));
f.revalidate();
}
});
f.setVisible(true);
}
public interface Observer extends EventListener {
public void hiWasPerformed();
}
class ButtonPanel extends Panel {
private EventListenerList eventListener = new EventListenerList();
public ButtonPanel(Frame f) {
Button b = new Button("Hi");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Observer[] listeners = eventListener.getListeners(Observer.class);
for (Observer observer : listeners) {
observer.hiWasPerformed();
}
}
});
f.add("North", b);
}
public void addObsever(Observer observer) {
eventListener.add(Observer.class, observer);
}
public void removeObsever(Observer observer) {
eventListener.remove(Observer.class, observer);
}
}
}
It looks like nothing is happening because the buttons are being added below the bottom of the window. You should consider using a layout manager to solve this issue.
However, in the meantime the simple solution is to move this line f.add("South", new Button("REEE")); inside the action event and to make use of Frame.pack();:
public class Main1
{
public static void main(String[] args)
{
Frame f = new Frame();
//set minimums rather than a fixed size
f.setMinimumSize(new Dimension(500, 500));
f.setVisible(true);
CustomButton b = new CustomButton(f);
//Add this line to update/size/show the UI
f.pack();
//Don't place any more code inside the main method. Future events should be triggered by interacting with the UI/buttons
}
}
Then for the button we don't need to extend Panel, we can do something like this:
class CustomButton implements ActionListener
{
Frame parentFrame;
public CustomButton(Frame f)
{
parentFrame = f;
Button b = new Button("Hi");
b.addActionListener(this);
f.add("North", b);
}
public void actionPerformed(ActionEvent e)
{
//Add button here instead of the main class
parentFrame.add("South", new Button("REEE"));
//The buttons are being added below the bottom of your window, this will force them to be shown.
//Using a layout manager will solve this ploblem and you will not need to do this:
parentFrame.pack();
}
}
Note: clicking on the "Hi" button multiple times will have interesting results of the "REEE" buttons overlapping or doing odd things if you resize the window.
I am developing a tool for my laptop. I want to disable minimize button in the JFrame. I have already disabled maximize and close button.
Here is the code to disable maximize and close button:
JFrame frame = new JFrame();
frame.setResizable(false); //Disable the Resize Button
// Disable the Close button
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Please, tell me how to disable minimize button.
Generally, you can't, what you can do is use a JDialog instead of JFrame
As #MadProgrammer said (+1 to him), this is definitely not a good idea you'd rather want to
use a JDialog and call setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); to make sure it cannot be closed.
You could also use a JWindow (+1 to #M. M.) or call setUndecorated(true); on your JFrame instance.
Alternatively you may want to add your own WindowAdapater to make the JFrame un-minimizable etc by overriding windowIconified(..) and calling setState(JFrame.NORMAL); from within the method:
//necessary imports
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Test {
/**
* Default constructor for Test.class
*/
public Test() {
initComponents();
}
public static void main(String[] args) {
/**
* Create GUI and components on Event-Dispatch-Thread
*/
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
}
});
}
private final JFrame frame = new JFrame();
/**
* Initialize GUI and components (including ActionListeners etc)
*/
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setResizable(false);
frame.addWindowListener(getWindowAdapter());
//pack frame (size JFrame to match preferred sizes of added components and set visible
frame.pack();
frame.setVisible(true);
}
private WindowAdapter getWindowAdapter() {
return new WindowAdapter() {
#Override
public void windowClosing(WindowEvent we) {//overrode to show message
super.windowClosing(we);
JOptionPane.showMessageDialog(frame, "Cant Exit");
}
#Override
public void windowIconified(WindowEvent we) {
frame.setState(JFrame.NORMAL);
JOptionPane.showMessageDialog(frame, "Cant Minimize");
}
};
}
}
If you don't want to allow any user action use JWindow.
You may try to change your JFrame type to UTILITY. Then you will not see both minimize btn and maximize btn in your program.
I would recommend you to use jframe.setUndecorated(true) as you are not using any of the window events and do not want the application to be resized. Use the MotionPanel that I've made, if you would like to move the panel.
I am a novice as already stated and looking to create a button to close the program out. I am not talking about making sure the typical window close (Red X) terminates the program. I wish to make an additional button within my frame that when clicked will terminate the program as well.
You can add an ActionListener to your button which, upon action being performed, exits from the JVM.
yourButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
If you have set up the main application frame's (JFrame) defaultCloseOperation to JFrame.EXIT_ON_CLOSE then simply calling the frame's dispose method will terminate the program.
JButton closeButton = JButton("Close");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
yourReferenceToTheMainFrame.dispose();
}
});
If not, then you will need to add to the actionPerformed method a call to System.exit(0);
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class GoodbyeWorld {
GoodbyeWorld() {
final JFrame f = new JFrame("Close Me!");
// If there are no non-daemon threads running,
// disposing of this frame will end the JRE.
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// If there ARE non-daemon threads running,
// they should be shut down gracefully. :)
JButton b = new JButton("Close!");
JPanel p = new JPanel(new GridLayout());
p.setBorder(new EmptyBorder(10,40,10,40));
p.add(b);
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
ActionListener closeListener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
f.setVisible(false);
f.dispose();
}
};
b.addActionListener(closeListener);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new GoodbyeWorld();
}
};
SwingUtilities.invokeLater(r);
}
}
If you are extending the org.jdesktop.application.Application class (Netbeans would do that) you could invoke exit() in your app class, so:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
yourApp.exit();
}
});
I have a class developed with windowbuilderpro that i want to close also from a JButton further than with the standard X button on the window, so here the example of the class :
public class MainWindow {
public JFrame frame;
public MainWindow() {
initialize();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void show() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//Show the main Frame
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
When i close the window from the X button the window close correctly and the process terminate.
When i close instead from a JButton that have this listener :
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Close the application main form
frame.setVisible(false);
frame.dispose();
}
});
the frame window close correctly but the process remain alive ... Why ?
As you can see there is an AWT-Shutdown thread that start and terminate continuously, How can i achieve the same behaviour of the X button that close also the application process ?
Notes :
System.exit(0); is not suitable because it terminate the application also if there are another background running thread and i don't want that . The MainWindow class should close and release it's resource, the same behaviour that have closing the application with the X button that close the MainWindow instance but if there are background thread running it doesn't kill they but wait until they finished their work...
Enviroment :
JDK 7
Eclipse 3.7.1
not sure what you really needed, that looks like that you create new JFrame again an again, don't do that, create JFrame once and re-use this Container
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // do nothing
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); // same as setVisible(false)
then for visibily you can only to call frame.setVisible(true);
for more Confortable is override WindowListener, then you can control some Events
All threads in this code stop when either the x button or the Exit button are activated. Are you getting different behavior?
import java.awt.event.*;
import javax.swing.*;
public class MainWindow {
public JFrame frame;
JButton mntmExit = new JButton("Exit");
public MainWindow() {
frame = new JFrame("Close Me!");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Close the application main form
frame.setVisible(false);
frame.dispose();
}
});
frame.add(mntmExit);
frame.pack();
show();
}
public void show() {
//Show the main Frame
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainWindow mw = new MainWindow();
mw.show();
}
});
}
}
Just add one line:
System.exit(0);
I have a JFrame and JPanel full of Jsomethings with an actionlistener. When the user clicks an object I want to open another JFrame. Here is what I did:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == rejectionbutton){
RejectApp ra = new RejectApp();
ra.main(null);
}
}
(RejectApp calls a new JFrame.) So another JFrame opens on the screen with more options. It works OK (so far), but I want to know is this standard? I mean calling the main method like this?
Another question is, without using a cardlayout (which I don't want to use), is the best way to handle multiple panels, by doing this sort of thing?
I would change a few things. First off, usually an application has one JFrame and then if it needs to show another window does so as a modal or non-modal dialog such as can be obtained with a JDialog or JOptionPane. Having said that, it's even more common to have one JFrame and swap "views" in the JFrame -- swap contentPanes or other large panels via a CardLayout as this would mimic the behavior of many gui programs we all currently use.
Personally, I also try to gear my GUI creation towards creating a JPanel or JComponent rather than towards creating a top-level window. This way if I want to display the GUI as a stand alone app, a dialog, or an applet I can pop it into the contentPane of a JFrame or JDialog or JApplet respectively, or if as an inner panel of a more complex GUI, then insert it there, or in an application with a swapping view, then as a card in a CardLayout as noted above. The bottom line is I feel that this structure gives you the developer a lot more options in how you can use this GUI.
Also, I would avoid calling another class's main as you're doing (assuming this is the public static void main method) as you lose all benefits of OOPs. You also seem to be trying to call a static method in a non-static way (assuming I understand your program structure correctly).
For your second question, it begs a question of my own: why do you not want to use CardLayout?
edit: an example of what I meant is as follows:
import java.awt.Dimension;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SwingEg {
private static void createAndShowUI() {
JFrame frame = new JFrame("Main JFrame");
frame.getContentPane().add(new MainGUI().getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MainGUI {
private static final Dimension MAIN_PANEL_SIZE = new Dimension(450, 300);
private JPanel mainPanel = new JPanel();
private JDialog modalDialog;
private JDialog nonModalDialog;
public MainGUI() {
JButton openModalDialogBtn = new JButton("Open Modal Dialog Window");
openModalDialogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openModalDialogBtnActionPerformed(e);
}
});
JButton openNonModalDialogBtn = new JButton("Open Non-Modal Dialog Window");
openNonModalDialogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openNonModalDialogBtnActionPerformed(e);
}
});
mainPanel.setPreferredSize(MAIN_PANEL_SIZE);
mainPanel.add(openModalDialogBtn);
mainPanel.add(openNonModalDialogBtn);
}
private void openModalDialogBtnActionPerformed(ActionEvent e) {
if (modalDialog == null) {
Window topWindow = SwingUtilities.getWindowAncestor(mainPanel);
modalDialog = new JDialog(topWindow, "Modal Dialog", ModalityType.APPLICATION_MODAL);
modalDialog.getContentPane().add(new DialogPanel().getMainPanel());
modalDialog.pack();
modalDialog.setLocationRelativeTo(topWindow);
modalDialog.setVisible(true);
} else {
modalDialog.setVisible(true);
}
}
private void openNonModalDialogBtnActionPerformed(ActionEvent e) {
if (nonModalDialog == null) {
Window topWindow = SwingUtilities.getWindowAncestor(mainPanel);
nonModalDialog = new JDialog(topWindow, "Non-Modal Dialog", ModalityType.MODELESS);
nonModalDialog.getContentPane().add(new DialogPanel().getMainPanel());
nonModalDialog.pack();
nonModalDialog.setLocationRelativeTo(topWindow);
nonModalDialog.setVisible(true);
} else {
nonModalDialog.setVisible(true);
}
}
public JPanel getMainPanel() {
return mainPanel;
}
}
class DialogPanel {
private static final Dimension DIALOG_SIZE = new Dimension(300, 200);
private JPanel dialogPanel = new JPanel();
public DialogPanel() {
dialogPanel.add(new JLabel("Hello from a dialog", SwingConstants.CENTER));
dialogPanel.setPreferredSize(DIALOG_SIZE);
}
public JPanel getMainPanel() {
return dialogPanel;
}
}
I would rather make a new instance of JFrame or a subclass, or call a new method who makes a new JFrame:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == rejectionbutton){
JFrame frame = new JFrame("New Frame");
//or
makeNewFrame();
}
}
Another simple Layout-Manager is the BorderLayout, it´s the default Layout-Manager of the JFrame class.
new YourJFrameNameHere().setVisible(true);
Replace YourJFrameNameHere with the JFrame name.
Simple, no?