Why is my program calling showMessageDialog twice in ItemStateChanged event, even I put it in if else?
private void checkBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
if(evt.getStateChange() == ItemEvent.SELECTED){
//System.out.println("Check box 1 selected");
JOptionPane.showMessageDialog(null, "Check box 1 selected");
}
else{
//System.out.println("Check box 1 deselected");
JOptionPane.showMessageDialog(null, "Check box 1 deselected");
}
}
If I only use System.out.println, the program will run correctly.
The state of the checkbox is not being updated before the JOptionPane is displayed. (Notice how the checkmark is not painted when the first option pane is displayed.
So what you need to do is make sure the state is updated and repainted before displaying the JOption pane by using SwingUtilities.invokeLater(...) to display the JOptionPane:
checkBox.addItemListener( new ItemListener()
{
public void itemStateChanged(java.awt.event.ItemEvent evt)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if(evt.getStateChange() == ItemEvent.SELECTED)
{
JOptionPane.showMessageDialog(null, "Check box 1 selected");
}
else
{
JOptionPane.showMessageDialog(null, "Check box 1 deselected");
}
}
});
}
});
Related
I see this has been asked multiple times and apologize in advance if I'm just missing something simple...
I've created a custom JDialog with the examples provided in the Java docs here and from a similar question asked here.
My main application is a JFrame that contains a JPanel with an array of JButtons that display various employee names. I've added a custom ActionListener to each JButton that calls the mentioned JDialog:
//inner class for handling user button pushes
private class UserButtonHandler implements ActionListener
{
//handle button event
#Override
public void actionPerformed(ActionEvent event)
{
statusDialog = new ChangeDialog(statusWindow);
statusDialog.setVisible(true);
statusDialog.setLocationRelativeTo(null);
//set title for dialog box
String dialogTitle = "Status change for " + event.getActionCommand();
statusDialog.setTitle(dialogTitle);
statNum = ((ChangeDialog) statusDialog).getInputStatus();
System.out.println("Current num is: " + statNum);
//statNum = statusDialog.getInputStatus();
}
}
Here is the class for the custom JDialog (ChangeDialog):
class ChangeDialog extends JDialog implements ActionListener, PropertyChangeListener
{
//create panel where users can modify their status
private final ChangePanel empStatusChangePanel;
//text of buttons in dialog
private String btnString1 = "OK";
private String btnString2 = "Cancel";
private String btnString3 = "Clear Time-Off";
private JOptionPane statusPane;
//determines message to return for user input
private int inputStatus;
public ChangeDialog(JFrame statusFrame)
{
empStatusChangePanel = new ChangePanel();
//create an array specifying the number
//of dialog buttons and their text
Object[] options = {btnString1, btnString2, btnString3};
//create the JOptionPane
statusPane = new JOptionPane(empStatusChangePanel,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.YES_NO_CANCEL_OPTION,
null,
options,
options[0]);
//set contents of dialog
setContentPane(statusPane);
//handle window closing
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//register event handler for changes in status pane state
statusPane.addPropertyChangeListener(this);
pack();
}
#Override
public void actionPerformed(ActionEvent e)
{
statusPane.setValue(btnString1);
}
#Override
public void propertyChange(PropertyChangeEvent e)
{
String prop = e.getPropertyName();
if (isVisible()
&& (e.getSource() == statusPane)
&& (JOptionPane.VALUE_PROPERTY.equals(prop)))
{
Object value = statusPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE)
{
//ignore reset
return;
}
//Reset the JOptionPane's value. If this is not done,
//then if the user presses the same button next time,
//no property change event will be fired
statusPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
if(value.equals(btnString1)) //user clicked "OK"
{
//validation of user input
inputStatus = empStatusChangePanel.validateUserInput();
//handle validation results
switch (inputStatus)
{
case 0: //user input is good
JOptionPane.showMessageDialog(this, "Good input given");
dispose();
break;
case 1: //one (or both) of the date pickers are empty
JOptionPane.showMessageDialog(this, "PTO pickers can't be empty.",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
case 2:
case 3: //bad date range (start before end or visa-versa)
JOptionPane.showMessageDialog(this, "Bad date range.",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
case 99: //dates are equal
JOptionPane.showMessageDialog(this, "Single-day PTO");
dispose();
break;
}
}
else if(value.equals(btnString3)) //user clicked "Clear Input"
{
JOptionPane.showMessageDialog(this, "User clicked 'clear input");
//more processing should be done here
empStatusChangePanel.recycle();
//dispose();
}
else //user clicked "Cancel" or closed dialog
{
JOptionPane.showMessageDialog(this, "User closed status window");
dispose();
}
}
}
//returns value from user validation
public int getInputStatus()
{
return inputStatus;
}
}
I need to access the method getInputStatus from the custom dialog but each attempt I've tried comes back stating that:
getInputStatus is undefined for the type JDialog
I have looked at several other similar posts but feel that I'm missing something fundamental in trying to solve this problem (or I've been looking at the code too long).
Another thing that has me stumped (and why I left it in the first snippet) is that if I cast the method to the type ChangeDialog
statNum = ((ChangeDialog) statusDialog).getInputStatus();
It suddenly has access (this was a suggestion from Eclipse and doesn't make sense to me). Thanks again for any and all help.
That is how inheritance works, you have defined statusDialog as a JDialog reference and JDialog doesn't have a getInputStatus method.
To access the members of ChangeDialog, you have to define statusDialog as variable of ChangeDialog.
public static int clickOnExit() {
int dialogButton=JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog(null, sharedConstants.exitMessage,"Confirm",dialogButton);
if(dialogButton == JOptionPane.YES_OPTION){return JFrame.EXIT_ON_CLOSE;}
else{return JFrame.DO_NOTHING_ON_CLOSE;}
}
for confirm(YES) it works, but i am not sure if cancel option is solved properly. i just want to cancel JOptionPane and keep frame opened.
You need to do three things:
Set your main application frame to do nothing on close.
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
Register a WindowListener that listens to the windowClosing event.
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
maybeExit(); // Will not return if user clicks yes.
super.windowClosing(e);
}
});
Write code to conditionally call System.exit if the user confirms they wish to exit the application.
private void maybeExit() {
int yesNo = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (yesNo == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
Some suggestions were useful. I solved it in this way:
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (HandlingDialogBox.clickOnExit(frame) == 0) {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
} else {
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
});
}
AND
public static int clickOnExit(final JFrame frame) {
return JOptionPane.showConfirmDialog(frame,sharedConstants.exitMessage,"Confirm",
JOptionPane.YES_NO_OPTION);
}
Sorry for bit messy parenthesis use, will clean that up later ...
Its my first time programming checkboxes; I figured out how to make a checkbox appear, and do a command when checked. However, when the box is unchecked, instead of undoing the command, it instead does the command a second time. How can I undo the command when unchecking the box?
Code: (instantiation of checkboxes)
negA = new JCheckBox("Neg");
negA.addActionListener(this);
negA.setActionCommand("A-5");
tossupA = new JCheckBox("Tossup");
tossupA.addActionListener(this);
tossupA.setActionCommand("A10");
powerA = new JCheckBox("Power");
powerA.addActionListener(this);
powerA.setActionCommand("A05");
Command:
public void actionPerformed(ActionEvent e)
{
//get the String value from the button pressed
String result = e.getActionCommand();
char team = result.charAt(0);
//set text on screen to reflect new score
String screenText = "Team "+(team)+"'s total score for this tossup: ";
//add score to subtotal and show on screentext
if(team=='A'){
teamATempScore += Integer.parseInt(result.substring(1));
screenText += teamATempScore;
}
//and now for B
else if(team=='B'){
teamBTempScore += Integer.parseInt(result.substring(1));
screenText += teamBTempScore;
}
When the box is unchecked, I want the score to decrement by the amount that it was incremented, but instead the score just increments again :(
Thanks!
(yes, if you were wondering, this is a scorekeeping program for a game of Quizbowl) :D
The listener just checks to see if the checkBox was clicked -- It doesn't check if it went from unchecked to checked, or vice versa.
Use the .isSelected() method to determine whether the checkbox is checked or not after it becomes clicked.
For example:
if (negA.isSelected())
{
//the checkbox was checked after they clicked it, do something
}
else
{
//the checkbox was unchecked after they clicked it, do something else
}
You have to check the state of the control and then either increment or decrement. The compiler cannot auto generate the reverse of your code.
To check the state of the checkbox, you call the isSelected() method on it like in the example below.
import javax.swing.JOptionPane;
public class CheckboxExample extends javax.swing.JFrame {
private javax.swing.JCheckBox jCheckBox1;
public CheckboxExample() {
jCheckBox1 = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jCheckBox1.setText("CheckMe");
jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox1ActionPerformed(evt);
}
});
getContentPane().add(jCheckBox1);
pack();
}
// this will get called when the state of the checkbox changes
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jCheckBox1.isSelected()) {
JOptionPane.showMessageDialog(this, "Checked", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this, "Unchecked", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CheckboxExample().setVisible(true);
}
});
}
}
I have a login form with 2 JTextFields - one "elbtUser" the other "pass" (username and password) and everything works. I want to show a message as shown below if username is left empty and pass is clicked else the button will enable. It works but the message keeps repeating in an endless loop. How to I get back to form break out?
pass.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
if(elbtUser.getText().equals("")) {
JOptionPane.showMessageDialog(null, "username cannot be empty");
}
else {
btnLogin.setEnabled(true);
}
}
});
I can't say for 100% certainty, but I'm guessing after the dialog is closed the text field regains focus and triggers the action listener. If this is the case, try 1 of two things:
1) add a variable to keep state and when the dialog should be shown. Once on focus gained, and then it should be reset when elbtUser gains focus.
2) You can force elbtUser to request focus after dialog is shown, elbtUser.requestFocus();
//edit.. i Just tried (1) as it seemed easier and it works,
pass.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
if(elbtUser.getText().equals("")) {
//do this *BEFORE* displaying the dialog!!!
elbtUser.requestFocus(false);
JOptionPane.showMessageDialog(null, "username cannot be empty");
}
else {
}
}
});
I want to Stop accidentally closings in my project. I'm using JFrame Form as Home page. When I click Home window's close button I put Exit cord in Yes Option. I want to stop closing when I click No Option. Is there any way. Here is my cord. I'm using netbeans 7.3
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int i= JOptionPane.showConfirmDialog(null, "Are you sure to exit?");
if (i == JOptionPane.YES_OPTION) {
System.exit(0);
} else{
new Home().setVisible(true);
}
}
How about
class MyGUI extends JFrame {
public MyGUI() {
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// <- don't close window
// when [X] is pressed
final MyGUI gui = this;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int i = JOptionPane.showConfirmDialog(gui,
"Are you sure to exit?", "Closing dialog",
JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
setSize(200, 200);
setVisible(true);
}
//demo
public static void main(String[] args) {
new MyGUI();
}
}
You can simply do that like this
Integer opt = JOptionPane.showConfirmDialog(null, "This application cannot continue without login to the database\n Are you sure you need to exit...?", "Application X", JOptionPane.YES_NO_OPTION);
if(opt== JOptionPane.NO_OPTION){
this.setVisible(true);
}else{
System.exit(0);
}