单击按钮更改面板大小

发布于 2024-11-29 23:06:36 字数 4925 浏览 2 评论 0原文

我有以下代码:

package in.res.num.tapb.ui;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

class MainClass extends JPanel {
    public MainClass() {
        Registration registration = new Registration();
        ButtonPanel buttonPanel = new ButtonPanel();
        buttonPanel.setRegistration(registration);

        buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
        registration.setBorder(BorderFactory.createTitledBorder("Registration Panel"));

        setLayout(new BorderLayout());
        add(registration, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Registration");
        frame.getContentPane().add(new MainClass());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }

    @SuppressWarnings("serial")
    private class ButtonPanel extends JPanel {
        private Registration registration;

        public ButtonPanel() {
            setLayout(new GridLayout(1, 0, 10, 0));     
            for (final String keyText : Registration.KEY_TEXTS) {
                JButton btn = new JButton(keyText);
                btn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (registration != null) {
                            registration.swapView(keyText);
                        }
                    }
                });
                add(btn);
            }
        }

        public void setRegistration(Registration registration) {
            this.registration = registration;
        }
    }

    private static class Registration extends JPanel {
        private static final Dimension PREF_SIZE = new Dimension(450, 300);
        public static final String USER_AGREEMENT = "User Agreement";
        public static final String USER_INFO = "User Information";
        public static final String ENROLLMENT = "Enrollment";
        public static final String[] KEY_TEXTS = { USER_AGREEMENT, USER_INFO, ENROLLMENT };
        private CardLayout cardlayout = new CardLayout();
        private JPanel cards = new JPanel(cardlayout);

        public Registration() {
            cards.add(createUserAgreePanel(), USER_AGREEMENT);
            cards.add(createUserInfoPanel(), USER_INFO);
            cards.add(createEnrollmentPanel(), ENROLLMENT);
            setLayout(new BorderLayout());
            add(cards, BorderLayout.CENTER);
        }



        private JPanel createEnrollmentPanel() {
            JPanel enrol = new JPanel();
            enrol.setSize(new Dimension(400, 200));
            enrol.add(new JLabel("Enrollment"));
            return enrol;
        }

        private JPanel createUserAgreePanel() {
            JPanel userAgree = new JPanel();
            userAgree.setSize(new Dimension(200, 300));
            userAgree.add(new JLabel("User Agreement"));
            return userAgree;
        }

        private JPanel createUserInfoPanel() {
            JPanel userInfo = new JPanel();
            userInfo.setSize(new Dimension(300, 400));
            userInfo.add(new JLabel("User Information"));
            return userInfo;
        }

        public void swapView(String key) {
            cardlayout.show(cards, key);
        }

    }

}

如您所见,我想更改按钮单击时的大小。是否可以?上面的代码不起作用,我的意思是大小没有改变。如何在飞行中更改尺寸?

谢谢和问候。 编辑:

在选择 JList 行时交换面板。

    getChoicesList().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent listSelectionEvent) {
            getViewPanel().changeView(getChoicesList().getSelectedIndex());
            getChoicePanel().changeView(Constants.PanelInfo.valueOf(getEngine().getChoiceList().get(getChoicesList().getSelectedIndex()).getEnumName()).getDimensionForScrollPaneOfChoicePanel());
            ((MainFrame) getTopLevelAncestor()).pack();
        }
    });

ViewPanel#changeView(),这会交换面板:

public void changeView(int index) {
    removeAll();
    getPanels().get(index).setPreferredSize(Constants.PanelInfo.valueOf(getEngine().getChoiceList().get(index).getEnumName()).getDimensionForViewPanel());
    add(getPanels().get(index));
}

I have the following code:

package in.res.num.tapb.ui;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

