I've searched similar threads but I can't seem the find the solution that fits. (I'm new to java)
I have made an texteditor and i need to make the option to save before exit. A possible window that pops up and asks the user if they want to save or not...
The main frame has set this:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
And this is my inner class that handles the event that is generated when the user selects Exit from the file menu.
private class ExitListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
Thanks!
So in your frame class you should override the method processWindowEvent.
#Override
protected void processWindowEvent(WindowEvent e) {
if(e.getID() == WindowEvent.WINDOW_CLOSING){
System.out.println("Windows is closing");
}
super.processWindowEvent(e);
}
Related
I am building a text editor and I don't know how to handle a listener on Swing exit button, which is create automatically.
I want to use dialogs when user doesn't save file, for example press exit button.
final JFrame f = new JFrame("Good Location & Size");
// make sure the exit operation is correct.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent we) {
// pop the dialog here, and if the user agrees..
System.exit(0);
}
});
As seen in this answer to Best practice for setting JFrame locations, which serializes the frame location & size before exiting.
Assuming you have a handle on your window, assuming it's a Window object (e.g. a JFrame or other kind of window), you can listen to WindowEvent events. Here is an example with windowClosed, you can replace it with windowClosing if you need to intercept it before.
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
// do something here
}
});
Go stepwise:
Declare a boolean variable saved and set its default value to false.
When user saves the file, change it to true
When exit button is pressed, check the variable.
If true, exit, else, prompt user for saving file.
So, finally this code snippet looks like:
public boolean saved = false;
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saved = true;
//Code to save file
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(saved)
System.exit(0);
else {
//Code to prompt user to save file
}
}
});
I am quite new to Java, but familiar with native Android dev so bear with me xD. I created an application that creates a JFrame. Then I set the closeOperation to: setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);.
It performs as expected, the frame is hidden and this is what I want (when I close). I need the application to keep on running (only once instance), because I am running a thread in the background that is performing an operation.
My actionListener on my button in my JFrame currently does this: setVisible(false);
My question is this, how can I maximize the JFrame again after it has been hidden? Would it be possible to display the frame when the user clicks on the minimized application in the task bar? Is there some type of listener that I need to implement?
Thanks in advance, any advice will be appreciated
UPDATE
For this solution to work correctly you need to do the following. Also have a look at XtremeBaumer's answer for this to make sense.
On JFrame creation setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);.
When you want to minimize the app (on click possibly) frame.setState(Frame.ICONIFIED);.
When you want to maximize the app again frame.setState(Frame.NORMAL); in windowDeiconified event.
One last thing, if you want to also minimize your app when the user clicks on the exit button (red x) add this to the windowClosing event frame.setState(Frame.ICONIFIED);.
this.addWindowListener(new WindowListener(){
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
setState(Frame.ICONIFIED)
}
#Override
public void windowDeactivated(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
this.setVisible(true);
//this should be what you want
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowOpened(WindowEvent e) {
}
});
i hope this solves your question. add it to your JFrame
I've already this project, but I'm having more problems. The dialog for SetMusicDialog opens, but it won't close when I try to exit out. I have a System.exit, but I'm not sure why the window won't close.
import java.awt.*;
import java.io.*;
public class SetMusicDialog extends Dialog
{
public static String sng;
public SetMusicDialog()
{
super ((Dialog)null, "Set Music");
Panel mpanel;
Font l = new Font("Helvetica", Font.ITALIC, 12);
setFont(l);//sets font
setBackground(Color.cyan);
Panel f = new Panel();
f.add("West", new Button("Death Grips"));
f.add("East", new Button("Siren"));
add("South",f);
pack(); // make it just fit
resize(preferredSize());
move(200,200);
}
public boolean handleEvent1 (Event evt)
{
switch (evt.id)
{
case Event.WINDOW_DESTROY:
System.exit(0);
dispose();
return true;
case Event.ACTION_EVENT:
if("Death Grips".equals(evt.arg))
{
sng= "breakmirrors.wav";
}
else if("Siren".equals(evt.arg))
{
sng= "bip.wav";
}
dispose();
}
return false;
}
}
You can add this:
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
});
windowClosed won't detect if the user tries to close the window. It will only run if the window has been closed. So use windowClosing.
Also, by using WindowAdapter you do not need to write all the methods of WindowListener.
I added this code in your constructor, and it works properly.
If you are using AWT, you should create a WindowListener as MadProgrammer stated. Basically, a WindowListener is a class that has methods that are run when certain window-related actions occur. To write code that will run when a Dialog (which extends Window) is closed:
//d is a dialog
d.addWindowListener(new WindowListener() {
//You'll need to implement all the abstract methods. leave them empty.
#Override
public void windowClosed(WindowEvent e) {
//Your code
}
});
Basically, you're anonymously implementing the abstract class WindowEvent. Make sure you implement all the other methods too, or you will get compiler errors. Your IDE should automatically implement all the methods.
I have a JFrame main window wich has a Register button on in.Click the register button and the JDialog windows pops out.
public void mouseClicked(MouseEvent e) {
Reg new1=new Reg(users);
new1.setVisible(true);
}
The JDialog window has 2 buttons->Register,Cancel.Both of them must do something and close the Dialog window.
This is what I tried.
In the Reg(Dialog window)---> btnCancel:
public void mouseClicked(MouseEvent e) {
dialog.dispose();
System.out.println("Reg disposed by cancel button");
}
This closes the D window when run just the D window but I guess when executed from the main window(Button clicked) it still exists like an object in the main fraim"class" and doesn't close.What should I do ?How do I make it close ?
You need some way for the frame to determine how the dialog was closed
// Why are you using a `MouseListener` on buttons??
// User use keyboards to, use an ActionListener instead
public void mouseClicked(MouseEvent e) {
Reg new1=new Reg(users);
new1.setVisible(true);
switch (new1.getDisposeState()) {
case Reg.OK:
// Clicked Ok
break;
case Reg.CANCEL:
// Clicked cancel or was closed by press [x]
break;
}
}
Then in your Reg class, you need to maintain information about the state...
public class Reg extends JDialog {
public static final int OK = 0;
public static final int CANCEL = 1;
private int disposeState = CANCEL;
//...
public int getDisposeState() {
return disposeState
}
public void setDisposeState(int state) {
disposeState = state;
}
Then you change the state
// Why are you using a `MouseListener` on buttons??
// User use keyboards to, use an ActionListener instead
public void mouseClicked(MouseEvent e) {
setDisposeState(CANCEL);
dialog.dispose();
System.out.println("Reg disposed by cancel button");
}
This all assumes that your dialog is modal of course...
Now, having said all that, personally, I would make your Reg class a JPanel and add it to a JOptionPane instead or use a CardLayout
Take a look at:
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listeners
How to Make Dialogs
How to Use CardLayout
...for more details
I am working on a Java application and interfacing with an RFID reader that acts as a keyboard input device.
The application will be used for employee time tracking, so the employee should not see the code that his/her RFID tag contains.
Currently, the application opens a jFrame that asks the employee to scan their tag. This is where I would like to listen for the keyboard input.
All of the RFID tags are 10 digits, so I would like to use some kind of regex to detect when a card is scanned if possible.
If someone could point me in the right direction, or contribute some code I would be grateful.
Thanks in advance.
UPDATE:
I was able to read the input of the scanner by adding the following to the constructor of my JFrame.
addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){ System.out.print(e.getKeyChar());}
#Override
public void keyReleased(KeyEvent e) { }
#Override
public void keyTyped(KeyEvent e) { }
});
So it is now confirmed that the Reader is just standard Keyboard input.
Here is an example of what I get for a tag: 0006459027
Now, the big question is, how do I take the characters that I got, and detect that it is a 10 digit string, and from there trigger an event to open a new frame?
First, I'd see if the RFID reader is triggering an ActionEvent to be fired when the tag is scanned. This would be the simplest approach.
Failing that, you would need to attach a DocumentListener to the fields underlying document and monitor for changes.
You'll need to decide how best to interrupt the results (as you're likely to get each letter of the RFID at a time). You could monitor the length of the document or have a javax.swing.Timer which triggers after a short delay (you'd reset the timer on each update event triggered by the DocumentListener)
Check out
JTextField.addActionListener
JTextField.getDocument().addDocumentListener
I'd suggest taking a look at DocumentFilter as well, but your interested in the final result, not modifying it.
UPDATED with DocumentListener Example
// In the classes variable decleration section...
private JTextField rfidField;
// In the classes constructor or UI init method...
rfidField = new JTextField(12);
rfidField.getDocument().addDocumentListener(new DocumentListener() {
public void handleUpdate(DocumentEvent e) {
if (e.getDocument().getLength() == 10) {
System.out.println("Trigger me happy...");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
rfidField.setText(null);
}
});
}
}
#Override
public void insertUpdate(DocumentEvent e) {
handleUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
handleUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
handleUpdate(e);
}
});
// Now don't forget to add the field to your forms container ;)
//////
One of things I would be do when you "trigger" the code event is, once you've read it from the text field, is clear the text field (JTextField.setText(null)) - IMHO
If the RFID reader acts as a keyboard input device, try with key events:
JFrame frame = new JFrame();
// frame setup
frame.addKeyListener(new KeyAdapter(){
public void KeyPressed(KeyEvent ke)
{
System.out.println(ke);
}
});
Otherwise you have to check which kind of event it fires.
I was in a similar situation but with a bar-code scanner.
I really worked hard on a custom DocumentListener that would take care of all scenarios, and none of it worked.
Out of desperation, I added an ActionListener and it then worked very well.
Here is a code snap-shot :
try {
txtStockItemRef.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(txtStockItemRef.getText());
DatabaseManager.peformStockItemLookupByBarcodeRef(txtStockItemRef.getText());
}
});
} catch(Exception exc) {
LiveCityRetailTools.handleExceptionWithUserMessage(exc);
}