Java – how to add JButton to JScrollPane?
•
Java
Hi, I want to make a desktop application here. I'm using JScrollPane I want to add a multipul button to the JScrollPane I can only add a single button. What should I do
My code is as follows
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);
}
}
Updated code
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);
}
}
How can I achieve the output I want? Thank you in advance
Solution
Add a button to a panel with an appropriate layout (such as GridLayout or flowlayout) Add a panel to the scroll pane
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
