2016-01-22 73 views
0

我试图做一个基于文本的冒险游戏,其中屏幕的顶部是一个JScrollPane内的JTextArea,显示发生了什么,底部是一个JOptionPane,点击一个按钮做出选择。默认情况下,按钮水平排列。唯一的问题是,如果我有太多的按钮,没有空间用于新的按钮,并且它们被推离屏幕。我需要他们垂直排列,因为他们比他们高。 JOptionPane和JScrollPane嵌套在嵌套在JFrame中的gridLayout中。这是我使用,使框架的方法:如何在JOptionPane中垂直排列按钮?

/** 
* 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); 
} 
+1

*“and the bottom is a JOptionPane”* - 为什么?你的问题的简短答案是,不。对你的问题的长答案是,自己动手 – MadProgrammer

+1

使用“BoxLayout”。 – user1803551

+0

但是,如何将一个BoxLayout应用于JOptionPane中的按钮? –

回答

0

而不是使用一个JOptionPane的,在GridLayout使用JButtons。您可以在创建后指定要创建多少个组件,如下所示:new GridLayout(0, 3)。这会导致3个按钮堆叠在一起,第一个是你想要的数量,第二个是你想要的数量。试试这个:

/** 
* 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); 
}