Java: Cancel Button does not close the window for JFrame - java

I want the window to close when I press on Cancel button, but it's not working.
Code:
public class FirstClass{
private JFrame frame;
private JButton btnCancel;
public FirstClass() {
frame = new JFrame("GRIIS Data Transfer [Mobile to PC]");
frame.setBounds(200,200,900,450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
btnCancel = new JButton("Cancel");
btnCancel.setBounds(800, 5, 85, 25);
frame.add(btnCancel);
btnCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.exit(0);
}
});
}
});
}//end of constructor
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
FirstClass window = new FirstClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Please let me know in case of changes needed in the code.
btnCancel.addActionListener()
so my code will work and close the application when I press on Cancel button.

Dont use window listner it gives event at time of closing, try
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});

No need to override WindowListener method,
public void actionPerformed(ActionEvent e) {
System.exit(0);
}

Related

Java - how do I check whether a JFrame is closed

When a user clicks the red 'X' button of a JFrame, how do I detect whether the JFrame is open or closed? I have a swing timer where the JFrame keeps updating it's label until the user closes down the JFrame.
int delay = 1000; //milliseconds
final Timer timer = new Timer(delay, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
tempLabel.setVisible(true);
String tmp = "test";
tempLabel.setText("Temperature : " + tmp);
// timer.stop();
}
});
timer.start();
You have to implement either the WindowStateListener or the WindowListener. If you use the WindowListener it could look like this:
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.Timer;
public class Foo implements WindowListener {
private Timer timer;
public static void main(String args[]){
initTimerComponent();
}
private void initTimerComponent() {
int delay = 1000; //milliseconds
timer = new Timer(delay, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
tempLabel.setVisible(true);
String tmp = "test";
tempLabel.setText("Temperature : " + tmp);
}
});
timer.start();
}
#Override
public void windowOpened(WindowEvent e) { }
#Override
public void windowClosing(WindowEvent e) {
timer.stop();
}
#Override
public void windowClosed(WindowEvent e) { }
#Override
public void windowIconified(WindowEvent e) { }
#Override
public void windowDeiconified(WindowEvent e) { }
#Override
public void windowActivated(WindowEvent e) { }
#Override
public void windowDeactivated(WindowEvent e) { }
}
You have to implement them all as WindowListener is an interface and the first concrete class implementing an interface is forced to implement all its abstract methods. But you actually need just one method.
Use this method
public void windowClosing(WindowEvent e) {
timer.stop();
}
to stop your timer as soon as the window is closing after the user clicked the red X.
Answer
addWindowListener(new WindowAdapter() {
//for closing
#Override
public void windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(null, "Closing");
}
//for closed
#Override
public void windowClosed(WindowEvent e) {
}
});

Java Swing GUI. Activating/Firing more buttons while keeping the mousebutton pressed

