JButton in JDialog vs JOptionPane

I have created two different JDialogs, one with JOptionPane and one in the old-fashioned way. My problem is that the buttons in the different JDialogs get different appearence (I'm usings javas Metal L&F). Take a look at this sample code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestFrame extends JFrame implements ActionListener {
   JDialog dialog1;
   JDialog dialog2;
   JButton button1;
   JButton button2;
   JButton dialogButton;
   public TestFrame() {
      button1 = new JButton("Open dialog 1");
      button1.addActionListener(this);
      button2 = new JButton("Open dialog 2");
      button2.addActionListener(this);
      getContentPane().add(button1, BorderLayout.NORTH);
      getContentPane().add(button2, BorderLayout.SOUTH);
      pack();
      setVisible(true);
   public static void main(String args[]) {
      new TestFrame();
   public void openDialog1() {
      JOptionPane vAbout = new JOptionPane("Just some text...", JOptionPane.INFORMATION_MESSAGE);
      dialog1 = vAbout.createDialog(this, "Dialog 1");
      dialog1.show();
   public void openDialog2() {
      dialog2 = new JDialog(this, "Dialog 2", true);
      GridBagLayout gbl = new GridBagLayout();
      GridBagConstraints gbc = new GridBagConstraints();
      dialog2.getContentPane().setLayout(gbl);
      JLabel text = new JLabel("Just some text...");
      dialogButton = new JButton("OK");
      dialogButton.addActionListener(this);
      dialog2.getContentPane().add(text, gbc);
      gbc.gridy = 1;
      dialog2.getContentPane().add(dialogButton, gbc);
      dialog2.pack();
      dialog2.setVisible(true);
   public void actionPerformed(ActionEvent e) {
      System.out.println(e.getSource());
      if (e.getSource() == button1)
         openDialog1();
      if (e.getSource() == button2)
         openDialog2();
      if (e.getSource() == dialogButton)
         dialog2.dispose();
   protected void processWindowEvent(WindowEvent e) {
      super.processWindowEvent(e);
      if(e.getID() == WindowEvent.WINDOW_CLOSING) {
         System.exit(0);
}How can I get my button in dialog2 to look the same as the button in dialog1?

To set the button to be default, you need some modification. Here's the basic frame work:
public class TestFrame() extends JFrame
   //Your constructor
   public TestFrame()
      //Do stuff in here
      myDialog mydialog = new myDialog(this);
      mydialog.show()
   public static void main(String[] args)
      //etc
   private void SomeOtherMethods()
       //Declare your JOptionPane
public class myDialog extends JDialog
   //Constructor
   public myDialog()
       //Add Components like usual
       getRootPane.setDefaultButton(DialogButton);
       getContentPane.add(Your_Panels);
    private void SomeOtherMethods()
}Basically, you're taking your JDialog and placing it in it's own class (which is better anyway, trust me). Then it will set the button as the default and make the border darker.
Let me know if you have anymore questions.

Similar Messages

  • Is there any way to wait for a value without using JDialog or JOptionPane?

    I am implementing a dictionary program by detecting word in a JTextPane and asking a user to choose one of available meanings from JOptionPane or JDialog. The program runs under a while-loop until all dictionary words are detected or a user clicks cancel.
    However, I don't want to use JDialog or JOptionPane because it is sometimes annoying to have a popup window on every detected dictionary word.
    So, I use JList with Buttons on the same Frame as the JTextPane. However, now, the program does not stop when it detects a dictionary word. It just uses a default value of the JList for translating word to meaning.
    Is there any way I can simulate the JDialog or JOptionPane without using it?
    I mean I'd like to stopp the program temporary, wait for an answer from other components, and then continue to detect the next dictionary word.
    Thank you.

    I'm probably reading this all wrong, but instead of the while loop,
    the method just looked for a dictionary word from a particular caretPosition,
    so, to start, it would be findWord(0)
    when found, add whatever to wherever, note the caretPostion at the end of the 'found' word, and method returns.
    when the user selects whatever button, the button's actionListener also calls the method again, using the noted caretPosition
    findWord(42);
    so, it starts searching from 42 (instead of the start)
    basically it is event driven
    findWord sets the button/s
    click a button starts findWord

  • IMAGE NOT DISPLAYED OVER JButton ON JDialog

    Hi,
    I am trying to display an image over a JButton inside a JDialog(pops up on button click from an applet). But it is invisible. But I am sure that it is drawn on the ContentPane since when i click partially/half at the position
    of the JButton I could see the JButton with the image. Actualy I am resizing the JDialog since I have two buttons, one to minimise and the other two maximise the size of the JDailog.
    All the buttons are in place but not visible neither at the first place nor when the JDialog is resized.
    The code is as follows:
    package com.dataworld.gis;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class PrintThisPolygon extends JDialog {
         protected Image image;
         protected JButton print;
         protected JButton resize;
         protected JButton desize;
         private int pX=0, pY=0, pWidth=0, pHeight=0;
         public PrintThisPolygon(JFrame parent, Viewer viewer) {
              super(parent, "Print Polygon", true);
              this.setModal(false);
              getContentPane().setLayout(null);
              image = this.viewer.getScreenBuffer();
              pane = new Panel();
              print = new JButton("print", new ImageIcon("images/print.gif"));
              print.setBounds(0,5,50,20);
              print.setEnabled(true);
              print.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        print();
              resize = new JButton("+", new ImageIcon("images/print.gif"));
              resize.setBounds(55,5,50, 20);
              resize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizePlus();
              desize = new JButton("-", new ImageIcon("images/print.gif"));
              desize.setBounds(105,5,50, 20);
              desize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizeMinus();
              getContentPane().add(print);
              getContentPane().add(resize);
              getContentPane().add(desize);
    public String getAppletInfo() {
         return "Identify Polygon\n"
    public void paint(Graphics g){
         System.out.println("Paint : pX " + pX + " pY :" + pY);
         g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
    protected void print() {
         ImagePrint sp = new ImagePrint(this.viewer);
    public void resizeMinus(){
         repaint();
    public void resizePlus(){
         repaint();
    Can anybody has any clue. Can anybody help me out.
    Thanx

    I added resize code for those buttons and ended up with repaint problems too. When you manually resized the window everything was fine again. After a bit of digging around I found you need to call validate on the dialog and then things work.
    IL,
    There is the new scaling version of the code I modified above:package forum.com.dataworld.gis;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class PanelPaintFrame extends JFrame {
         public static void main(String[] args) {
              PanelPaintFrame frame = new PanelPaintFrame ();
              frame.setVisible (true);
         public PanelPaintFrame ()  {
              setBounds (100, 100, 600, 600);
              setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JButton showPrintDialogButton = new JButton ("Show Print Dialog...");
              JPanel buttonPanel = new JPanel ();
              buttonPanel.add (showPrintDialogButton);
              getContentPane ().add (buttonPanel);
              showPrintDialogButton.addActionListener (new ActionListener ()  {
                   public void actionPerformed (ActionEvent e)  {
                        PrintThisPolygon printDialog = new PrintThisPolygon (PanelPaintFrame.this);
                        printDialog.show();
              pack ();
         public class PrintThisPolygon extends JDialog {
              protected ImageIcon myOrigonalImage = null;
              protected Image image;
              protected JButton print;
              protected JButton resize;
              protected JButton desize;
              private int pX=0, pY=0, pWidth=0, pHeight=0;
              JPanel pane = null;
              public PrintThisPolygon(JFrame parent/*, Viewer viewer*/) {
                   super(parent, "Print Polygon", true);
    //               this.setModal(false);
                   getContentPane().setLayout(null);
                   //  Substitute my own image
                   myOrigonalImage = new ImageIcon (PrintThisPolygon.class.getResource ("images/MyCoolImage.jpg"));
                   //  Start off full size
                   pWidth = myOrigonalImage.getIconWidth();
                   pHeight = myOrigonalImage.getIconHeight();
                   image = myOrigonalImage.getImage ().getScaledInstance(pWidth, pHeight, Image.SCALE_DEFAULT);
    //               image = this.viewer.getScreenBuffer();
    //               pane = new Panel();
                   //  Create a JPanel to draw the image
                   pane = new JPanel(){
                        protected void paintComponent(Graphics g)  {
                             System.out.println("Paint : pX " + pX + " pY :" + pY);
                             g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
                   pane.setBounds (0, 0, pWidth, pHeight);
                   //  Load the button image using a URL
                   print = new JButton("print", new ImageIcon(PrintThisPolygon.class.getResource ("images/print.gif")));
    //               print = new JButton("print", new ImageIcon("images/print.gif"));
                   print.setBounds(0,5,55,20);
                   print.setEnabled(true);
                   print.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             print();
                   resize = new JButton("+", new ImageIcon("images/print.gif"));
                   resize.setBounds(55,5,50, 20);
                   resize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizePlus();
                   desize = new JButton("-", new ImageIcon("images/print.gif"));
                   desize.setBounds(105,5,50, 20);
                   desize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizeMinus();
                   //  Setup a transparent glass panel with no layout manager
                   JPanel glassPanel = new JPanel ();
                   glassPanel.setLayout (null);
                   glassPanel.setOpaque (false);
                   //  Add the image panel to the dialog
                   getContentPane().add(pane);
                   //  Add the buttons to the glass panel
                   glassPanel.add(print);
                   glassPanel.add(resize);
                   glassPanel.add(desize);
                   //  Set our created panel as the glass panel and turn it on
                   setGlassPane (glassPanel);
                   glassPanel.setVisible (true);
                   setBounds (100, 100, pWidth, pHeight);
    //               setBounds (100, 100, 500, 300);
              public String getAppletInfo() {
                   return "Identify Polygon\n";
    //          public void paint(Graphics g){
    //          protected void paintComponent(Graphics g)  {
    //               System.out.println("Paint : pX " + pX + " pY :" + pY);
    //               g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
              protected void print() {
                   //  Pretend to print
    //               ImagePrint sp = new ImagePrint(this.viewer);
                   System.out.println ("Print view...");
              public void resizeMinus(){
                   //  Scale the image down 10%
                   int scaledWidth = pWidth - (int)(pWidth * 0.1);
                   int scaledHeight = pHeight - (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              public void resizePlus(){
                   //  Scale the image up 10%
                   int scaledWidth = pWidth + (int)(pWidth * 0.1);
                   int scaledHeight = pHeight + (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              private void scaleImage (int scaledWidth, int scaledHeight)  {
                   //  Create a new icon for drawing and retrieve its actuall size
                   image = myOrigonalImage.getImage ().getScaledInstance (scaledWidth, scaledHeight, Image.SCALE_DEFAULT);
                   pWidth = scaledWidth;
                   pHeight = scaledHeight;
                   //  Resize
                   setSize (pWidth, pHeight);
                   pane.setSize (pWidth, pHeight);
                   validate();
    }

  • JDialog and JOptionPane

    Could anyone please help me with this. I'm getting a class cast exception when I run this code.
    final JOptionPane optionPane = new JOptionPane(message+"\nOk to proceed?",JOptionPane.QUESTION_MESSAGE,JOptionPane.YES_NO_OPTION);
         final JDialog dialog = new JDialog();
         dialog.setContentPane(optionPane);
         dialog.setDefaultCloseOperation(
              JDialog.DO_NOTHING_ON_CLOSE);
              dialog.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent we) {
                   JOptionPane warn = new JOptionPane();
                   warn.showMessageDialog(null,"You must choose an action!","Warning",JOptionPane.WARNING_MESSAGE);
         optionPane.addPropertyChangeListener(
              new PropertyChangeListener() {
                   public void propertyChange(PropertyChangeEvent e) {
                        String prop = e.getPropertyName();
                        if (dialog.isVisible()
                        && (e.getSource() == optionPane)
                        && (prop.equals(JOptionPane.VALUE_PROPERTY) ||
                             prop.equals(JOptionPane.INPUT_VALUE_PROPERTY))) {
                                  //Do Check here
                                  dialog.setVisible(false);
                   dialog.pack();
                   dialog.setVisible(true);
                   int value = ((Integer)optionPane.getValue()).intValue();
                   if (value == JOptionPane.YES_OPTION) {
                        returnInt = 1;
                   } else if (value == JOptionPane.NO_OPTION) {
                        returnInt = 0;
                   } else {returnInt = 5;}
    return returnInt;
    I use a small applet to call this method and pass it parameters.
    thanks

    Hi,
    You have to check if a user has made a choice before casting optionPane.getValue to Integer. If the user has not made any selection yet, the object - JOptionPane.UNINITIALIZED_VALUE, which cannot be cast into Integer, will be returned.
    Try adding the following to your code:
    if (optionPane.getValue() != JOptionPane.UNINITIALIZED_VALUE) {
    value = ((Integer) optionPane.getValue()).intValue();
    or you could use a while loop to wait for a user to make a selection.

  • How to add jbutton to jDialog

    Hi,
    I have a popup JDialog after my application is running. I want to include some function button on JDialog, but it failed to show.
    Thanks,
    Tom

    hey i am doing a school progect, and i have some code that is like this:
    import java.awt.*;
    import hsa.Console;
    public class Asmt4_LemireE
    static Console c; // The output console
    public static void main (String[] args)
    c = new Console (120, 125, 20); //'c' is the output console
    // Place your program here:
    //User Promtp
    c.setCursor(15,5);
    c.println("Press any key to see a graph of this information");
    c.getChar();
    c.clear();
    //System.out.println("This is the second page");
    //Set Text Color
    c.setTextColor(Color.red);
    //Things on Menu.
    double Chicken_Wings,Hamburger_and_Fries , Steak_and_Beer, Ribs_and_Rice, Fajita_Pita, Bacon_Burger , Classic_Sirlon, Honey_BBQ_Sirlion , pluto;
    Chicken_Wings = 5.00;
    Hamburger_and_Fries = 4.50;
    Steak_and_Beer = 10.00;
    Ribs_and_Rice = 8.53;
    Fajita_Pita = 5.33;
    Bacon_Burger = 4.99;
    Classic_Sirlon = 20.00;
    Honey_BBQ_Sirlion = 10.99;
    pluto = 5870.00;
    for (double x=1; x<Chicken_Wings/80; x++)
    c.setCursor(2, 0);
    c.print("");
    c.println("Chicken_Wings");
    c.setCursor(1, 17);
    c.println(Chicken_Wings);
    c.println("Hamburger_and_Fries");
    c.setCursor(2, 20);
    c.println(Hamburger_and_Fries);
    c.println("Steak_and_Beer");
    c.setCursor(3, 15);
    c.println(Steak_and_Beer);
    c.println("Ribs_and_Rice");
    c.setCursor(4, 15);
    c.println(Ribs_and_Rice);
    c.println("Fajita_Pita");
    c.setCursor(5, 13);
    c.println(Fajita_Pita);
    c.println("Bacon_Burger");
    c.setCursor(6, 13);
    c.println(Bacon_Burger);
    c.println("Classic_Sirlon");
    c.setCursor(7, 15);
    c.println(Classic_Sirlon);
    c.println("Honey_BBQ_Sirlion");
    c.setCursor(8, 18);
    c.println(Honey_BBQ_Sirlion);
    c.println("Pluto");
    c.setCursor(9, 10);
    c.println(pluto);
    //Set Text Color
    c.setTextColor(Color.green);
    //Print Restaurant Name
    c.setCursor(1, 35);
    c.println("Napsters Cyber Cafe");
    c.setCursor(5, 15);
    //Menu Names
    c.println("MENU");
    c.setCursor(5, 60);
    c.println("MENU");
    //Order Button
    c.setCursor(25, 70);
    c.println("Press To Order");
    //Rectangles for Menu
    c.drawRect(400, 1, 240, 30);
    c.drawRect(1, 80, 1000, 600);
    c.drawLine(500, 80, 500, 680);
    c.drawRect(826, 652, 172, 20);
    and i was wondering if i could put the button code in, and replace the name of the buttons (which i know how to do) and make them link to another page. or if it is easier to just combine the 2 codes together.

  • JDialog or JOptionPane...

    Hi!
    Is there any way to create a window in some block of code and kill him in another block below? I need to create a window which won't wait for OK click or something, just it comes when I create him and dissappears when I want. How to do that?

    You can install a TimerTask-object who watches for a specific time you want if the user did an action. Then you can close the frame/dialog or what ever there.

  • ActionListener in JDialog created by JOptionPane

    I have a problem I absolutely cannot get around. I've been toying with this code all day and nedd some help badly. The code is posted below. Let me give you some background. I have an application that uses "popups" to ask the user a series of questions. I have two bg images I want to display for the background,
    as well as a custom button (that's no sweat). I originally wrote a class extending JDialog to show the popups. But JDialog does not "block" and wait for user input. I started toying around with JOptionPane. I have created a JDialog from JOptionPane.createDialog(parent, title). All the components display correctly and
    the dialog blocks, BUT the actionListener I added to my button does not go into action. Am I barking up the wrong tree, or is there a way to get a JDialog to block
    the running thread?
    class myDialog{
    JDialog main;
    JTextField inputfield;
      public myDialog(JFrame parent, String display){
    main = this.createDialog(parent, "hello");
    Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
            main.setBounds(screenSize.width/2 - 195,
                      screenSize.height/2 - 50,395,110);
    JLabel textInsert = new JLabel(display);
    textInsert.setFont(new Font("Serif", Font.BOLD|Font.ITALIC, 14));
    textInsert.setForeground(Color.gray);
    JButton next = new JButton(new ImageIcon("images/gui/next.png"));
    inputfield = new JTextField(20);
    Container c = main.getContentPane();
    c.setLayout(new BorderLayout());
    c.removeAll(); // call this to remove the components added by JOptionPane.
    BackgroundComponent panel = new BackgroundComponent(new ImageIcon("images/gui/upperdialog.png").getImage());
    BackgroundComponent panel2 = new BackgroundComponent(new ImageIcon("images/gui/lowerdialog.png").getImage());
    panel.add(new JLabel(new ImageIcon("images/gui/spacer.png")));
    panel.add(textInsert);
    panel2.add(inputfield);
    panel2.add(next);
    c.add(panel, BorderLayout.NORTH);
    c.add(panel2, BorderLayout.CENTER);
    main.setResizable(true);
    main.setVisible(true);
    next.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
             main.setVisible(false);
         }Thanx in advance -- CSB

    the wrong tree, or is there a way to get a JDialog to
    block
    the running thread?Yes, by making it modal:
    main.setModal(true);
    main.setVisible(true);There are also a couple of JDialog constructors that you can use to create a modal dialog without having to use the setModal method.

  • Headache: Data Xchange from JDialog to JTable using JButton

    My head is spinning about how to get this to work. What is really confusing me is the data exchange from the JDialog.
    I have a JTable where one of the columns uses a JButton as the cell editor for each cell in that column. That part seems to be no problem. The JButton is labeled "Define Staff..."
    When the user clicks on the JButton, a JDialog containing a JList is to appear. If the user clicks cancel, the JDialog is disposed and nothing happens. If the user clicks OK, the selected items are to be returned to the cell in some way and the label of the JButton is to change to "Modify Staff..."
    How can I return the list from the JDialog to the "cell" so that when I access the cell using getValueAt() I get the list of values, and not the JButton object?

    Thanks.
    The actual JButton is inside a JTable cell though.
    Where would I add the event handler for the button? In the editor? In the renderer?
    Excerpt from the JTable file:
         PositionTable.getColumn("Staff").setCellRenderer(new ButtonRenderer());
         PositionTable.getColumn("Staff").setCellEditor(new ButtonEditor(new JCheckBox()));ButtonEditor.java
    public class ButtonEditor extends DefaultCellEditor {
      protected JButton button;
      private String    label;
      private boolean   isPushed;
      public ButtonEditor(JCheckBox checkBox) {
        super(checkBox);
        button = new JButton();
        button.setOpaque(true);
        button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            fireEditingStopped();
      public Component getTableCellEditorComponent(JTable table, Object value,
                       boolean isSelected, int row, int column) {
        if (isSelected) {
        } else{
          button.setForeground(table.getForeground());
          button.setBackground(table.getBackground());
        label = (value ==null) ? "" : value.toString();
        isPushed = true;
        return button;
      public Vector<String> getCellEditorValue() {
        Vector<String> staff = new Vector<String>();
        if (isPushed)  {
          staffSelector temp = new staffSelector(null,true,"Building Supervisor");
          temp.setVisible(true);
          staff = temp.getSelectedStaff(true);
        isPushed = false;
       // return new String( label ) ;
       //Return vector people selected.
       return staff;
      public boolean stopCellEditing() {
        isPushed = false;
        return super.stopCellEditing();
      protected void fireEditingStopped() {
        super.fireEditingStopped();
    }ButtonRenderer.java
    public class ButtonRenderer extends JButton implements TableCellRenderer {
      public ButtonRenderer() {
        setOpaque(true);
      public Component getTableCellRendererComponent(JTable table, Object value,
                       boolean isSelected, boolean hasFocus, int row, int column) {
        if (isSelected) {
          setForeground(table.getForeground());
          setBackground(table.getBackground());
        } else{
          setForeground(table.getForeground());
          setBackground(UIManager.getColor("Button.background"));
        setText( (value ==null) ? "Define Staff..." : "Modify Staff..." );
        return this;
    }Message was edited by:
    AsymptoticCoder
    Made an error.

  • Change Coffee cup icon on JDialog & JOptionPane

    I try to change the coffee cup icon on my JDialog and JOptionPane.
    My JDialog box does not load the Parent Icon (JFrame icon), and not even show a coffee cup icon.
    My JOptionPane would just show a coffee cup icon, eventhough its parent is the above JDialog with no icon.
    Is there anyone know how to fix this?
    I'd like show my icon on the JOptionPane instead of the coffee cup icon.
    And also to show my icon on the JDialog instead of nothing, not even a coffee icon.
    Any help is appreciated.
    CL

    Passing a parent with the desired icon to the JDialog/JOptionPane should solve your problem, however there is a bug in swing that prevents any icon from showing in the titlebar if a JDialog is made non-resizable (through a call to setResizable(false)).
    The bug adatabse says that this has been resolved but I am using jdk 1.3.1 and continue to have this problem.

  • JOptionPane JButton Icon

    Hi,
    Does anyone knows how to set icons in the JOptionPane buttons ?
    I use this but when I click it never closes the dialog.
    JButton[] options = new JButton[3];
    options[0] = new JButton("B1");
    options[1] = new JButton("B2");
    options[2] = new JButton("B3");
    int n = JOptionPane.showOptionDialog(null,
    "Would you like to replace it ?",
    "Question",
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,
    null);
    System.out.println(n);
    Thanks.

    Use this :
    Icon[] options = { new ImageIcon("yes.gif"),new ImageIcon("no.gif"), new ImageIcon("cancel.gif")};
    int res = JOptionPane.showOptionDialog(null, "Select a button", "title", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);I hope this helps,
    Denis

  • Key-enable buttons on a JOptionPane

    Hi,
    The existing code in my Application uses a JOptionPane static method = JOptionPane.showOptionDialog() to create a dialog box.Is there any way I can key-enable the buttons on the dialog created by this method.
    public int createAndShowGUI() {
    if (!issuesPanel.hasIssues())
    return -2; //TODO make constant
    else {
    //Custom button text
    String[] options = should_continue ? new String[] {returnText, continueText} : new String[] {returnText};
    int optionButtons = should_continue ? JOptionPane.OK_CANCEL_OPTION : JOptionPane.CANCEL_OPTION ;
    log.info("IssuesOptionPane displayed - " + title);
    int optionChosen = JOptionPane.showOptionDialog(parent,
    issuesPanel.createAndGetIssuesPanel(),
    title,
    optionButtons,
    JOptionPane.PLAIN_MESSAGE,
    null, //don't use a custom icon
    options, //titles of buttons
    null); //no default selected button
    String buttontext = optionChosen == CLOSE ? "X" : options[optionChosen];
    log.info("User clicked on the " + buttontext + " button");
    return optionChosen;
    I see that there is no way to get a handle on the JButtons created by the JOptionPane.So, one work around that I tried is to create a JPanel, add JButtons , set Input Map, set Action Map ( to add key bindings ) on it.Then create a JDialog and pass this JPanel to the dialog using setContentPane
         private static void createAndShowGUI(){
              JButton bookingButton=new JButton(bookStr);
              JButton returnButton=new JButton(returnStr);
              bookingButton.addActionListener(new BookAction());
              returnButton.addActionListener(new ReturnAction());
              JPanel panel=new JPanel();
              panel.add(bookingButton);
              panel.add(returnButton);
              panel.setActionMap(initActionMap());
              initAndSetInputMap(panel);
              JDialog dialog=new JDialog();
              dialog.setSize(400,100);
              dialog.setModal(true);
              dialog.setContentPane(panel);
              dialog.addPropertyChangeListener(indicator,listener);
              System.out.println("step 1" );
              dialog.pack();
              System.out.println("step 2");
              dialog.setVisible(true);
    But the problem that I am facing here is that the property change events triggered by the code inside the actionPerformed methods is not getting capturesd by the listener attached to the JDialog.
    Any thoughts?
    Thanks
    Aman

    google: JOptionPane mnemonics
    http://www.devx.com/tips/Tip/13718
    http://forum.java.sun.com/thread.jspa?threadID=321824&messageID=1649963
    http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2005-03/0495.html
    etc.

  • JOptionPane Help Needed

    I basically have two problems with JOptionPane that I've searched for answers yet I haven't found an applicable answer for my application. Here they are:
    1) How can I get a JPasswordField in a JOptionPane to be given focus when the JOptionPane is displayed?
    2) How can I get the default key mappings for JOptionPane not to work or atleast make it where when a user hits "Enter", it activates the button that has current focus? I have a problem with highlighting "Cancel" and hitting "Enter".
    Here is my code being used for the JOptionPane:
    String pwd = "";
    int tries = 0;
    JPasswordField txt = new JPasswordField(10);
    JLabel lbl = new JLabel("Enter Password :");
    JLabel lbl1 = new JLabel("Invalid Password.  Please try again:");
    JPanel pan = new JPanel(new GridLayout(2,1));
    int retval;
    while(tries < 3 && !valid)
         if(tries > 0)
              pan.remove(lbl);
              pan.remove(txt);
              pan.add(lbl1);
              pan.add(txt);
              txt.setText("");
         else
              pan.add(lbl);
              pan.add(txt);
         retval = JOptionPane.showOptionDialog(DBPirate.appWindow,pan,
         "Password Input",                              JOptionPane.OK_CANCEL_OPTION,                              JOptionPane.QUESTION_MESSAGE,
         null,null,null);
         if(retval == JOptionPane.OK_OPTION)
              pwd = new String(txt.getPassword());
              setPassword(pwd);
              if(cryptoUtil.testPassword(pwd))
                   valid = true;
              else
                   tries += 1;
         else
              System.exit(0);
    }Any help would be appreciated. Thanks, Jeremy

    Hello Jeremy,
    I am not too happy with my code, for I think there must be something more efficient and elegant. But after trying in vain with KeyListener and ActionMap this is presently the only way I could do it.
    // JOptionPane where the <ret>-key functions just as the space bar, meaning the
    // button having focus is fired.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ReturnSpace extends JFrame implements ActionListener
    { JButton bYes, bNo, bCancel;
      JDialog d;
      JOptionPane p;
      public ReturnSpace()
      { setSize(300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container cp= getContentPane();
        cp.setLayout(new FlowLayout());
        JButton b= new JButton("Show OptionPane");
        b.addActionListener(this);
        p=new JOptionPane("This is the question",
              JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
        d=p.createDialog(this,"JOptionPane with changing default button.");
        FocusListener fl= new FocusAdapter()
        { public void focusGained(FocusEvent e)
          {     JButton focusButton= (JButton)(e.getSource());
         d.getRootPane().setDefaultButton(focusButton);
        int i=1;
    //    if (plaf.equals("Motif")) i=2;
        bYes = (JButton)((JPanel)p.getComponent(i)).getComponent(0);
        bYes.addFocusListener(fl);
        bNo = (JButton)((JPanel)p.getComponent(i)).getComponent(1);
        bNo.addFocusListener(fl);
        bCancel = (JButton)((JPanel)p.getComponent(i)).getComponent(2);
        bCancel.addFocusListener(fl);
        cp.add(b);
        setVisible(true);
        d.setLocationRelativeTo(this);
      public void actionPerformed(ActionEvent e)
      { bYes.requestFocus();
        d.setVisible(true);
        Object value = p.getValue();
        if (value == null || !(value instanceof Integer))
        { System.out.println("Closed");
        else
        { int i = ((Integer)value).intValue();
          if (i == JOptionPane.NO_OPTION)
          { System.out.println("No");
          else if (i == JOptionPane.YES_OPTION)
          { System.out.println("Yes");
          else if (i == JOptionPane.CANCEL_OPTION)
          { System.out.println("Cancelled");
      public static void main(String argsv[])
      { new ReturnSpace();
    }Greetings
    Joerg

  • Japanese character is not displaying properly in JDialog

    Hi All,
    Japanese character are shown in parent window but not displaying properly JDialog window.
    Even JDialog Title bar is showing in Japanese properly but JLabel's and JButton text are not showing properly in Japanese.
    Anybody knows why Japanese characters are not showing properly in JLabel and JButton of JDialog window.
    Thanks,
    -Mani

    Specified font on that objects, that's why Japanese character doesn't shown.

  • JDialog best practice

    I am building a custom JDialog that includes a JPanel so that it's easier for me to customize (I'm using NetBeans). This is my first solo project as a developer so I want to make sure I follow best practice whenever possible. I have two questions in that regard.
    1. If I need to pop-up a user interface from my main frame that inlcudes several components (a text area, radio button groups, buttons, etc) is the JDialog my best option? I know that there are built in dialogs that are used for convenience but they aren't satisfactory for what I need from a user input perspective.
    2. The dialog I created contains almost as much code as the main JFrame. This JFrame class is becoming quite large to the point that it's hard to keep track of the code. I've thought about creating another class that extends JDialog and placing the code for the dialog in that class. Is that the generally accepted method for resolving this type of issue?
    Last note: I prefer to design my GUI using an IDE such as NetBeans so I can focus on the non-aesthetic code. Unfortunately there doesn't seem to be any logical way for me to create a JDialog outside of my main JFrame without having creating a generic class and write the aesthetic related code manually. Anyone using NetBeans have any suggestions? ( excuse me for that part if there is a separate NetBeans forum but I could not find one ).
    Thanks

    1. Yeah, I believe JDialog is your best choice. If it's quick pop-up question I instantiate the JDialog via JOptionPane, but if it's more complex I instantiate the JDialog directly.
    2. That's okay. You can separate the JDialog GUI into a system of objects working together. I usually make sure this system has only one or two points of access (that is, the reference that the main JFrame will have to it to set it visible and stuff) so that the system doesn't complicate the code that accesses it, but instead keeps its complications internal.
    3. I always code my GUIs. I hate how visual editors code it =\

  • Aligning Text in Center of JOptionPane

    Hi,
    I am trying to display messages using JOptionPane and a JDialog.
        JOptionPane pane = new JOptionPane(message,
                                           message_type,
                                           option_type,
                                           icon,
                                           options,
                                           initial_value){
          public int getMaxCharactersPerLineCount() { return    default_characters_per_line; }
        JDialog dialog = pane.createDialog(parent_component, title);
        dialog.setVisible(true);I want to be able to control the number of characters per line which I have found how to do, and to control the alignment of the text. I have not being able to work out how to control the alignment of the text. I would like to be able have the text centered so a long line followed by a short line is displayed nicely.
    I have tried using <html><center>My Text</center></html>, however, 1stly the html tags are counted as character therefore shortening the 1st line and secondly is the message is over several line then the tag are broken up and not interpreted properly.
    Any assistance greatly appreciated.
    Leon

    //Create the dialog.
                        final JDialog dialog = new JDialog(frame,
                                                           "A Non-Modal Dialog");
                        //Add contents to it. It must have a close button,
                        //since some L&Fs (notably Java/Metal) don't provide one
                        //in the window decorations for dialogs.
                        JLabel label = new JLabel("<html><p align=center>"
                            + "This is a non-modal dialog.<br>"
                            + "You can have one or more of these up<br>"
                            + "and still use the main window.");
                        label.setHorizontalAlignment(JLabel.CENTER);
                        Font font = label.getFont();
                        label.setFont(label.getFont().deriveFont(font.PLAIN,
                                                                 14.0f));extract from
    http://java.sun.com/docs/books/tutorial/uiswing/examples/components/DialogDemoProject/src/components/CustomDialog.java

Maybe you are looking for