Make a conditional in a JDialog - java

I'm trying to put a conditional in a JDialog which detect if the two buttons in it are disabled. I need that also to close the dialog when it reach this condition so I found 2 problems. Example code:
public static String windowvisitAlert(JButton but, JButton but2, String message1, String message2) throws Exception, Exception {
String n = "";
Object[] options = {but, but2};
Object a = message1;
JOptionPane pane = new JOptionPane(a, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
JDialog dialog = pane.createDialog(message2);
dialog.setContentPane(pane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setSize(new Dimension(450, 10));
dialog.pack();
dialog.setVisible(true);
return n;
}
This is the method which creates a JDialog from a JPanel options. We have 2 buttons and 2 "messages" which only determinates the name of the dialog window.
I tried to put :
if (but.isEnabled()==false && but2.isEnabled()==false) {
dialog.setVisible(false);
}else{
dialog.setVisible(true);}
Also this method will return the value n so I don't know how will a condition work inside it.
Where i implement this method:
public void actionPerformed(ActionEvent e) {
final JButton but = new JButton("VISITA");
final JButton but2 = new JButton("RESPONSABLE");
try {
ActionListener actionListener2 = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//action performed
}
};
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//action performed
}
};
but.addActionListener(actionListener2);
but2.addActionListener(actionListener);
Alerts.windowvisitAlert(but, but2, Gui.getProperties().getProperty("text"), Gui.getProperties().getProperty("text"));
}catch (Exception ex) {
sc.functionSavingInLog(Utils.getClassInfo(Thread.currentThread().getStackTrace()[1]), ex.toString());
System.out.println(Utils.getClassInfo(Thread.currentThread().getStackTrace()[1]) + ex);
}
}
This is actually not working so my question is:
-How can I make this condition work and make the JDialog close when it hits it?
If not, how can I change the method or just do a jpanel?

Related

Adding a 3rd button to JOptionPane drop down menu

I am relatively new to Java and have been trying to figure out a way to create a JOption window that not only has a drop down option with an "Ok" and "Cancel" button, but also adds an additional button called "Back." So far none of my attempts have successfully been able to add this Back button and every time I run the code it simply brings up the traditional dropdown/ok/cancel type window. Additionally I would also like the window to close when a button has been clicked, but I have been unsuccessful in that as well. Here is the code I have so far, not entirely sure what's missing/wrong with it:
public static String sampleWindow(){
JButton jbt_ok = new JButton("OK");
JButton jbt_back = new JButton("Back");
JButton jbt_cancel = new JButton("Cancel");
boolean greyOutBackButton = false;
jbt_ok.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("OK was clicked");
}
});
jbt_cancel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Cancel was clicked");
}
});
if(greyOutBackButton)
jbt_back.setEnabled(false);
else
jbt_back.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Back was clicked");
}
});
Object[] options = {jbt_ok, jbt_back, jbt_cancel};
Object selectionObject = JOptionPane.showInputDialog(null, "message", "", JOptionPane.DEFAULT_OPTION, null, options, options[0]);
if (selectionObject == null)
System.exit(0);
String selectionString = selectionObject.toString();
System.out.println("Selection String: "+ selectionString);
return selectionString;
}

how to get a value from a Jcombobox array using a anonymous class

