问题
I'm tried to add a JPanel to a JScrollPane using:
panel1 Panel1 = new panel1();
jScrollPane1.setViewportView(Panel1);
and it worked. But the problem is scrollPane doesn't show scroll bars even the Panel1 is bigger. (I'm working with NetBeans & panel1 is a jpanel form)
回答1:
Override, getPreferredSize() method for the said JScrollPane
, you might be able to see the Scroll Bar. Or one can simply call setPreferredSize(), though as stated in the API
Sets the preferred size of this component. If preferredSize is null, the UI will be asked for the preferred size
overriding will be beneficial, as it tends to define some appropriate dimensions to the said JComponent
.
Something like this:
JScrollPane scroller = new JScrollPane() {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
};
scroller.setViewportView(panelWithScroll);
One example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelScroller {
private void displayGUI() {
JFrame frame = new JFrame("Swing Worker Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
JPanel panelWithScroll = new JPanel();
panelWithScroll.setLayout(new GridLayout(0, 1, 5, 5));
JScrollPane scroller = new JScrollPane() {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
};
scroller.setViewportView(panelWithScroll);
//scroller.setPreferredSize(new Dimension(300, 200));
for (int i = 0; i < 20; i++) {
panelWithScroll.add(new JLabel(Integer.toString(i + 1), JLabel.CENTER));
}
contentPane.add(scroller);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new PanelScroller().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
回答2:
If you only want the scrollbars to show up you can call
JScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
But that don't make them work at all.
if you wont to make them work you can try to set the preferred size of the component inside the Scrollpane to larger then size of Scrollpane and then call repaint(e.g. by make the window fullscreen)
来源:https://stackoverflow.com/questions/24639132/jscrollpane-doesnt-show-scroll-bars-when-jpanel-is-added