how to set & manage the layout of JOptionPane

戏子无情 提交于 2019-12-24 05:34:12

问题


I have a simple JOptionPane with some components and I want to arrange them.

For example I want to put the label next to the text/password field, sets their width etc..

This is like how I did it, of course the result wasn't what I wanted:

public class CreateApplicationUserScreen {

  CreateApplicationUserScreen(){
    JLabel l_name=new JLabel("Username");
    JLabel l_pass=new JLabel("Password");
    JTextField tf_name=new JTextField(10);
    JPasswordField pf_pass=new JPasswordField(10);
    JButton b_privs = new JButton("Privs");
    JButton b_databases = new JButton("Databases");

    int res = JOptionPane.showOptionDialog(window, 
                                          new Object[] { l_name, tf_name, 
                                                         l_pass, pf_pass, 
                                                         b_privs, b_databases }, 
                                          "Create application user", 
                                          JOptionPane.OK_CANCEL_OPTION,
                                          JOptionPane.PLAIN_MESSAGE,null, 
                                          new String[]{"Create", "Cancel"},
                                          "default");
  }
}

回答1:


You can add any Swing component to the option pane. So build your own panel:

import java.awt.*;
import javax.swing.*;

public class OptionPanePanel
{
    private static void createAndShowUI()
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );

        //  Build a custom panel

        JPanel panel = new JPanel( new GridLayout(2, 2) );
        panel.add( new JLabel("First Name") );
        JTextField firstName = new JTextField(10);
//      firstName.addAncestorListener( new RequestFocusListener(false) );
        panel.add( firstName );
        panel.add( new JLabel("Last Name") );
        JTextField lastName = new JTextField(10);
        panel.add( lastName );

        int result = JOptionPane.showConfirmDialog(
            frame, // use your JFrame here
            panel,
            "Use a Panel",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.PLAIN_MESSAGE);

        if(result == JOptionPane.YES_OPTION)
        {
            System.out.println(firstName.getText() + " : " + lastName.getText());
        }
        else
        {
            System.out.println("Canceled");
        }

        //  Let Option Pane build the panel for you

        Object[] msg = {"First Name:", firstName, "Last Name:", lastName};

        result = JOptionPane.showConfirmDialog(
            frame,
            msg,
            "Use default layout",
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.PLAIN_MESSAGE);

        if (result == JOptionPane.YES_OPTION)
        {
            System.out.println(firstName.getText() + " : " + lastName.getText());
        }
        else
        {
            System.out.println("Canceled");
        }
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

One drawback to this approach is that the focus will be on the button, not the text field. So you may want to use the RequestFocusListener to place focus on your first text field.




回答2:


  • JOptionPane uses BoxLayout, implemented in API

  • you can to set any LayoutManager, Font, Icon, etc.

  • required to call JOptionPane.pack(), if is changed LayoutManager

for example

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class OptionPaneOptions {

    private JPanel options;
    private Object[] items;

    public OptionPaneOptions() {
        options = new JPanel(new GridLayout(0, 3));
        options.add(createOptionPane("Plain Message", JOptionPane.PLAIN_MESSAGE));
        options.add(createOptionPane("Error Message", JOptionPane.ERROR_MESSAGE));
        options.add(createOptionPane("Information Message", JOptionPane.INFORMATION_MESSAGE));
        options.add(createOptionPane("Warning Message", JOptionPane.WARNING_MESSAGE));
        options.add(createOptionPane("Want to do something?", JOptionPane.QUESTION_MESSAGE));
        items = new Object[]{"First", "Second", "Third"};
        JComboBox choiceCombo = new JComboBox(items);
        options.add(titled(new JOptionPane(choiceCombo,
                JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION), "Question Message"));
        JFrame frame = new JFrame("JOptionPane'Options");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(options, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    static JOptionPane createOptionPane(String message, int type) {
        JOptionPane pane = new JOptionPane(message, type);
        System.out.println(pane.getLayout());
        String title = message;
        if (type == JOptionPane.QUESTION_MESSAGE) {
            title = "Question Message";
            pane.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION);
        }
        return titled(pane, title);
    }

     static <T extends JComponent> T titled(T c, String title) {
        c.setBorder(BorderFactory.createTitledBorder(title));
        return c;
    }

    public static void main(String[] args) {
        OptionPaneOptions test = new OptionPaneOptions();
    }
}


来源:https://stackoverflow.com/questions/17617390/how-to-set-manage-the-layout-of-joptionpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!