在Swing中按宽度调整容器中的组件

时间:2016-01-09 20:29:41

标签: java swing layout-manager

我在创建自己的swing组件时遇到问题。我想创建将呈现一些图像的组件,它将按比例适合当前窗口(或容器)大小。

问题在于我无法知道容器中组件的真实可用空间(没有内容,边框,可能是其他东西......)。

此示例显示了问题:

public class Main
{
    static class MyComponent extends JComponent
    {
        @Override
        public Dimension getPreferredSize()
        {
            if(isShowing())
            {
                int width = getParent().getSize().width - 4;
                Dimension dimension = new Dimension(width, (int)(width / 0.8));
                System.out.println(dimension);
                return dimension;
            }
            return super.getPreferredSize();
        }

        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);

            g.setColor(Color.WHITE);
            g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(Color.RED);
            g.fillOval(0, 0, getWidth(), getHeight());
        }
    }

    public static void main(String... args)
    {
        JFrame frame = new JFrame("Test");
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBackground(Color.DARK_GRAY);
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(2, 2, 2, 2);
        c.gridx = c.gridy = 0;
        panel.add(new MyComponent(), c);
        c.gridy++;
        panel.add(new MyComponent(), c);
        frame.add(new JScrollPane(panel));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }
}

如果从getParent().getSize().width - 4表达式中删除4(从插图中向左和向右)并启动,您将看到该组件将无限增加其大小。

在上面的代码中,我获得了容器的全宽,但是我需要可用的宽度,以便组件不会一次又一次地触发容器调整大小。

还是有其他方法可以正常使用组件吗?

0 个答案:

没有答案