可调整大小的窗口,带3个比例面板

时间:2014-11-14 04:17:46

标签: java swing user-interface

我希望有一个窗口,其中包含两个垂直比例为3:1的面板,而较大的一个面板包含一个方形面板。另外,我想在方形面板的中心画一些东西,比如圆圈。

我的程序的行为表明3:1的比例和方形之间存在冲突。调整大小时,形状奇怪地跳跃。最终结果不正确,第一部分不成立。此外,圆圈偏离中心。

我是java的新手,因此,我将非常感谢有关错误以及如何以正确方式实现此问题的任何评论。

结果如下:

enter image description here

我希望:(1)红色面板作为方形(2)蓝色面板严格比绿色面板(3)高3倍,在红色框中间有圆圈。

这是我的代码:

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class ProportionalPanels
{
    private JFrame window = new JFrame("Proportional resizable panels");
    private JPanel allContaining = new JPanel( new GridBagLayout() );
    private JPanel upper = new JPanel( new GridBagLayout() );
    private JPanel lower = new JPanel();
    private JPanel square = new JPanel()
    { 
        @Override
        public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            Container c = getParent();
            if (c != null) {
                d = c.getSize();
            } else {
                return new Dimension(10, 10);
            }
            int w = (int) d.getWidth();
            int h = (int) d.getHeight();
            int s = (w < h ? w : h);
            return new Dimension(s, s);
        }

        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            g.setColor(Color.GRAY);
            int x = this.getWidth(), y = this.getHeight(); 
            g.fillOval(x/2,y/2,x/4,y/4);
        }
    };

    public ProportionalPanels()
    {
        // setting colors
        allContaining.setBackground(Color.WHITE);       
        square.setBackground(Color.RED);
        upper.setBackground(Color.BLUE);
        lower.setBackground(Color.GREEN);

        // setting upper
        upper.add(square);

        // setting allContaining
        GridBagConstraints g = new GridBagConstraints();
        g.gridx = g.gridy = 0;
        g.weightx = 1; g.weighty = 0.75;
        g.fill = GridBagConstraints.BOTH;
        allContaining.add(upper,g);
        g.gridy += 1;
        g.weighty = 0.25;
        g.fill = GridBagConstraints.BOTH;
        allContaining.add(lower,g);


        window.add(allContaining);

        // setting window
        window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        window.setLocationByPlatform(true);
        window.pack();
        window.setSize(400,200);
        window.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            public void run()
            {
                new ProportionalPanels();
            }
        });
    }
}

修改

想象一下国际象棋的简单gui,只是为了类比。一个窗口吐成两个面板,上面一个(蓝色)是包含棋盘,下面一个(绿色)是一些按钮。这些面板的唯一限制是保持垂直比例 - 上面的比例比下面的高3倍。然后,深入到面板层次结构中,上面板包含square面板(红色),它是一个正方形,具有上面板的高度,并水平放置在上面板的中间。方形面板的左侧和右侧有额外的空间,相应调整以保持红色面板正方形和绿色高度比红色小3倍。红色面板在它的中心有一些图画,这里是一个灰色的圆圈,但为了保持国际象棋的类比,它可以是棋盘或其他任何东西的图像。

1 个答案:

答案 0 :(得分:2)

我并非100%确定我理解这个问题,但是,它从未停止过我......

