you could 'roll-your-own'
something like this
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Testing
{
int selectedIndex = -1;
JDialog dialog;
public Testing()
{
final JOptionPane optionPane = new JOptionPane("Pick a Button:");
JButton[] btns = new JButton[4];
for(int x = 0; x < btns.length; x++)
{
final int SELECTION = x;
btns[x] = new JButton(""+x);
btns[x].setToolTipText(""+x);
btns[x].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
selectedIndex = SELECTION;
dialog.dispose();
}
});
}
optionPane.setOptions(btns);
dialog = optionPane.createDialog(null, "Pick One");
dialog.setModal(true);
dialog.setVisible(true);
if(selectedIndex > -1)
{
JOptionPane.showMessageDialog(null,"You selected index # "+selectedIndex);
}
else JOptionPane.showMessageDialog(null,"Cancelled");
System.exit(0);
}
public static void main(String[] args){new Testing();}
}
> It returns the previously clicked button index if the exit button of the dialog is pressed
I don't follow this?
if a button is clicked the dialog closes
if the 'X" is clicked (or esc key) the selection stays at -1, and the 'cancelled'
message is displayed
can you describe the steps to produce the problem
Thanks for your reply
What i did is i dint reset the selectedIndex
It is working fine now
Code snippet is as follows
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
class Testing extends JFrame {
public Testing() {
JButton showBtn = new JButton("Show");
showBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
showoption();
}
});
getContentPane().add( showBtn, BorderLayout.NORTH );
setSize(400,400);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setVisible( true );
}
int selectedIndex = -1;
JDialog dialog = null;
public void showoption(){
selectedIndex = -1;
final JOptionPane optionPane = new JOptionPane("Pick a Button:");
JButton[] btns = new JButton[4];
for(int x = 0; x < btns.length; x++) {
final int SELECTION = x;
btns[x] = new JButton(""+x);
btns[x].setToolTipText(""+x);
btns[x].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
selectedIndex = SELECTION;
dialog.dispose();
}
});
}
optionPane.setOptions(btns);
dialog = optionPane.createDialog(null, "Pick One");
dialog.setModal(true);
dialog.setVisible(true);
if(selectedIndex > -1){
JOptionPane.showMessageDialog(null,"You selected index # "+selectedIndex);
}
else JOptionPane.showMessageDialog(null,"Cancelled");
}
public static void main(String[] args){new Testing();}
}