I have a array of Jradiobuttons.i am trying to have java anonymous class that implement ActionListener so when the user press on a radio button I can do something but since this is an array i cant give the array index using a while loop so how to identify what Jradiobutton I am using.and I want to get the text of that radio button and save it in a another variable...How can I do this?
This is what so far I have done :
if(count!=0) {
rs=pst.executeQuery();
JRadioButton a []=new JRadioButton[count];
jPanel3.setLayout(new GridLayout());
int x=0;
ButtonGroup bg=new ButtonGroup();
while(rs.next()) {
a[x]=new JRadioButton(rs.getString("name"));
bg.add(a[x]);
jPanel3.add(a[x]);
a[x].setVisible(true);
a[x].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,a[x].getText()); //here i cant use this x...even though i make x global value of x always will be 6 becouse of while loop.
}
});
x++;
}
}
If i understand you correctly, You can set the name of radio button:
a[x]=new JRadioButton(rs.getString("name"));
a[x].setName(rs.getString("name"));
and in ActionPerformed you get the source of action:
public void actionPerformed(ActionEvent e) {
if( e.getSource() instanceof JRadioButton){
String selectedRadioName = ((JRadioButton) e.getSource()).getName();
JOptionPane.showMessageDialog( null, selectedRadioName );
}
You could...
Supply each JRadioButton with a ActionCommand which will be made available via the ActionEvent
a[x]=new JRadioButton(rs.getString("name"));
a[x].setActionCommand(String.valueOf(x));
//...
a[x].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
int value = Integer.parseInt(cmd);
JOptionPane.showMessageDialog(null, a[value].getText());
}
});
See How to Use Buttons, Check Boxes, and Radio Buttons for more details
You could...
Use the Action API to surround the message and action in a self contained unit of work...
public class MessageAction extends AbstractAction {
private String message;
public MessageAction(String text, String message) {
this.message = message;
putValue(NAME, text);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, message);
}
}
And then apply it to your button something like...
a[x] = new JRadioButton(new MessageAction(rs.getString("name"), "Hello from " + x);
See How to Use Actions for more details.

Java swing CheckBox not selected while display Conformation Dialog

I am working on an application in which I have developed a window with three check boxes. When first and second check boxes are selected, new windows will be opened as desired. The third check box is for closing the application. When Exit check box is selected, it is showing the conformation Dialog as desired but Exit check box is not ticked.
I could not trace out the issue here. Please help me to resolve this issue!
package jcheckbox;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InitiaaWindow extends JPanel {
static JFrame frame = new JFrame("Credit Contract Validation");
private static final long serialVersionUID = 1L;
JCheckBox jValidateECOUT;
JCheckBox jValidateSuperDeals;
JCheckBox jEXIT;
JLabel jlbPicture,jlbPicture1;
CheckBoxListener myListener = null;
public InitiaaWindow() {
myListener = new CheckBoxListener();
jValidateECOUT = new JCheckBox("ValidateECOUT");
jValidateECOUT.setMnemonic(KeyEvent.VK_C);
jValidateECOUT.setSelected(false);
jValidateECOUT.addItemListener(myListener);
jValidateSuperDeals = new JCheckBox("ValidateSuperDeals");
jValidateSuperDeals.setMnemonic(KeyEvent.VK_G);
jValidateSuperDeals.setSelected(false);
jValidateSuperDeals.addItemListener(myListener);
jEXIT = new JCheckBox("EXIT");
jEXIT.setMnemonic(KeyEvent.VK_G);
jEXIT.setSelected(false);
jEXIT.addItemListener(myListener);
jlbPicture = new JLabel(new ImageIcon("src/jcheckbox/image.jpg"));
jlbPicture1 = new JLabel(new ImageIcon("src/jcheckbox/image1.jpg"));
JPanel jplCheckBox = new JPanel();
jplCheckBox.setLayout(new GridLayout(0, 1));
jplCheckBox.add(jValidateECOUT);
jplCheckBox.add(jValidateSuperDeals);
jplCheckBox.add(jEXIT);
setLayout(new BorderLayout());
add(jplCheckBox, BorderLayout.WEST);
add(jlbPicture1, BorderLayout.CENTER);
add(jlbPicture, BorderLayout.EAST);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
class CheckBoxListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (jValidateECOUT.isSelected())
{
try {
UIPack.UI.myMethod(null);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (jValidateSuperDeals.isSelected())
{
try {
ValidateSuperDealsUIPack.UI.ValidateSuperDealsUI(null);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (jEXIT.isSelected())
{
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Would you like to close the application", "Conformation message",dialogButton);
if(dialogResult==0)
System.exit(1);
else
JOptionPane.getRootFrame().dispose();
}
}
}
public static void main(String s[]) {
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new InitiaaWindow());
frame.pack();
frame.setVisible(true);
}
}
Since showConfirmDialog creates a modal dialog until the dialog is closed the execution of item selection event may not propagate to other listeners which might be responsible for updating the display of the checkbox.
If you click 'No' in the dialog, does the checkbox update properly? If yes then you can create the dialog in a separate runnable task using SwingUtilities.invokeLater this will ensure the current processing of selection event completes before the modal dialog is opned.
You can add
jEXIT.setSelected(true);
before
int dialogButton = JOptionPane.YES_NO_OPTION;
1.Sorry, but your code style is really terrible (IMHO, I don't want you to be dissappointed of that).
2.Use ActionListener instead of ItemListener for JCheckBox. And check the source of action before process it:
ActionListener listener = new ActionListener({
#Override
public void actionPerfomed(ActionEvent ae) {
if (ae.getSource().equals(comboBox1) {
//process 1
} else if (ae.getSource().equals(comboBox2) {
//process 2
} else if (ae.getSource().equals(comboBox3) {
//process 3
}
}
});
comboBox1.add(listener);
comboBox2.add(listener);
comboBox3.add(listener);
3.If you want to show modal dialogs on action events, it is good to use SwingUtilities.invokeLater() for that, because your action' source should repaint after action perfomed.

JOptionPane Passing Custom Buttons

I'm trying to get the value returned by custom buttons passed to JOptionPane. However the buttons I pass don't return a value at all. Only when the exit button is pressed is a value of -1 returned. I need this because I am changing the properties of the buttons enabled or disabled. I assume I need the buttons to return some information to the JOptionPane in some way. Any idea?
JButton button1= new JButton("Button 1");
JButton button2= new JButton("Button 2");
button1.setEnabled(false);
int value = JOptionPane.showOptionDialog(null, "Heres a test message", "Test", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{button1, button2}, button1);
JOptionPane.showMessageDialog(null, "You entered " + value);
Nb This is related to my previous question - JOptionPane Grey Out One Button
I tried setting the value of the buttons like you said but they never return OK or CANCEL.
Whenever checking the value of the buttons, they never return the value I set them too.
JButton button1= new JButton("Button1");
JButton button2= new JButton("Button2");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
// set the value of the option pane
pane.setValue(JOptionPane.OK_OPTION);
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
// set the value of the option pane
pane.setValue(JOptionPane.CANCEL_OPTION);
}
});
if (JOptionPane.showOptionDialog(null, "Pick a button", "Pick", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{button1, button2}, button1) == JOptionPane.OK_OPTION) {
JOptionPane.showMessageDialog(null, "Button1");
}
else{
JOptionPane.showMessageDialog(null, "Button2");
}
See above, always I get the button2 popup no matter what.
In the example I linked to you previous question, the buttons use the JOptionPane#setValue method to set the return value. This allows you to continue using the API as normal, while providing you with the customisation your after.
final JButton okay = new JButton("Ok");
okay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
// set the value of the option pane
pane.setValue(JOptionPane.OK_OPTION);
}
});
Take a closer look at Disable ok button on JOptionPane.dialog until user gives an input
Updated
I've gone back through the code and correct the actionPerformed methods to enable it to return a valid value...
final JButton okay = new JButton("Ok");
okay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
pane.setValue(okay);
}
});
okay.setEnabled(false);
final JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
pane.setValue(cancel);
}
});
The value returned by the index of the value in the options array (last parameter)
So, for example...
int value = JOptionPane.showOptionDialog(
null,
field,
"Get",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
new Object[]{okay, cancel},
okay);
If the user clicks the okay button, the return value will be 0, or if they select the cancel button, it will be 1
If you need this complex behavior, consider creating your own JDialog and then displaying it in a modal fashion.
If you have to use a JOptionPane, you can do this by extracting its JDialog and recursively iterating through its components til you find the one you want to disable and disable it:
import java.awt.Component;
import java.awt.Container;
import javax.swing.*;
public class Foo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
doRun();
}
});
}
public static void doRun() {
String[] options = {"Button 1", "Button 2", "Button 3"};
JOptionPane myOptionPane = new JOptionPane("Heres a test message",
JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION,
null, options, options[2]);
JDialog myDialog = myOptionPane.createDialog(null, "My Test");
myDialog.setModal(true);
inactivateOption(myDialog, options[1]);
myDialog.setVisible(true);
Object result = myOptionPane.getValue();
// Note: result might be null if the option is cancelled
System.out.println("result: " + result);
System.exit(0); // to stop Swing event thread
}
private static void inactivateOption(Container container, String text) {
Component[] comps = container.getComponents();
for (Component comp : comps) {
if (comp instanceof AbstractButton) {
AbstractButton btn = (AbstractButton) comp;
if (btn.getActionCommand().equals(text)) {
btn.setEnabled(false);
return;
}
} else if (comp instanceof Container) {
inactivateOption((Container) comp, text);
}
}
}
}
However for myself, I'd just create a JDialog.
You don't have to define your buttons explicitly.
int result = JOptionPane.showOptionDialog(this, "Are you sure you want to...?", "Title", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] { "Yes", "No" }, JOptionPane.NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
...
}