基本上,这使用了非常粗糙的自定义布局管理器。它将保持第一个和最后一个组件大小为3:1的比例(宽度是高度的比率)

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.LayoutManager;
import java.awt.LayoutManager2;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JPanel master = new JPanel(new PropertionalLayoutManager());
                master.add(new TestPane(), "left");
                master.add(new DrawPane(), "center");
                master.add(new TestPane(), "right");

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(master);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PropertionalLayoutManager implements LayoutManager {

        private Component left;
        private Component right;
        private Component center;

        @Override
        public void addLayoutComponent(String name, Component comp) {
            if ("center".equals(name)) {
                center = comp;
            } else if ("left".equals(name)) {
                left = comp;
            } else if ("right".equals(name)) {
                right = comp;
            }
        }

        @Override
        public void removeLayoutComponent(Component comp) {
        }

        public Dimension getSize(Dimension leftSize, Dimension centerSize, Dimension rightSize) {


            Dimension size = new Dimension();
            if (leftSize != null && right != null) {

                int width = leftSize.width;
                int height = leftSize.height;

                size.width = Math.max(width, rightSize.width) * 2;
                size.height = Math.max(height, rightSize.height);

            } else if (leftSize != null) {

                size.width = leftSize.width;
                size.height = leftSize.height;

            } else if (right != null) {

                size.width = rightSize.width;
                size.height = rightSize.height;

            }

            if (center != null) {

                size.width += centerSize.width;
                size.height = Math.max(centerSize.height, size.height);

            }

            return size;

        }

        @Override
        public Dimension preferredLayoutSize(Container parent) {

            Dimension leftSize = left == null ? null : left.getPreferredSize();
            Dimension centerSize = right == null ? null : right.getPreferredSize();
            Dimension rightSize = center == null ? null : center.getPreferredSize();

            return getSize(leftSize, centerSize, rightSize);

        }

        @Override
        public Dimension minimumLayoutSize(Container parent) {

            Dimension leftSize = left == null ? null : left.getMinimumSize();
            Dimension centerSize = right == null ? null : right.getMinimumSize();
            Dimension rightSize = center == null ? null : center.getMinimumSize();

            return getSize(leftSize, centerSize, rightSize);

        }

        @Override
        public void layoutContainer(Container parent) {

            // Get rid of anything else that might have been added...
            for (Component comp : parent.getComponents()) {

                comp.setBounds(0, 0, 0, 0);

            }

            int width = parent.getWidth();
            int height = parent.getHeight();

            int outterWidth = height / (3 / 1);

            if (left != null) {

                left.setBounds(0, 0, outterWidth, height);

            }

            if (right != null) {

                right.setBounds(width - outterWidth, 0, outterWidth, height);

            }

            if (center != null) {

                center.setBounds(outterWidth, 0, width - (outterWidth * 2), height);

            }

        }

    }

    public class DrawPane extends JPanel {

        public DrawPane() {
            setBackground(Color.BLUE);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(100, 300);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int x = (getWidth() - (getWidth() / 4)) / 2;
            int y = (getHeight()- (getHeight() / 4)) / 2;
            g.setColor(Color.GRAY);
            g.fillOval(x, y, getWidth() / 4, getHeight() / 4);
        }

    }

    public class TestPane extends JPanel {

        private JLabel size;

        public TestPane() {
            setBackground(Color.GREEN);
            setLayout(new GridBagLayout());
            size = new JLabel();
            addComponentListener(new ComponentAdapter() {
                @Override
                public void componentResized(ComponentEvent e) {
                    size.setText(getWidth() + "x" + getHeight());
                }
            });
            add(size);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(100, 300);
        }

    }

}

<强>更新

更像是......

Square Square

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JPanel master = new JPanel(new SquareLayoutManager());
                master.setBackground(Color.BLUE);
                master.add(new DrawPane());

                JPanel green = new JPanel();
                green.setBackground(Color.GREEN);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());

                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                gbc.weightx = 1;
                gbc.weighty = 0.66666666666667;
                gbc.fill = GridBagConstraints.BOTH;
                frame.add(master, gbc);

                gbc.gridy++;
                gbc.weighty = 0.33333333333333;
                frame.add(green, gbc);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class SquareLayoutManager implements LayoutManager {

        @Override
        public void addLayoutComponent(String name, Component comp) {
        }

        @Override
        public void removeLayoutComponent(Component comp) {
        }

        @Override
        public Dimension preferredLayoutSize(Container parent) {

            int width = 0;
            int height = 0;
            for (Component comp : parent.getComponents()) {
                width = Math.max(comp.getPreferredSize().width, width);
                height = Math.max(comp.getPreferredSize().width, height);
            }

            // You could define rows and columns and blah, blah, blah, but I'm to lazy...

            return new Dimension(Math.max(width, height) * parent.getComponentCount(), Math.max(width, height));

        }

        @Override
        public Dimension minimumLayoutSize(Container parent) {

            return preferredLayoutSize(parent);

        }

        @Override
        public void layoutContainer(Container parent) {

            Insets insets = parent.getInsets();
            int size = (parent.getHeight() - (insets.bottom + insets.top));
            int x = (parent.getWidth() - (insets.left + insets.right) - size) / 2;
            int y = insets.top;
            for (Component comp : parent.getComponents()) {
                comp.setBounds(x, y, size, size);
                x += size; // Could define a gap, but, lazy...
            }

        }

    }

    public class DrawPane extends JPanel {

        public DrawPane() {
            setBackground(Color.RED);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(100, 300);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int x = (getWidth() - (getWidth() / 4)) / 2;
            int y = (getHeight() - (getHeight() / 4)) / 2;
            g.setColor(Color.GRAY);
            g.fillOval(x, y, getWidth() / 4, getHeight() / 4);
        }

    }

}