JScrollPane防止组件缩小到其首选大小以下 [英] JScrollPane prevents components shrinking below their preferred size

查看:87
本文介绍了JScrollPane防止组件缩小到其首选大小以下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Miglayout 为我的程序定义布局.问题是JScrollPane阻止JButton缩小到其首选大小以下. JButton的最小,首选和最大宽度设置为"w 300:600:900" //min:pref:max.

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();
    }
}

推荐答案

JScrollPane的默认行为是在滚动窗格中以其首选大小显示组件,以便可以根据需要显示滚动条.

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.

如果要更改行为,则可以尝试在面板上实现Scrollable界面.您可能可以覆盖getScrollableTracksViewportWidth()方法以返回true.现在,您的面板应该随着滚动窗格的视口大小而调整大小.但是,如果您将视口设置得太小,则使用这种方法将不会获得滚动条.

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.

如果您希望在上述情况下使用滚动条,那么当preferredSize大于视口的大小时,您可能还需要覆盖getPreferredSize()方法以返回最小大小.

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.

您还可以查看可滚动面板,它可以实现Scrollable界面供您使用,并允许您使用一些便捷方法来自定义行为.

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.

这篇关于JScrollPane防止组件缩小到其首选大小以下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