2016-01-22 49 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); 
}