Adding a 3rd button to JOptionPane drop down menu - java

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

Related

Java Swing how to define multiple focus listeners on JTextFields but with different button actions

I am making JTextFields which should be populated when click on a button.
Suppose for an example:
txtField1.addFocusListener(new FocusListener() {
JTextField field = txtField1;
#Override
public void focusGained(FocusEvent e) {
btnMain_0.addActionListener(ee -> {
if (field.getText().length() > 4)
return;
else
field.setText((field.getText() + "0"));
});
}
#Override
public void focusLost(FocusEvent e) {
}
});
txtField2.addFocusListener(new FocusListener() {
JTextField field = txtField2;
#Override
public void focusGained(FocusEvent e) {
btnMain_0.addActionListener(ee -> {
if (field.getText().length() > 4)
return;
else
field.setText((field.getText() + "0"));
});
}
#Override
public void focusLost(FocusEvent e) {
}
});
But if I click on txtField1 and press btnMain_0, it enter 0.
Then if I click on txtField2 and press btnMain_0, it enter 00 (it considered pressing btnMain_0 two times).
How I can make it? Is there better solution two run listeners from list of jtextfields?
You can define a custom TextAction and add it to your buttons.
The TextAction allows you to track the last text component that had focus (before you click on the button).
Something like:
class KeyboardAction extends TextAction
{
private String letter;
public KeyboardAction(String letter)
{
super(letter);
this.letter = letter;
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.setCaretPosition( component.getDocument().getLength() );
component.replaceSelection( letter );
}
}
You then use the class like:
jButton1 = new JButton( new KeyboardAction("1") );
jButton2 = new JButton( new KeyboardAction("2") );
or you add the Action to an existing button by using:
button.setAction( new KeyboardAction("1") );

Make a conditional in a JDialog

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?

Add two buttons if another button has been pressed

b.button1 = new JButton("Deal");
b.button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//code
b.button2 = new JButton("Hit");
panel.add(b.button2);
panel.validate();
b.button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//code
}
});
b.button3 = new JButton("Stay");
panel.add(b.button3);
panel.validate();
b.button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//code
}
}
});
So I want The Buttons Hit and Stay to be added as soon as the Deal button has been pressed. I searched for a solution and found the panel.validate() method. I used it but now if I press the Deal button it only adds the Hit button.
You could add the buttons before and make them "hidden". If you press the button, you can "show" them to include them.

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