2010-05-03 24 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)。而且通过考虑我并不是说“这样做是因为网络上的一些人这么说”我的意思是“如果它对最终用户有意义的话,就这样做”。