2010-05-03 30 views
1

我想添加一個JList到GUI,但是想知道如何定位它?我希望它出現在TextArea的右側,以便將數據發送到GUI進行選擇。Java在GUI上定位列表

任何人都可以建議如何做到這一點?下面是代碼(注:Java和GUI的很新)

protected static void createAndShowGUI() { 
     GUI predict = new GUI(); 
     JFrame frame = new JFrame("Phone V1.0"); 

     frame.setContentPane(predict.createContentPane()); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setMinimumSize(new Dimension(300, 400)); 
     frame.setVisible(true); // Otherwise invisible window 
} 

private JPanel createContentPane() { 
    JPanel pane = new JPanel(); 

    TextArea = new JTextArea(5, 10); 
    TextArea.setEditable(false); 
    TextArea.setLineWrap(true); 
    TextArea.setWrapStyleWord(true); 
    TextArea.setWrapStyleWord(true); 
    pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); 
    //Adds the buttons from Top  to Bottom 

    String[] items = {"dsfsdfd"}; 
    list = new JList(items); 
    JScrollPane scrollingList = new JScrollPane(list); 
    int orient = list.getLayoutOrientation(); 

    JPanel window = new JPanel(); 
    pane.add(window); 

    JPanel buttonPanel = new JPanel(); 
    buttonPanel.setLayout(new GridLayout(5, 3)); 

    JButton[] buttons = new JButton[] { 
     new JButton("Yes"), 
     new JButton(""), 
     new JButton("Clr"), 
     new JButton("1"), 
     new JButton("2abc"), 
     new JButton("3def"), 
     new JButton("4ghi"), 
     new JButton("5jkl"), 
     new JButton("6mno"), 
     new JButton("7pqrs"), 
     new JButton("8tuv"), 
     new JButton("9wxyz"), 
     new JButton("*+"), 
     new JButton("0_"), 
     new JButton("^#") 
    }; // Array Initialiser 

    for (int i = 0; i < buttons.length; i++) { 
     buttonPanel.add(buttons[i]); 
     buttons[i].addActionListener(this); 
    } 
    pane.add(TextArea); 
    pane.add(list); 
    pane.add(buttonPanel); 


    return pane; 
} 

回答

0

我可以給你推薦FormLayout。在我發現這個佈局之前,我有一個真正的痛苦GridBagLayoutFormLayout功能更強大,學習和使用起來更方便,而且免費。給它一個機會。

1

將您的TextArealistBorderLayout管理器包裝在一個新面板中。基本上,BorderLayout管理器允許您使用北,南,東,西和中心座標來排列組件。由於父容器具有更多可用空間,因此中心的組件佔用所有可用空間。

private JPanel createContentPane() { 
    JPanel pane = new JPanel(); //this is your main panel 
    JPanel textAreaPanel = new JPanel(new BorderLayout()); //the wrapper 

    //Some more code... 

    //Then at the end 
    //Make your TextArea take the center 
    textAreaPanel.add(TextArea, BorderLayout.CENTER); 
    //And the list to the east 
    textAreaPanel.add(list, BorderLayout.EAST); 
    pane.add(textAreaPanel); 
    pane.add(buttonPanel); 

    return pane; 
} 

很酷的事情是,你可以在其他面板裏面窩板,將它們添加不同的佈局管理器,讓您想要的佈局。

在無關的筆記上,請嘗試關注Java naming conventions。而不是JTextArea TextArea使用JTextArea textArea。它使您和閱讀代碼的人更容易理解它。

2

閱讀Swing教程Using Layout Mananger中的部分。沒有必要只使用一個佈局管理器。您可以嵌套佈局管理器以獲得所需的效果。

0

正如其他人所建議的,熟悉佈局管理器的概念。有幾個標準的Swing API和幾個很好的第三方API。

此外,您還需要將JList添加到滾動窗格(JScrollPane)。您可能想要考慮將添加到拆分窗格(JSplitPane)。而且通過考慮我並不是說「這樣做是因爲網絡上的一些人這麼說」我的意思是「如果它對最終用戶有意義的話,就這樣做」。