2014-12-05 64 views
0

我正在尝试构建一个Java GUI,其中包含多个选项卡。 在其中一个选项卡中,我希望同时具有可滚动的JTextArea以及与JTextArea交互的顶部/底部的一些按钮。我无法弄清楚如何将两者都放到同一个选项卡中,我要么获取按钮和不可滚动的jtextarea,要么只是可滚动的jtextarea。我也不想在其他标签中显示按钮。这里是我的代码:将按钮和可滚动面板添加到选项卡 - Java

private final JTextArea music = new JTextArea(); 
private final JTextArea button = new JTextArea(); 
private final JTextArea test = new JTextArea(); 
private final JTabbedPane tab = new JTabbedPane(); 
private JTable table; 

music.append(newPlaylist.toString()); 
JFrame frame = new JFrame("GUI"); 
frame.setTitle("Music File Organiser"); 

JPanel panel = new JPanel(); 
panel.setLayout(new FlowLayout(FlowLayout.CENTER)); 
JButton button1 = new JButton("Hello"); 
JButton button2 = new JButton("Sort by Album Title"); 
JButton button3 = new JButton("Sort by Track Title"); 

button1.addActionListener(new ActionListener() {code}; 
button2.addActionListener(new ActionListener() {code}; 
button3.addActionListener(new ActionListener() {code}; 

panel.add(music); 
panel.add(button1); 
panel.add(button2); 
panel.add(button3); 

JScrollPane scroll = new JScrollPane(panel); 
JScrollPane scroll2 = new JScrollPane(table); 

tab.add("Music Files", scroll); 
tab.add("Table", scroll2); 

this.add(tab); 
frame.setLocationRelativeTo(null); 
this.setSize(1200, 1000); 
this.setVisible(true); 
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

该标签是第一个。如何将按钮添加到“滚动”?我在这里尝试的方式是将JTextArea“音乐”添加到面板中,然后将按钮添加到同一个面板,然后将面板添加到JScrollPane,然后将JScrollPane添加到选项卡。任何帮助真的会被赞赏。

回答

2

将您的视觉元素封装到子面板中。

JPanel buttonPanel = new JPanel(); //panel for buttons. 
buttonPanel.add(button1); 
buttonPanel.add(button2); 
buttonPanel.add(button3); 

JScrollPane scroll = new JScrollPane(music); //scrollable pane for JTextArea 

panel.add(buttonPanel); 
panel.add(scroll); //add sub-components to panel for tab 

/*here you would add some layout code to fit the panel and scroll into the associated spaces */ 

tab.add("Music Files", panel); //add panel to tab 
+0

儿童面板听起来很聪明。但我怎样才能“添加一些布局代码”面板?我的意思是,它是同一个面板,所以我如何告诉buttonPanel保持在顶部并滚动以保持底部? – jogorm 2014-12-05 15:26:32

+0

[如何使用LayoutManager](https://docs.oracle.com/javase/tutorial/uiswing/layout/using.html)您也可以使用像[WindowBuilder](https:// eclipse)这样的GUI设计工具。 org/windowbuilder /)来查看你的设计而不必重新编译。 – Compass 2014-12-05 15:29:30

+0

非常了解这一点,但WindowBuilder太容易:) 现在进一步了,同时获得滚动和按钮,但只要我开始滚动,buttonpane就会消失.. – jogorm 2014-12-05 15:35:23

0

你可以做这样的事情:

JPanel tab = new JPanel() 
    JPanel tabWithButtons = new JPanel() 
    JPanel tabWithScrollPanel = new JPanel() 

    tab.add(tabWithScrollPanel) 
    tab.add(tabWithButtons) 

IMO这是更好的办法,因为我认为应该按钮不被包含在JScrollPane中,他们应该可以看到所有的时间

当然,您必须将所有元素添加到正确的JPanel。

此外,你可以尝试与包含所有元素的面板的宽度/高度设置,也许ScrollArea面板是大?

相关问题