If I want to do an action, if a button is pressed I can use a ActionListener. But now if I want to activate more buttons by keeping the mousebutton pressed.
How can I implement this?
Thanks
Add a ChangeListener to the buttons ButtonModel, monitor for a change to the isPressed state.
The trick then is setting up some process which can then add the other components, in this simple example, I've used a Swing Timer, which will add roughly 40 new components a second while the button is pressed
public class TestPane extends JPanel {
private Timer timer = new Timer(25, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
add(new JButton("..."));
revalidate();
repaint();
}
});
public TestPane() {
JButton btn = new JButton("Help");
btn.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isPressed()) {
timer.start();
} else {
timer.stop();
}
}
});
add(btn);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
Thanks, this works if I press one Button. But if I press one Button and move the mouse with pressed mousebutton to another Button the secound button does nothing
Just so we're clear, I think this is a bad user experience, but that's me
public class Test {
public static void main(String[] args) {
new Test();
}
private boolean pressed = false;
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
add(makeButton("1"));
add(makeButton("2"));
}
protected JButton makeButton(String text) {
JButton btn = new JButton(text);
MouseAdapter ma = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
pressed = true;
}
#Override
public void mouseReleased(MouseEvent e) {
pressed = false;
}
#Override
public void mouseEntered(MouseEvent e) {
if (pressed) {
JButton btn = (JButton) e.getComponent();
System.out.println("Entered " + btn.getText());
btn.doClick();
}
}
};
btn.addMouseListener(ma);
btn.addMouseMotionListener(ma);
return btn;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
#npinti Now I can do an action for every button over which i hover with my mouse. But if I try to change the implementation, so that the action are only done, if the mouse is also clicked, the action only works if i press a button and over the same button again. `JButton b = new JButton();
if(a==1){
b.setBackground(Color.WHITE);
}else{
b.setBackground(Color.BLACK);
}
b.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent arg0 ) {
matrix.activate(x,y);
}
});
b.addMouseListener(new MouseListener() {
int pressed =0;
#Override
public void mouseReleased(MouseEvent e) {
pressed =0;
}
#Override
public void mousePressed(MouseEvent e) {
pressed =1;
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
if (e.getComponent().equals(b) && pressed ==1){
b.setBackground(Color.BLACK);
}
}
public void mouseClicked(MouseEvent e) {
pressed =1;
}
});`
Catch mouseEntered on your buttons and if a global boolean pressed is true (set it to true when you press a mouse button and false on release), fire an action with JButton.doClick() which simulates a click event on the button.

JFrame and while loop

How do I break a while loop if I click on my jframe shutdown? I 'm making a clicker that needs to be stopped at some point, but it'll just continue clicking even tho the exit has been pressed.
public class ClickWindow {
private JFrame frame;
private static Clicker click;
private static long currTime;
private static long totalTime;
private JTextField textField;
private static int textFieldValue = 0;
private static Boolean Bool = true;
/**
* Launch the application.
*/
public static void main(String[] args) throws InterruptedException {
click = new Clicker();
ClickWindow window = new ClickWindow();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ClickWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setBounds(100, 100, 289, 90);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_1 = new JButton("Press Space");
btnNewButton_1.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
Bool = false;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
if(textFieldValue == 0){
textFieldValue = 250;
}
try {
while (Bool) {
click.click();
textFieldValue = Integer.parseInt(textField.getText());
Thread.sleep(textFieldValue);
}
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
btnNewButton_1.setBounds(10, 25, 110, 23);
frame.getContentPane().add(btnNewButton_1);
textField = new JTextField();
textField.setBounds(127, 25, 141, 23);
frame.getContentPane().add(textField);
textField.setColumns(10);
}
public void windowClosing(WindowEvent event) {
Bool = false;
}
}
Clicker class
public class Clicker{
public static void click() throws AWTException{
Robot bot = new Robot();
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
Edited with the full code.
You should define the defaultCloseOperation for your JFrame:
JFrame myFrame = new JFrame("MyFrame");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If you set the defaultCloseOperation, hitting the close button will trigger a call to System exit:
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
JFrame myFrame = new JFrame("MyFrame");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//...add components here
myFrame.pack();
myFrame.setVisible(true);
}
catch (Exception e)
{
System.exit(-1);
}
}
});
}
If you want to shutdown the entire application you can just do this:
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This will shutdown your application after the Jframe was closed.
You can also call System.exit(0) in your windowClosing method or whenever you want to shutdown your application
instead of adding the keyListener to your JButton try having your JFrame, i.e. ClickWindow implement it. I think this would work.

Swing invokeLater() method not working

In my main Swing frame I have this method:
public void receiveCommand(String command) {
if (command.equals("enable")) {
Runnable enable = new Runnable() {
public void run() {
button1.setEnabled(true);
button1.revalidate();
button1.repaint();
}
};
SwingUtilities.invokeLater(enable);
}
basically, I'm trying to update the GUI (enable the button button1) from outside by calling the receiveCommand() method.
However this doesn't work, i.e button1 is still disabled. What did I do wrong here?
EDIT:
Here is the declaration of button1:
private javax.swing.JButton button1;
button1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
button1.setEnabled(false);
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button1ActionPerformed(evt);
}
});
Both button1 and the receiveCommand method are in this Game class:
public class Game extends javax.swing.JFrame
The method is called from another class:
gameUI.receiveCommand("enable"); //gameUI is a Game object
EDIT 2: Thank you for all your help! It turns out to be a wrong reference after all, so all I did was trying to update the GUI of a wrong frame that hadn't been set visible yet. Silly me
So anyway, this works.
public class TestInvokeLater {
public static void main(String[] args) {
new TestInvokeLater();
}
public TestInvokeLater() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(12, 12, 12, 12));
final JButton runMe = new JButton("Run me");
runMe.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runMe.setEnabled(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
runMe.setEnabled(true);
}
});
}
}).start();
}
});
setLayout(new GridBagLayout());
add(runMe);
}
}
}

Pressing Enter to Continue

I have a JDialog which has two fields, username and password. I want to make the form like normal ones in which pressing enter will be like pressing continue.
I have already tried getRootPane().setDefaultButton(myButton);, but only that does not seem to work.
I have already tried getRootPane().setDefaultButton(myButton);, but only that does not seem to work.
than you have to invoke code for this button with method
JButton#doClick();
but better would be use KeyBindings
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Test {
private static final long serialVersionUID = 1L;
private JDialog dialog = new JDialog();
private final JPanel contentPanel = new JPanel();
private Timer timer1;
private JButton killkButton = new JButton("Kill JDialog");
private JButton okButton = new JButton("OK");
public Test() {
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel buttonPane = new JPanel();
okButton.setActionCommand("OK");
buttonPane.add(okButton);
killkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
killkButton.setActionCommand("Kill JDialog");
buttonPane.add(killkButton);
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
startTimer();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
dialog.setLayout(new BorderLayout());
dialog.getRootPane().setDefaultButton(okButton);
dialog.add(buttonPane, BorderLayout.SOUTH);
dialog.add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setLocation(100, 100);
dialog.setVisible(true);
setKeyBindings();
}
private void setKeyBindings() {
okButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
okButton.getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
startTimer();
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setVisible(true);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
}
});
}
}
JButton button = ...
JTextField password = ...
ActionListener buttonListener = ...
button.addActionListner(buttonListener);
password.addActionListener(buttonListener);
When enter is pressed in a JTextField, an action event is fired.
You can achieve this by adding an action listener to your textfield, like so.
JTextField field1 = new JTextField();
field1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//here is your method to continue
continue();
}
});

Categories