JOptionPane.showMessageDialog wait until OK is clicked?

This might be a very simple thing that I'm overlooking, but I just can't seem to figure it out.
I have the following method that updates a JTable:
class TableModel extends AbstractTableModel {
public void updateTable() {
try {
// update table here
...
} catch (NullPointerException npe) {
isOpenDialog = true;
JOptionPane.showMessageDialog(null, "No active shares found on this IP!");
isOpenDialog = false;
}
}
}
However, I don't want isOpenDialog boolean to be set to false until the OK button on the message dialog is pressed, because if a user presses enter it will activate a KeyListener event on a textfield and it triggers that entire block of code again if it's set to false.
Part of the KeyListener code is shown below:
public class KeyReleased implements KeyListener {
...
#Override
public void keyReleased(KeyEvent ke) {
if(txtIPField.getText().matches(IPADDRESS_PATTERN)) {
validIP = true;
} else {
validIP = false;
}
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
if (validIP && !isOpenDialog) {
updateTable();
}
}
}
}
Does JOptionPane.showMessageDialog() have some sort of mechanism that prevents executing the next line until the OK button is pressed? Thank you.
The JOptionPane creates a modal dialog and so the line beyond it will by design not be called until the dialog has been dealt with (either one of the buttons have been pushed or the close menu button has been pressed).
More important, you shouldn't be using a KeyListener for this sort of thing. If you want to have a JTextField listen for press of the enter key, add an ActionListener to it.
An easy work around to suite your needs is the use of showConfirmDialog(...), over showMessageDialog(), this lets you take the input from the user and then proceed likewise. Do have a look at this example program, for clarification :-)
import javax.swing.*;
public class JOptionExample
{
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
int selection = JOptionPane.showConfirmDialog(
null
, "No active shares found on this IP!"
, "Selection : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.INFORMATION_MESSAGE);
System.out.println("I be written" +
" after you close, the JOptionPane");
if (selection == JOptionPane.OK_OPTION)
{
// Code to use when OK is PRESSED.
System.out.println("Selected Option is OK : " + selection);
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
// Code to use when CANCEL is PRESSED.
System.out.println("Selected Option Is CANCEL : " + selection);
}
}
});
}
}
You can get acces to the OK button if you create optionpanel and custom dialog. Here's an example of this kind of implementation:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author OZBORN
*/
public class TestyDialog {
static JFrame okno;
static JPanel panel;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
zrobOkno();
JButton przycisk =new JButton("Dialog");
przycisk.setSize(200,200);
panel.add(przycisk,BorderLayout.CENTER);
panel.setCursor(null);
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
przycisk.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor"));
final JOptionPane optionPane = new JOptionPane(
"U can close this dialog\n"
+ "by pressing ok button, close frame button or by clicking outside of the dialog box.\n"
+"Every time there will be action defined in the windowLostFocus function"
+ "Do you understand?",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION);
System.out.println(optionPane.getComponentCount());
przycisk.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
final JFrame aa=new JFrame();
final JDialog dialog = new JDialog(aa,"Click a button",false);
((JButton)((JPanel)optionPane.getComponents()[1]).getComponent(0)).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
aa.dispose();
}
});
dialog.setContentPane(optionPane);
dialog.pack();
dialog.addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Zamykam");
aa.dispose();
}
#Override public void windowGainedFocus(WindowEvent e) {}
});
dialog.setVisible(true);
}
});
}
public static void zrobOkno(){
okno=new JFrame("Testy okno");
okno.setLocationRelativeTo(null);
okno.setSize(200,200);
okno.setPreferredSize(new Dimension(200,200));
okno.setVisible(true);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel();
panel.setPreferredSize(new Dimension(200,200));
panel.setLayout(new BorderLayout());
okno.add(panel);
}
}
Try this,
catch(NullPointerException ex){
Thread t = new Thread(new Runnable(){
public void run(){
isOpenDialog = true;
JOptionPane.setMessageDialog(Title,Content);
}
});
t.start();
t.join(); // Join will make the thread wait for t to finish its run method, before
executing the below lines
isOpenDialog = false;
}

Categories