Java 如何在JOptionPane中垂直排列按钮?

Java 如何在JOptionPane中垂直排列按钮?,java,swing,layout-manager,Java,Swing,Layout Manager,我正在尝试制作一个基于文本的冒险游戏,屏幕顶部是一个JScrollPane中的JTextArea,显示正在发生的事情,底部是一个JOptionPane,您可以在其中单击按钮进行选择。默认情况下,按钮水平排列。唯一的问题是,如果我有太多的按钮,就没有空间放新的按钮,它们就会被从屏幕上推下来。我需要它们垂直排列,因为它们比高的要胖。JOptionPane和JScrollPane嵌套在gridLayout中,gridLayout嵌套在JFrame中。这是我用来制作框架的方法: /** * Make

我正在尝试制作一个基于文本的冒险游戏,屏幕顶部是一个JScrollPane中的JTextArea,显示正在发生的事情,底部是一个JOptionPane,您可以在其中单击按钮进行选择。默认情况下,按钮水平排列。唯一的问题是,如果我有太多的按钮,就没有空间放新的按钮,它们就会被从屏幕上推下来。我需要它们垂直排列,因为它们比高的要胖。JOptionPane和JScrollPane嵌套在gridLayout中,gridLayout嵌套在JFrame中。这是我用来制作框架的方法:

/**
 * Make the frame and everything in it
 */
private void makeFrame()
{
    frame = new JFrame("Adventure!");

    JPanel contentPane = (JPanel)frame.getContentPane();
    contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));
    contentPane.setLayout(new GridLayout(0, 1));

    textArea = new JTextArea(20, 50);       
    textArea.setEditable(false);
    textArea.setLineWrap(true);
    textArea.setFont(new Font("font", Font.BOLD, 15));
    JScrollPane scrollPane = new JScrollPane(textArea);
    contentPane.add(textArea);

    optionPane = new JOptionPane("", JOptionPane.DEFAULT_OPTION, JOptionPane.DEFAULT_OPTION, null, null);
    contentPane.add(optionPane);

    frame.pack();
    // place the frame at the center of the screen and show
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
    frame.setVisible(true);
}

网格布局中使用
JButtons
而不是使用
JOptionPane
。您可以这样指定创建时需要跨下的组件数量:
newgridlayout(0,3)
。这将导致3个按钮堆叠在一起,第一个
int
是您想要跨越的数量,第二个是您想要向下的数量。试试这个:

/**
 * Make the frame and everything in it
 */
private void makeFrame()
{
frame = new JFrame("Adventure!");

JPanel contentPane = (JPanel)frame.getContentPane();
contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));
contentPane.setLayout(new GridLayout(0, 1));

textArea = new JTextArea(20, 50);       
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setFont(new Font("font", Font.BOLD, 15));
JScrollPane scrollPane = new JScrollPane(textArea);
contentPane.add(textArea);


//This replaces your JOptionPane block
    buttonPane = new JPanel();
    buttonPane.setLayout(new GridLayout(0, 1));
    contentPane.add(buttonPane);

frame.pack();
// place the frame at the center of the screen and show
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
frame.setVisible(true);
}

“底部是一个JOptionPane”-为什么?你的问题的简短答案是“不”。你的问题的长答案是“自己动手”,但我如何将BoxLayout应用于JOptionPane中的按钮?@MadProgrammer:你建议我使用什么来代替?
//将框架放在屏幕中央,并显示维度d=Toolkit.getDefaultToolkit().getScreenSize();frame.setLocation(d.width/2-frame.getWidth()/2,d.height/2-frame.getHeight()/2)可替换为<代码>//将框架放在屏幕中央,并显示frame.setLocationRelativeTo(null)以最小尺寸提供ASCII艺术或GUI预期布局的简单绘图,如果可以调整大小,则具有更大的宽度和高度。