class MainClass extends JPanel {
    public MainClass() {
        Registration registration = new Registration();
        ButtonPanel buttonPanel = new ButtonPanel();
        buttonPanel.setRegistration(registration);

        buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
        registration.setBorder(BorderFactory.createTitledBorder("Registration Panel"));

        setLayout(new BorderLayout());
        add(registration, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Registration");
        frame.getContentPane().add(new MainClass());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }

    @SuppressWarnings("serial")
    private class ButtonPanel extends JPanel {
        private Registration registration;

        public ButtonPanel() {
            setLayout(new GridLayout(1, 0, 10, 0));     
            for (final String keyText : Registration.KEY_TEXTS) {
                JButton btn = new JButton(keyText);
                btn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (registration != null) {
                            registration.swapView(keyText);
                        }
                    }
                });
                add(btn);
            }
        }

        public void setRegistration(Registration registration) {
            this.registration = registration;
        }
    }

    private static class Registration extends JPanel {
        private static final Dimension PREF_SIZE = new Dimension(450, 300);
        public static final String USER_AGREEMENT = "User Agreement";
        public static final String USER_INFO = "User Information";
        public static final String ENROLLMENT = "Enrollment";
        public static final String[] KEY_TEXTS = { USER_AGREEMENT, USER_INFO, ENROLLMENT };
        private CardLayout cardlayout = new CardLayout();
        private JPanel cards = new JPanel(cardlayout);

        public Registration() {
            cards.add(createUserAgreePanel(), USER_AGREEMENT);
            cards.add(createUserInfoPanel(), USER_INFO);
            cards.add(createEnrollmentPanel(), ENROLLMENT);
            setLayout(new BorderLayout());
            add(cards, BorderLayout.CENTER);
        }



        private JPanel createEnrollmentPanel() {
            JPanel enrol = new JPanel();
            enrol.setSize(new Dimension(400, 200));
            enrol.add(new JLabel("Enrollment"));
            return enrol;
        }

        private JPanel createUserAgreePanel() {
            JPanel userAgree = new JPanel();
            userAgree.setSize(new Dimension(200, 300));
            userAgree.add(new JLabel("User Agreement"));
            return userAgree;
        }

        private JPanel createUserInfoPanel() {
            JPanel userInfo = new JPanel();
            userInfo.setSize(new Dimension(300, 400));
            userInfo.add(new JLabel("User Information"));
            return userInfo;
        }

        public void swapView(String key) {
            cardlayout.show(cards, key);
        }

    }

}

As you can see I want to change the size on button click. Is it possible? The above code is not working, I mean the size is not changing. How can I change the size on fly?

Thanks and regards.
Edit:

swap the panel on selecting a row of JList.

    getChoicesList().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent listSelectionEvent) {
            getViewPanel().changeView(getChoicesList().getSelectedIndex());
            getChoicePanel().changeView(Constants.PanelInfo.valueOf(getEngine().getChoiceList().get(getChoicesList().getSelectedIndex()).getEnumName()).getDimensionForScrollPaneOfChoicePanel());
            ((MainFrame) getTopLevelAncestor()).pack();
        }
    });

ViewPanel#changeView(), this swaps the panel:

public void changeView(int index) {
    removeAll();
    getPanels().get(index).setPreferredSize(Constants.PanelInfo.valueOf(getEngine().getChoiceList().get(index).getEnumName()).getDimensionForViewPanel());
    add(getPanels().get(index));
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一笔一画续写前缘 2024-12-06 23:06:36

调整 JFrame 大小后,使用:
yourframe.validate();

After resizing the JFrame, use:
yourframe.validate();

烟沫凡尘 2024-12-06 23:06:36

使用布局管理器时,切勿使用 setSize()。确定尺寸是布局管理器的工作。您可以通过设置首选或最小或最大尺寸向布局管理器提供提示。但是,不建议您这样做,因为组件和面板应以其首选尺寸显示,这将由您使用的布局管理器确定。如果您确实覆盖了大小,那么代码应该是:

// enrol.setSize(new Dimension(400, 200));
enrol.setPreferredSize(new Dimension(400, 200));

但是,这仍然无法按照您想要的方式工作,因为 CardLayout 的工作是确定使用 CardLayout 添加到面板的所有面板的最大尺寸。因此,当您从一个面板切换到另一个面板时,您无法获得每个面板的大小。这对于用户来说是更好的体验,因为用户不希望每次点击按钮时看到帧大小不断变化。

如果您确实希望每次单击按钮时框架都会更改大小,则基本代码将是:

mainPanel.remove(oldPanel);
mainPanel.add(newPanel);
frame.pack();

然后主面板的布局管理器将观察新添加的面板的首选大小。

You should never use setSize() when using a layout manager. It is the job of the layout manager to determine the size. You can provide hints to the layout manager by setting the peferred or minimum or maximum sizes. However it is not recommend that you do this since components and panels should be displayed at their preferred size which will be determined by the layout manager you are using. If you did override the size then the code should be:

// enrol.setSize(new Dimension(400, 200));
enrol.setPreferredSize(new Dimension(400, 200));

However, this still won't work the way you want because the job of the CardLayout is to determine the largest size of all panels added to the panel using a CardLayout. So when you swap from panel to panel you don't get the size of each individual panel. This is s better experience for the user because the user doesn't want to see the frame size keep changing every time they hit a button.

If you did want to have the frame change size every time you click on a button then the basic code would be:

mainPanel.remove(oldPanel);
mainPanel.add(newPanel);
frame.pack();

Then the layout manager of the main panel will observe the preferred size of the newlay added panel.

只是在用心讲痛 2024-12-06 23:06:36

作为 camickr 的答案的具体示例,以下程序显示当通过 pack() 调整框架大小时,如何依赖组件的首选大小。 faux 内容是一系列标签,但任何 JComponent 都可以。由于内容是动态重新创建的,因此它可以根据程序中的其他条件进行更改。

在此处输入图像描述

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/** @see https://stackoverflow.com/questions/7059278 */
class MainPanel extends JPanel {

    private static final String title = "Registration Panel";
    private JFrame frame = new JFrame(title);
    private JPanel registration = new JPanel();

    public MainPanel() {
        this.setLayout(new BorderLayout());
        registration.setBorder(BorderFactory.createTitledBorder(title));
        registration.add(PanelType.USER_AGREEMENT.panel);
        ButtonPanel buttonPanel = new ButtonPanel();
        buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
        add(registration, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void display() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new MainPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainPanel().display();
            }
        });
    }

    private class ButtonPanel extends JPanel {

        public ButtonPanel() {
            for (final PanelType panel : PanelType.values()) {
                final JButton button = panel.button;
                this.add(button);
                button.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        registration.removeAll();
                        registration.add(panel.create());
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                    }
                });
            }
        }
    }

    private enum PanelType {

        USER_AGREEMENT("User Agreement", 2),
        USER_INFO("User Information", 4),
        ENROLLMENT("Enrollment Form", 6);
        private String name;
        private int count;
        private JButton button;
        private JPanel panel;

        private PanelType(String name, int count) {
            this.name = name;
            this.count= count;
            this.button = new JButton(name);
            this.panel = create();
        }

        private JPanel create() {
            this.panel = new JPanel(new GridLayout(0, 1));
            this.panel.add(new JLabel(name));
            this.panel.add(new JLabel(" "));
            for (int i = 0; i < count; i++) {
                this.panel.add(new JLabel("Label " + String.valueOf(i + 1)));
                            }
            return panel;
        }
    }
}

As a concrete example of camickr's answer, the program below shows how to rely on the preferred size of components as the frame is resized via pack(). The faux content is a series of labels, but any JComponent will do. As the content is recreated dynamically, it can change according to other conditions in the program.

enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/** @see https://stackoverflow.com/questions/7059278 */
class MainPanel extends JPanel {

    private static final String title = "Registration Panel";
    private JFrame frame = new JFrame(title);
    private JPanel registration = new JPanel();

    public MainPanel() {
        this.setLayout(new BorderLayout());
        registration.setBorder(BorderFactory.createTitledBorder(title));
        registration.add(PanelType.USER_AGREEMENT.panel);
        ButtonPanel buttonPanel = new ButtonPanel();
        buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
        add(registration, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void display() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new MainPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainPanel().display();
            }
        });
    }

    private class ButtonPanel extends JPanel {

        public ButtonPanel() {
            for (final PanelType panel : PanelType.values()) {
                final JButton button = panel.button;
                this.add(button);
                button.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        registration.removeAll();
                        registration.add(panel.create());
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                    }
                });
            }
        }
    }

    private enum PanelType {

        USER_AGREEMENT("User Agreement", 2),
        USER_INFO("User Information", 4),
        ENROLLMENT("Enrollment Form", 6);
        private String name;
        private int count;
        private JButton button;
        private JPanel panel;

        private PanelType(String name, int count) {
            this.name = name;
            this.count= count;
            this.button = new JButton(name);
            this.panel = create();
        }

        private JPanel create() {
            this.panel = new JPanel(new GridLayout(0, 1));
            this.panel.add(new JLabel(name));
            this.panel.add(new JLabel(" "));
            for (int i = 0; i < count; i++) {
                this.panel.add(new JLabel("Label " + String.valueOf(i + 1)));
                            }
            return panel;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文