Handling exit button which is create automatically? - java

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
}
}
});

Related

How can I create Enter event when I want to click on button, without using class Robot?

How can I create Enter event when I want to click on button, without using class Robot? I have already created a form and I create button btnMainOk.
I've tried to use keyListener but it's not working.
btnMainOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btnMainOk.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
}
}
});
}
});
The goal is when I click with my mouse device on button, that button should act like I pressed enter key on my keyboard.

How to enable / disable buttons in java, eclipse?

How can I disable buttons with the press of one button and when the task that the button which has been pressed was assigned to has been done then I want all the buttons to be enabled. for example;
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Up Button");
}
});
DownButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Down Button");
}
});
LeftButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
UpButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Left Button");
}
});
RightButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
UpButton.setEnabled(false);
System.out.printline("Right Button");
}
});
I have tried to do it but it does not work. What I want is, for example, my Upbutton is printing out ("Up button"), so when a user presses this button I want all the other buttons to be disabled until it has finished doing the command that it was suppose to do, in this case print out a text but later on I will be adding things like adding up two user inputs e.g. I will have a button that will ask the user to type number 1 and then number 2 and then the computer will add them up and during this process I want all the buttons to be disabled expect the one that has been clicked on, until the user has given all numbers and the computer has given the output.
I hope I have explained myself properly, if not please let me know and I will try my best to give more information. Thanks in advance.
How about using Command objects? Each command object might have execute() and canExecute() methods at least. Then;
btnA.setEnabled( cmdA.canExecute() );
btnA.addActionListener( event-> {
cmdA.execute();
btnB.setEnabled( cmdA.canExecute() );
});
That seems right. Maybe you want them invisible instead of disabled...
In that case:
LeftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setVisible(false);
UpButton.setVisible(false);
RightButton.setVisible(false);
System.out.printline("Left Button");
HereĀ“s an example of something that works:
private void jButtonChangeChampActionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxPlayer.setEnabled(true);
jComboBoxChampion.setEnabled(true);
jButtonSelecionar.setVisible(true);
jButtonMagias.setVisible(false);
}
What if you try this:
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpButtonActionPerformed(evt);
}
});
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Up Button");
}
It works here...
If you want to Set the Button Disabled , You can use the
btnExample.setDisable(true); // This will disable the Button
btnBreak.setVisible(false); // This will make the button Disappear visually only.
Hope this help guys.
You have to first disable the other buttons, finish your task and then enable the buttons again.
For example:
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
// first disable all other buttons
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.println("Up Button");
// do rest of your tasks here.
// now enable them again
DownButton.setEnabled(true);
LeftButton.setEnabled(true);
RightButton.setEnabled(true);
}
});
Similarly, setup the Listeners for the other buttons.
Hope this helps!

How to Save before Exit Java

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);
}

How to delete text when a user clicks a JTextField?

In my program, the user writes something in a JTextField then clicks a 'generate' button, which triggers the characters in the JTextField to be drawn to a JPanel.
I would then like to clear all the text in the JTextField when the user clicks the JTextField again. I tried to achieve this by adding a FocusListener and an ActionListener to the JTextField, however my attempts did not work. Moreover, my implementation of the FocusListener gave an Unreachable Statement compiler error.
Is this possible to do in Java and if so how can I do this?
The code below is my ActionListener implementation.
dfaText = new JTextField(6);
dfaText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
generateLabel.setText("NOOOOO!!!");
dfaText.setText("");
isDfaDrawn = false;
canDraw = false;
repaint();
}
});
Add a mouse listener:
field.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
field.setText("");
}
});
Bear in mind this could get frustrating if the user legitimately clicks elsewhere and returns to the field. You may wish to maintain some state, e.g. only clear the field if the button has been clicked in the interim.
You can do this:
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField.setText("");
}
});
Just an addition to others' code.
public void textfieldMouseClicked(java.awt.event.MouseEvent evt) {
uname_tf.setText(null);
} //This will set the JTextfield blank on mouse click//
public void textfieldFocusLost(java.awt.event.FocusEvent evt) {
uname_tf.setText("Username");
} //This will bring back the default text when not in focus//
Hope it helps, Cheers!!!
If you want it just one Click on it to delete the text you can do like this :
textField.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
textFieldMousePressed(evt);
}
});
private void textFieldMousePressed(java.awt.event.MouseEvent evt) {
textField.setText("");
}
Add 1 line to you buttonMethod e.g:
txtfield.clear();
or set your txtfield to an empty string

action listening for a JFrame

I am trying to listen tab-in tab-out action for my swing gui that is made by JFrame. I have a JTextField added to the JFrame that will be getting the user clipboard whenever the window is selected so the user may tab between programs, copy some url so when back to my program, this JTextField will be populated by the copied url string.
EDIT:
I have tried this:
frame.addFocusListener(
new FocusListener() {
public void focusGained(FocusEvent e) {
url= getClipboardData();
}
#Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
}
);
it doesnt work
A frame doesn't recieve a focus event. A component on the frame gets the focus event.
If you want to know when a frame gets focus then use a WindowListener and handle the windowActivated event.
What you want is a FocusListener not an ActionListener. Check out the java Doc and you'll know how to use it. It's easy.
it looks like you are not setting the clipboard data onto the text field.
frame.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
getJTextField().setText(getClipboardData());
}
public void focusLost(FocusEvent e) {
//ignored
}
});
Something like that will likely solve your problem

Categories