I have learnt to create a menu with radio buttons using java, but I want to know how to make radio buttons WITHIN radio buttons. The real problem is that I have finally created the radio buttons 'within' a radio button by displaying a new menu with a new group of buttons, but whenever I click on these new radio buttons, nothing happens. It is as if the buttons are not being listened to. Here is my code (example, but still the same idea):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestRadioButtons extends JPanel implements ActionListener
{
private String test = "Test Button 1";
private String random = "RANDOM";
private String test2 = "Button to Click";
private String random2 = "RANDOM MK. 2";
private static boolean menu = false;
public TestRadioButtons()
{
super(new BorderLayout());
//creates first set of radio buttons
JRadioButton testButton = new JRadioButton(test);
testButton.setMnemonic(KeyEvent.VK_T);
testButton.setActionCommand(test);
JRadioButton randomButton = new JRadioButton(random);
randomButton.setMnemonic(KeyEvent.VK_R);
randomButton.setActionCommand(random);
//groups the first set of buttons
ButtonGroup group1 = new ButtonGroup();
group1.add(testButton);
group1.add(randomButton);
//register listener for first radio buttons
testButton.addActionListener(this);
randomButton.addActionListener(this);
//put first radio buttons into a column in a panel
JPanel radioPanel1 = new JPanel(new GridLayout(0, 1));
radioPanel1.add(testButton);
radioPanel1.add(randomButton);
//set first menu border
add(radioPanel1, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,250));
//I also have it so that if the a boolean value equals true, the following menu appears:
if (menu == true)
{
JRadioButton test2Button = new JRadioButton(test2);
test2Button.setMnemonic(KeyEvent.VK_A);
test2Button.setActionCommand(test2);
JRadioButton random2Button = new JRadioButton(random2);
random2Button.setMnemonic(KeyEvent.VK_B);
random2Button.setActionCommand(random2);
ButtonGroup group2 = new ButtonGroup();
group2.add(test2Button);
group2.add(random2Button);
test2Button.addActionListener(this);
random2Button.addActionListener(this);
JPanel radioPanel2 = new JPanel(new GridLayout(0, 1));
radioPanel2.add(test2Button);
radioPanel2.add(random2Button);
add(radioPanel2, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,250));
}
}
public static void menu2()
{
JFrame innerMenu = new JFrame();
innerMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent innerComponent = new TestRadioButtons();
innerComponent.setOpaque(true);
innerMenu.setContentPane(innerComponent);
innerMenu.pack();
innerMenu.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (test.equals(e.getActionCommand()))
{
menu = true;
menu2();
if (test2.equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(null, "This is just a TEST!");
}
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Radio Button Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent component = new TestRadioButtons();
component.setOpaque(true);
frame.setContentPane(component);
frame.pack();
frame.setVisible(true);
}
public static void main (String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If anyone is able to help me (as well as fix up my code in the part where I create the new menu), I would be grateful.
Just a } problem
Change your public void actionPerformed(ActionEvent e) like this
public void actionPerformed(ActionEvent e)
{
if (test.equals(e.getActionCommand()))
{
menu = true;
menu2();
}
if (test2.equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(null, "This is just a TEST!");
}
}
Related
This code not work properly. When I select male, every time it select female automatically?
How to validate radio button for gender?
rbtnmale = new JRadioButton("male");
rbtnmale.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
gender="male";
rbtnmale.setSelected(true);
rbtnmale.setSelected(false);
}
});
rbtnmale.setBounds(116, 127, 58, 23);
frame.getContentPane().add(rbtnmale);
rbtnfemale = new JRadioButton("female");
rbtnfemale.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
gender="female";
rbtnfemale.setSelected(true);
rbtnmale.setSelected(false);
}
});
You should be using ButtonGroup, put all of your JRadioButtons in it and then loop through buttonGroup.getElements() to find which JRadioButton is selected. Here is a complete example:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class Example {
ButtonGroup group = new ButtonGroup();//used to store all radio buttons.
public Example() {
initComponents();
currentSelectedOption();
}
private void initComponents() {
//Radio buttons
JRadioButton female = new JRadioButton("Female");
JRadioButton male = new JRadioButton("Male");
JRadioButton other = new JRadioButton("Other");
female.setSelected(true);//by default, select female.
//Add all radio buttons to a group.
//It will allow to only have one selected at a time.
group.add(male);
group.add(female);
group.add(other);
//Add your components to a panel, it's a good practice.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel.add(female);
panel.add(male);
panel.add(other);
JFrame frame = new JFrame("Example");
frame.setLayout(new BorderLayout());
frame.setLocationRelativeTo(null);
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
/**
* Getting the current selected radio button.
*
* #return Text of the radio button currently selected.
*/
public String getSelectedOption() {
Enumeration<AbstractButton> radioButtons = group.getElements();
while (radioButtons.hasMoreElements()) {
AbstractButton currentRadioButton = radioButtons.nextElement();
if (currentRadioButton.isSelected()) {
return currentRadioButton.getText();
}
}
return null;
}
private void currentSelectedOption() {
String selected = getSelectedOption();
if (selected == null) {
System.out.println("There is something wrong! Nothing is selected");
return;
}
switch (selected.toLowerCase()) {
case "male":
System.out.println("male is selected");
break;
case "female":
System.out.println("female is selected");
break;
case "other":
System.out.println("other is selected");
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
rbtnmale.setSelected(true);
rbtnmale.setSelected(false);
Based on your current code you want:
//rbtnmale.setSelected(false);
rbtnfemale.setSelected(false);
However you don't even need the above code in the ActionListener for either of the radio buttons.
Instead you should be using a ButtonGroup and the ButtonGroup will manage the selected state of each radio button for you:
ButtonGroup group = new ButtonGroup();
group.add(btnMale);
group.add(btnFemale);
Read the section from the Swing tutorial on How Use Buttons for more information
I want to have a random radio button to be selected whenever this panel gets initialized, but I'm not sure how/if I can do that.
Is there a way to get a random button from the group and select it?
import javax.swing.*;
public class RandomPanel extends JPanel
{
private ButtonGroup buttonGroup;
private String[] buttonText =
{
"Red",
"Mashed Potatoes",
"Metal",
"Running",
"Butts",
"Turquoise"
};
public RandomPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createTitledBorder("Random Selections"));
buttonGroup = new ButtonGroup();
for (String text : buttonText)
{
JRadioButton option = new JRadioButton(text);
add(option);
button.add(option);
}
}
}
What you can do is keep a list/array of all the radio buttons you create, and then set the selected by using the button group's setSelected() method, something like this
buttonGroup.setSelected(buttonsArray[randomButtonNum].getModel(), true);
Try using the Randomclass .
// Library location
import java.util.Random;
//Inside some method
Random r = new Random();
randomIndex = r.nextInt(buttonText.length());
text = buttonText[randomIndex];
This will need arranging to suit your implementation, whats shown is a 'how-to' usage.
Note: the argument to nextInt(args) is exclusive. i.e. will return
0 <= x < args
I believe you are looking for something like the solution below.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class RandomPanel extends JPanel
{
private ButtonGroup buttonGroup;
private String[] buttonText =
{
"Red",
"Mashed Potatoes",
"Metal",
"Running",
"Butts",
"Turquoise"
};
private JRadioButton[] radioButton;
Random r = new Random();
public RandomPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createTitledBorder("Random Selections"));
buttonGroup = new ButtonGroup();
radioButton = new JRadioButton[buttonText.length];
for(int rb=0; rb<buttonText.length; rb++)
{
radioButton[rb] = new JRadioButton(buttonText[rb]);
add(radioButton[rb]);
buttonGroup.add(radioButton[rb]);
}
JButton b = new JButton("Random");
b.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
selectRandomButton();
}
});
add(b);
}
public void selectRandomButton()
{
radioButton[r.nextInt(radioButton.length)].setSelected(true);
}
public static void main(String[] args)
{
JFrame f = new JFrame("Test Random Button");
f.setSize(300, 300);
f.setLocationRelativeTo(null);;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new RandomPanel());
f.setVisible(true);;
}
}
I created a small method that allow me to set any radio group button. Very convenient if you don't want to use if for any radio button.
public void setButtonGroup(int rdValue, Enumeration elements ){
while (elements.hasMoreElements()){
AbstractButton button = (AbstractButton)elements.nextElement();
if(Integer.parseInt(button.getActionCommand())==rdValue){
button.setSelected(true);
}
}
}
then
setButtonGroup(randomIndex, yourButtonGroup.getElements());
I am new to java and creating a Simple gui App. In this simple app, I am trying to write a e-commerce letter for Firms. So, I planned my app something like this..
First i ask to user if he want to write an letter to British Firm or American. For this i use two radio buttons(one for american firm and second for british) and JButton. When user Trigger jbutton then i want to get radiobutton command(which type of letter user want to write).
The problem is I don't have any idea to get Radiobutton command when i trigger jButton. Please give me an Simple Idea(if possible with exapmle not complicated for begginers) to get RadioButtons value..
Here is my java Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class englet{
static public JFrame f;
static public JPanel p;
static class getTypeOfLetter implements ActionListener{
public void actionPerformed( ActionEvent e){
String btnInput = e.getActionCommand();
System.out.println(btnInput);
}
}
public static void askletter(){
JRadioButton btnRadio1;
JRadioButton btnRadio2;
ButtonGroup btngrp;
JButton btnGo = new JButton("Write");
btnRadio1 = new JRadioButton("Write Letter For American Firm");
btnRadio1.setActionCommand("Amer");
btnRadio2 = new JRadioButton("Write Letter For British Firm");
btnRadio2.setActionCommand("Brit");
btngrp = new ButtonGroup();
btnGo.setActionCommand("WriteTest");
btnGo.addActionListener(new getTypeOfLetter());
btngrp.add(btnRadio1);
btngrp.add(btnRadio2);
p.add(btnRadio1);
p.add(btnRadio2);
p.add(btnGo);
}
englet(){
f = new JFrame("English Letter");
p = new JPanel();
askletter();
f.add(p);
f.setSize(400,200);
f.setVisible(true);
}
public static void main (String[] argv ){
englet i = new englet();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I am using Notepad++ and CMD.. Not any another tools like netbeans initllli ecplisse.
**RE-EDIT ** I want a possible solution and can satisfy me.. this app works but i am not able to get radiobuttons commmand with jubtton..
You've got several issues:
Over-use of static. Most of the fields and methods of your code should be non-static
You're missing key fields that will be necessary to transmit the information needed. To get the selected JRadioButton, you need to make JRadioButton fields and check which is selected, or (and my preference), you need to make the ButtonGroup variable a field and check which JRadioButton has been selected based on the ButtonModel returned by the ButtonGroup.
You're currently using local variables and these won't be visible throughout the class, which is why either the JRadioButtons or the ButtonModel most be fields (declared in the class).
If you go with ButtonModel above, you must give each JRadioButton an appropriate actionCommand String.
For example:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GetRadio extends JPanel {
private static final String[] FIRMS = {"American Firm", "British Firm"};
// You need this field to access it in your listener
private ButtonGroup buttonGroup = new ButtonGroup();
public GetRadio() {
// create JButton and add ActionListener
JButton button = new JButton("Select");
button.addActionListener(new ButtonListener());
// JPanel with a grid layout with one column and variable number of rows
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
radioButtonPanel.setBorder(BorderFactory.createTitledBorder("Select Firm")); // give it a title
for (String firm : FIRMS) {
// create radiobutton and set actionCommand
JRadioButton radioButton = new JRadioButton(firm);
radioButton.setActionCommand(firm);
// add to button group and JPanel
buttonGroup.add(radioButton);;
radioButtonPanel.add(radioButton);
}
// add stuff to main JPanel
add(radioButtonPanel);
add(button);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// get button model of selected radio button from ButtonGroup
ButtonModel model = buttonGroup.getSelection();
// if null, no country selected
if (model == null) {
Component component = GetRadio.this;
String message = "You must first select a country!";
String title = "Error: No Country Selected";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(component, message, title, type);
} else {
// valid country selected
String country = model.getActionCommand();
System.out.println("Letter to " + country);
}
}
}
private static void createAndShowGui() {
GetRadio mainPanel = new GetRadio();
JFrame frame = new JFrame("Get Radio Btn");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I have main application where is table with values. Then, I click "Add" button, new CUSTOM (I made it myself) JDialog type popup comes up. There I can input value, make some ticks and click "Confirm". So I need to read that input from dialog, so I can add this value to table in main application.
How can I listen when "confirm" button is pressed, so I can read that value after that?
addISDialog = new AddISDialog();
addISDialog.setVisible(true);
addISDialog.setLocationRelativeTo(null);
//somekind of listener...
//after "Confirm" button in dialog was pressed, get value
value = addISDialog.ISName;
If the dialog will disappear after the user presses confirm:
and you wish to have the dialog behave as a modal JDialog, then it's easy, since you know where in the code your program will be as soon as the user is done dealing with the dialog -- it will be right after you call setVisible(true) on the dialog. So you simply query the dialog object for its state in the lines of code immediately after you call setVisible(true) on the dialog.
If you need to deal with a non-modal dialog, then you'll need to add a WindowListener to the dialog to be notified when the dialog's window has become invisible.
If the dialog is to stay open after the user presses confirm:
Then you should probably use a PropertyChangeListener as has been suggested above. Either that or give the dialog object a public method that allows outside classes the ability to add an ActionListener to the confirm button.
For more detail, please show us relevant bits of your code, or even better, an sscce.
For example to allow the JDialog class to accept outside listeners, you could give it a JTextField and a JButton:
class MyDialog extends JDialog {
private JTextField textfield = new JTextField(10);
private JButton confirmBtn = new JButton("Confirm");
and a method that allows outside classes to add an ActionListener to the button:
public void addConfirmListener(ActionListener listener) {
confirmBtn.addActionListener(listener);
}
Then an outside class can simply call the `addConfirmListener(...) method to add its ActionListener to the confirmBtn.
For example:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class OutsideListener extends JFrame {
private JTextField textField = new JTextField(10);
private JButton showDialogBtn = new JButton("Show Dialog");
private MyDialog myDialog = new MyDialog(this, "My Dialog");
public OutsideListener(String title) {
super(title);
textField.setEditable(false);
showDialogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!myDialog.isVisible()) {
myDialog.setVisible(true);
}
}
});
// !! add a listener to the dialog's button
myDialog.addConfirmListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = myDialog.getTextFieldText();
textField.setText(text);
}
});
JPanel panel = new JPanel();
panel.add(textField);
panel.add(showDialogBtn);
add(panel);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
private static void createAndShowGui() {
JFrame frame = new OutsideListener("OutsideListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyDialog extends JDialog {
private JTextField textfield = new JTextField(10);
private JButton confirmBtn = new JButton("Confirm");
public MyDialog(JFrame frame, String title) {
super(frame, title, false);
JPanel panel = new JPanel();
panel.add(textfield);
panel.add(confirmBtn);
add(panel);
pack();
setLocationRelativeTo(frame);
}
public String getTextFieldText() {
return textfield.getText();
}
public void addConfirmListener(ActionListener listener) {
confirmBtn.addActionListener(listener);
}
}
Caveats though: I don't recommend subclassing JFrame or JDialog unless absolutely necessary. It was done here simply for the sake of brevity. I also myself prefer to use a modal dialog for solving this problem and just re-opening the dialog when needed.
Edit 2
An example of use of a Modal dialog:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class OutsideListener2 extends JFrame {
private JTextField textField = new JTextField(10);
private JButton showDialogBtn = new JButton("Show Dialog");
private MyDialog2 myDialog = new MyDialog2(this, "My Dialog");
public OutsideListener2(String title) {
super(title);
textField.setEditable(false);
showDialogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!myDialog.isVisible()) {
myDialog.setVisible(true);
textField.setText(myDialog.getTextFieldText());
}
}
});
JPanel panel = new JPanel();
panel.add(textField);
panel.add(showDialogBtn);
add(panel);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
private static void createAndShowGui() {
JFrame frame = new OutsideListener2("OutsideListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyDialog2 extends JDialog {
private JTextField textfield = new JTextField(10);
private JButton confirmBtn = new JButton("Confirm");
public MyDialog2(JFrame frame, String title) {
super(frame, title, true); // !!!!! made into a modal dialog
JPanel panel = new JPanel();
panel.add(new JLabel("Please enter a number between 1 and 100:"));
panel.add(textfield);
panel.add(confirmBtn);
add(panel);
pack();
setLocationRelativeTo(frame);
ActionListener confirmListener = new ConfirmListener();
confirmBtn.addActionListener(confirmListener); // add listener
textfield.addActionListener(confirmListener );
}
public String getTextFieldText() {
return textfield.getText();
}
private class ConfirmListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = textfield.getText();
if (isTextValid(text)) {
MyDialog2.this.setVisible(false);
} else {
// show warning
String warning = "Data entered, \"" + text +
"\", is invalid. Please enter a number between 1 and 100";
JOptionPane.showMessageDialog(confirmBtn,
warning,
"Invalid Input", JOptionPane.ERROR_MESSAGE);
textfield.setText("");
textfield.requestFocusInWindow();
}
}
}
// true if data is a number between 1 and 100
public boolean isTextValid(String text) {
try {
int number = Integer.parseInt(text);
if (number > 0 && number <= 100) {
return true;
}
} catch (NumberFormatException e) {
// one of the few times it's OK to ignore an exception
}
return false;
}
}
Why don't you check if your jDialog is visible?
yourJD.setVisible(true);
while(yourJD.isVisible())try{Thread.sleep(50);}catch(InterruptedException e){}
this works, also.
import javax.swing.JOptionPane;
or if you're already swinging
import javax.swing.*;
will have you covered.
After conditional trigger JOptionPane to send your warning or whatever modal message:
JOptionPane.showMessageDialog(
null,
"Your warning String: I can't do that John",
"Window Title",
JOptionPane.ERROR_MESSAGE);
check your options for JOptionPane.* to determine message type.
A typical way to use JFileChooser includes checking whether user clicked OK, like in this code:
private void addModelButtonMouseClicked(java.awt.event.MouseEvent evt) {
JFileChooser modelChooser = new JFileChooser();
if(modelChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ){
File selectedFile = modelChooser.getSelectedFile();
if(verifyModelFile(selectedFile)){
MetModel newModel;
newModel = parser.parse(selectedFile, editedCollection.getDirectory() );
this.editedCollection.addModel(newModel);
this.modelListUpdate();
}
}
}
I tried to mimic this behavior in my own window inheriting JFrame. I thought that this way of handling forms is more convenient than passing collection that is to be edited to the new form. But I have realized that if I want to have a method in my JFrame returning something like exit status of it I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window.
So, how does showOpenDialog() work? When I tried to inspect the implementation, I found only one line methods with note "Compiled code".
I tried to mimic this behavior in my own window inheriting JFrame.
JFrame is not a modal or 'blocking' component. Use a modal JDialog or JOptionPane instead.
E.G.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/** Typical output:
[JTree, colors, violet]
User cancelled
[JTree, food, bananas]
Press any key to continue . . .
*/
class ConfirmDialog extends JDialog {
public static final int OK_OPTION = 0;
public static final int CANCEL_OPTION = 1;
private int result = -1;
JPanel content;
public ConfirmDialog(Frame parent) {
super(parent,true);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
content = new JPanel(new BorderLayout());
gui.add(content, BorderLayout.CENTER);
JPanel buttons = new JPanel(new FlowLayout(4));
gui.add(buttons, BorderLayout.SOUTH);
JButton ok = new JButton("OK");
buttons.add(ok);
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = OK_OPTION;
setVisible(false);
}
});
JButton cancel = new JButton("Cancel");
buttons.add(cancel);
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = CANCEL_OPTION;
setVisible(false);
}
});
setContentPane(gui);
}
public int showConfirmDialog(JComponent child, String title) {
setTitle(title);
content.removeAll();
content.add(child, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getParent());
setVisible(true);
return result;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Test ConfirmDialog");
final ConfirmDialog dialog = new ConfirmDialog(f);
final JTree tree = new JTree();
tree.setVisibleRowCount(5);
final JScrollPane treeScroll = new JScrollPane(tree);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Choose Tree Item");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = dialog.showConfirmDialog(
treeScroll, "Choose an item");
if (result==ConfirmDialog.OK_OPTION) {
System.out.println(tree.getSelectionPath());
} else {
System.out.println("User cancelled");
}
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(b);
p.setBorder(new EmptyBorder(50,50,50,50));
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
I guess you wait for the user to click some button by constantly checking what button is pressed.
"I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window."
May be you should use evens to get notified, when the user clicks on something, not waiting for them to press the button - maybe there is some OnWindowExit event?
Or maybe something like this:
MyPanel panel = new MyPanel(...);
int answer = JOptionPane.showConfirmDialog(
parentComponent, panel, title, JOptionPane.YES_NO_CANCEL,
JOptionPane.PLAIN_MESSAGE );
if (answer == JOptionPane.YES_OPTION)
{
// do stuff with the panel
}
Otherwise you might see how to handle window events, especially windowClosing(WindowEvent) here