【问题标题】:Change button layout in JOptionPane.showOptionDialog()在 JOptionPane.showOptionDialog() 中更改按钮布局
【发布时间】:2020-09-21 00:38:25
【问题描述】:

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

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

具体如何做到这一点?

这是我的代码:

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]);
}

【问题讨论】:

  • 如果您的对话框需要更复杂,请不要使用 JOptionPane。 Intead,创建并显示一个模态 JDialog。

标签: java swing joptionpane


【解决方案1】:

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

因此,正确的解决方案是创建一个自定义模态 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, 0, 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 并实现选项窗格功能所需的代码。

【讨论】:

  • 很高兴它有帮助。不要忘记通过单击复选标记(答案旁边)来“接受”答案,这样人们就知道问题已经解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2016-10-24
  • 2018-05-28
相关资源
最近更新 更多