你好,我正在使用swing制作桌面应用程序,在这里使用了jscrollpane。我想在jscrollpane中添加多个按钮,但目前只能添加单个按钮。请问如何实现?
下面是我的代码:
public class AddingToJScrollPane {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton jButton1 = new JButton("Hello");
JButton jButton2 = new JButton("Hello");
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.setViewportBorder(new LineBorder(Color.RED));
jScrollPane.getViewport().add(jButton1,jButton2);
frame.add(jScrollPane, BorderLayout.NORTH);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
更新代码
public class AddingToJScrollPane {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout( new GridLayout() );
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(panel);
JButton jButton1 = new JButton("Hello");
JButton jButton2 = new JButton("He");
// jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.setViewportBorder(new LineBorder(Color.RED));
// jScrollPane.getViewport().add(panel);
frame.add(jScrollPane, BorderLayout.NORTH);
panel.add(jButton1);
panel.add(jButton2);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
我该如何实现我想要的输出?感谢您提前帮忙。