How can I set an action command to window closing event? - java

How can I set an action command to closing event of a custom frame class which is a subclass of javax.swing.JFrame?
This is the current code:
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// some stuff here
}
});
The code that goes in // some stuff here is shared with a button labeled quit. For the button, I have set an action command to "quit" and set the listener to an external class named NavigationHandler whose actionPerformed has a case for "quit". If I could set the action command of my window closing event to "quit", I could use the same listener for the window too.
Currently I have a method that I call from both sites, but that feels unclean.

try as follow
To reuse the actionListener of quite button you can click quite button in windowClosing .
to click a button from code call doclick() method. example
quitButton.doClick();

You want to add a WindowListener to the JFrame which will let you get close events.
frame.addWindowListener(new MyWindowListener());
...
public class MyWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
// do something
}
}

Related

JPanel button not responding?

I implemented the following code to get my character image to change when I clicked the button I created in the JPanel of Netbeans but it's not even being called (tested this by adding a line to print out in console but that's not even being printed. Any help would be appreciated.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println("Switch!");
snowman.removeAllImages();
snowman.addImage(image2);
make try and catch statement in your action e.pritntrace it very helpful to debug you code and find your bugs hope this will help you
to change when I clicked the button I created in the JPanel of Netbeans but it's not even being called (tested this by adding a line to print out in console but that's not even being printed.
You may want to ensure the following:
Make sure the button you are interested to generate an event on click has already added as ActionListener object
Example:
If you create an inner class for your ActionListener object,
btn.addActionListener(new ButtonHandler());
If you implements your current class with ActionListener,
btn.addActionListener(this);
If you create an anonymous ActionListener object,
btn.addActionListner(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//To do when button is clicked
}
});
I see that you created your own method to handle an action event:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
If you do that, remember to fill up your codes in the actionPerformed() method of the ActionListener object which was added to your button.
Example:
#Override
public void actionPerformed(ActionEvent e){
jButton2ActionPerformed(e);
}
Well explained by user3437460. If that doesn't help please copy more code here to understand it. Add a button listener and make sure you called your private method from it as shown below.
btn.addActionListner(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
jButton2ActionPerformed(e);
}
});

Resetting a JDialog after closing

I am using a JDialog to get payment info, paymentAmount and Date is submitted by a JTextfield and a datechooser.beans.DateChooserCombo.
When the user close the JDialog or clicks Cancel, JDialog closes.But when they click the Payment button and JDialog reappears, previously submitted inputs are shown.
I want JDialog to be default state whenever it appears.Is there a default way to do this, or i have to create my own reset method?
When you close a dialog it is not destroyed. It will just become invisible, but it still contains everything as it was when it was closed.
You may override the function setVisible() and reinitialize it if the dialog should be shown again.
#Override
public void setVisible(boolean bVisible)
{
if(bVisible == false)
{
super.setVisible(bVisible);
return;
}
initMyValues();
super.setVisible(bVisible);
return;
}
Alternatively you could create a WindowListener and then you get notified about various state changes of the window. Depends on what suits your needs better. The WindowListener doesn't require you to create a separate class, jsut to override the setVisible(), but you have to add some extra function required by the interface.
Another workaround would be to set a windowListener to your dialog.
myDialog.addWindowListener(new WindowListener() {
/*Implements over methods here*/
#Override
public void windowClosing(WindowEvent e) {
//set default values here
}});

Events and Listeners in Java

