我正在尝试构建Java GUI,其中包括几个选项卡。 在其中一个选项卡中,我希望同时具有可滚动的JTextArea,以及顶部/底部的一些与JTextArea交互的按钮。我无法弄清楚如何将两者都放到同一个标签中,我要么得到按钮和不可滚动的jtextarea,要么只是可滚动的jtextarea。我也不想在其他标签中显示按钮。这是我的代码:
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添加到选项卡。任何帮助都会非常感激。
答案 0 :(得分: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
答案 1 :(得分:0)
您可以这样做:
JPanel tab = new JPanel()
JPanel tabWithButtons = new JPanel()
JPanel tabWithScrollPanel = new JPanel()
tab.add(tabWithScrollPanel)
tab.add(tabWithButtons)
IMO这是更好的方法,因为我认为按钮不应该包含在JScrollPane中,并且它们应该始终可见
当然,您必须将所有元素添加到正确的JPanel中。
另外,您可以尝试使用包含所有元素的面板的宽度/高度设置,或者ScrollArea面板可能很大?