问题
I have to use JScrollPane
in my Project but it is not working.
I have pasted my code where I use a JSCrollPane
in my main JPanel.
frame = new JFrame();
frame.setBounds(100, 100, 1179, 733);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane_1.setBounds(0, 0, 1163, 694);
frame.getContentPane().add(scrollPane_1);
JPanel panel = new JPanel();
scrollPane_1.setViewportView(panel);
panel.setLayout(null);
回答1:
Setting the layout to Null means you need to handle the placement manually --> Specify the pixel location and handle the size of the container.
A layout manager handles this placement for you. The manager calculates its preferred size based on its content. The ScrollPane uses this calculated size from the layout manager.
This means you should use a layout manager, place your components within it. The rest should work automatically.
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500, 500);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(30, 15));
for (int row = 0; row < 30; row++) {
for (int col = 0; col < 15; col++) {
panel.add(new Button("Button" + row + "/" + col));
}
}
frame.getContentPane().add(new JScrollPane(panel));
frame.setVisible(true);
}
回答2:
I am not sure which layout you are using, but you need to set your panel layout something like this
panel.setLayout(new FormLayout(
"default:grow",
"fill:default:grow"));
来源:https://stackoverflow.com/questions/44450172/jscrollpane-is-not-working-in-jpanel