在JOptionPane.showOptionDialog中更改按钮布局

问题描述

我正在开发一个程序,用户可以从命令列表中进行选择。我的程序有几个命令,并且JOptionPane.showOptionDialog()水平显示它们。

GIU

如您所见,窗口比我的屏幕宽。我想将其放置在两行按钮而不是一排的地方,这样用户可以看到所有选项。

这到底是怎么做到的?

这是我的代码

public int getCommand (String[] commands) {
    
    return JOptionPane.showOptionDialog
            (null,"Choose an option below",// Prompt message
                    windowTitle,// Window title
                    JOptionPane.YES_NO_CANCEL_OPTION,// Option type
                    JOptionPane.QUESTION_MESSAGE,// Message type
                    null,// Icon
                    commands,// List of commands
                    commands[commands.length - 1]);
}

解决方法

选项窗格的布局是在内部控制的,没有任何方法可以直接控制按钮的布局。

因此,正确的解决方案是仅创建一个自定义模式JDialog,该JDialog可根据您的需求显示组件。

但是,如果您确实要使用JOPtionPane功能,则需要:

  1. 将JOptionPane创建为Swing组件,然后更改包含按钮的面板的布局管理器。
  2. 将JOptionPane添加到JDialog并手动实现标准的选项窗格功能。

第一步演示如下:

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

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        String[] commands = {"1","2","3","4","5","6","7","8"};

        JOptionPane op = new JOptionPane
        (
            "Choose an option below",// Prompt message
            JOptionPane.QUESTION_MESSAGE,// Message type
            JOptionPane.YES_NO_CANCEL_OPTION,// Option type
            null,// Icon
            commands,// List of commands
            commands[commands.length - 1]
        );

        java.util.List<JButton> buttons = SwingUtils.getDescendantsOfType(JButton.class,op,true);
        Container parent = buttons.get(0).getParent();
        parent.setLayout( new GridLayout(2,5,5) );

        add(op);
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new SSCCE(),BorderLayout.LINE_START);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}

上面的代码搜索已添加到选项窗格中的按钮,然后找到父容器并将容器的布局管理器更改为GridLayout。您还将需要SwingUtils类。

要实施第二步,您需要Read the API for the JOptionPane。它包含将代码添加到JDialog并实现选项窗格功能所需的代码。