问题
I am using Miglayout to define a layout for my program. The problem is the JScrollPane
prevents the JButton shrinking below its preferred size. The minimum, preferred, and maximum widths for the JButton
are set like this, "w 300:600:900" //min:pref:max
.
What is the best way to fix this problem?
SSSCE
import java.awt.*;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;
public class ButLay extends JFrame {
private ButLay() {
super("Button Layout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("", "grow", "grow"));
createPanel();
setSize(800, 200);
setVisible(true);
}
JPanel panel = new JPanel(new MigLayout("", "grow", "grow"));
JScrollPane scroll;
JButton button = new JButton("Button");
private void createPanel() {
panel.add(button, "gapleft 100, align right, w 300:600:900, south");
scroll = new JScrollPane(panel);
getContentPane().add(scroll, "grow");
}
public static void main(String[] args) {
new ButLay();
}
}
回答1:
The default behaviour of a JScrollPane is to display the component in the scroll pane at its preferred size so that the scrollbars can appear as required.
If you want to change the behaviour then you can try to implement the Scrollable
interface on your panel. You might be able to override the getScrollableTracksViewportWidth()
method to return true
. Now your panel should resize as the viewport of the scrollpane resizes. However using this approach your won't get a scrollbar if you make the viewport too small.
If you want the scrollbar in the above situation, then you may also need to override the getPreferredSize()
method to return the minimum size when the preferredSize is greater than the size of the viewport.
You can also check out Scrollable Panel which implements the Scrollable
interface for you and allows you to customize the behaviour with some convenience methods.
来源:https://stackoverflow.com/questions/40651526/jscrollpane-prevents-components-shrinking-below-their-preferred-size