This should be a basic Java program for beginners to be found on
"Head First Java 2nd Edition" on the topic of ActionListener interface.
I didn't understand some of the terminologies used in this program such as
button.addActionListener(this);
when this code executes how is the method actionPerformed is triggered or run or
any terminologies you use??
//Program begins from now!!
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1B implements ActionListener {
JButton button;
public static void main(String[] args) {
SimpleGui1B gui = new SimpleGui1B();
gui.go();
}
public void go(){ //start go
JFrame frame= new JFrame();
button=new JButton("Click me");
frame.getContentPane().add(button);
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}//close go()
public void actionPerformed(ActionEvent event){
button.setText("I’ve been clicked!");
}
}
Let's break down this statement shall we:
button.addActionListener(this);
Okay, so you're referencing the button object. This is an object of type JButton I presume. The button object has a method called addActionListener. What this does, is add an object that implements the ActionListener interface.
The class that this occurs in is one of those objects. As you can see at the top it says:
public class SimpleGui1B implements ActionListener
So what the program is doing, is saying that the current class (this) will work as a parameter for your method. Then if you look in this class, you have a method actionPerformed.
public void actionPerformed(ActionEvent event){
button.setText("I’ve been clicked!");
}
This means that whenever the button is clicked, the code inside the actionPerformed method is called. Another alternative is to say:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Add some code here.
}
This is doing the exact same thing, only it's defining the class inside the brackets.
In the JButton class, the keyboard and mouse events are handled, and once the button detects a click, it iterates to its action listeners and calls them:
ActionEvent event = new ActionEvent(...);
for (ActionListener listener : addedListeners) {
listener.actionPerformed(event);
}
Listeners are just callback objects.
Let's walk through the code:
In javax.swing.AbstractButton there is a method called addActionListener where the code is:
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
listenerList is defined in javax.swing.JComponent as:
protected EventListenerList listenerList = new EventListenerList();
When an event occurs fireActionPerformed in javax.swing.AbstractButton is called. The code looks like:
protected void fireActionPerformed(ActionEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
ActionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ActionListener.class) {
// Lazily create the event:
if (e == null) {
String actionCommand = event.getActionCommand();
if(actionCommand == null) {
actionCommand = getActionCommand();
}
e = new ActionEvent(AbstractButton.this,
ActionEvent.ACTION_PERFORMED,
actionCommand,
event.getWhen(),
event.getModifiers());
}
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
The most important part is the last line that says:
((ActionListener)listeners[i+1]).actionPerformed(e);
This is the line of code that calls your actionPerformed() method
That means that the class which is invoking this code is a listener of button changes. So that button will invoke "actionPerformed" on this particular class.
button.addActionListener(this); tells button that this wants to know whenever the button is clicked. From then on, whenever the button is clicked it will go through its list of registered ActionListeners and call the actionPerformed method on each one.
What the code
button.addActionListener(this);
does is add your class (using the keyword this) to be the action listener of the button you created.
What this means, is that the button will call your class whenever an action (such as click) happens. This is why you need the method
public void actionPerformed(ActionEvent event){
button.setText("I’ve been clicked!");
}
Because it will be called by the button
Basically you are going thru observer pattern where observers registers themselves with subject.Now whenever this is some event triggers on subject , subject notifies the different observers. Here Button is subject and SimpleGui1B(basically listener) is observer.Now lets come to your code snippet
button.addActionListener(this);
In above line , button is subject and this is listener/observer. JButton has designed in a way, whenever some event(click in this case) happens on button, observers will be notified thru the method actionPerformed

ActionListener with a mousepress in java

I am trying to Make a action performed method activate when the mouse is pressed. is this possible. i can only find example like:
if(e.getsource() == button1){
....
}
can this method be activated by a mouseclick?
You could use a MouseListener to your component (and then call the actionListener from its mouse clicked event.
See: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
You may want to create a third function taking a JComponent source and having that containing your actionlistener code and being called by both your mouselistener and actionlistener.
You can try the following code...
This will just print "Hi" to terminal every time you click whatever you put the mouseListener on. Replace contentPane with whatever you called it, and don't forget your import statements.
contentPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("Hi");
}
});

How to capture a JFrame's close button click event?

I want to call a method confirmExit() when the red close button of the title bar of a JFrame is clicked.
How can I capture that event?
I'd also like to prevent the window from closing if the user chooses not to proceed.
import javax.swing.JOptionPane;
import javax.swing.JFrame;
/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure you want to close this window?", "Close Window?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Override windowClosing Method.
public void windowClosing(WindowEvent e)
It is invoked when a window is in the process of being closed. The close operation can be overridden at this point.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
also works. First create a JFrame called frame, then add this code underneath.
This may work:
jdialog.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.out.println("jdialog window closed event received");
}
public void windowClosing(WindowEvent e) {
System.out.println("jdialog window closing event received");
}
});
Source: https://alvinalexander.com/java/jdialog-close-closing-event
This is what I put as a menu option where I made a button on a JFrame to display another JFrame. I wanted only the new frame to be visible, and not to destroy the one behind it. I initially hid the first JFrame, while the new one became visible. Upon closing of the new JFrame, I disposed of it followed by an action of making the old one visible again.
Note: The following code expands off of Ravinda's answer and ng is a JButton:
ng.addActionListener((ActionEvent e) -> {
setVisible(false);
JFrame j = new JFrame("NAME");
j.setVisible(true);
j.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
setVisible(true);
}
});
});
Try this:
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
It will work.

Categories

Resources