繁体   English   中英

如何使用菜单在 java swing 的不同布局之间切换?

[英]How do I switch between different layouts for java swing using a menu?

我想制作一个没有默认布局的 JPanel 应用程序。 我希望能够使用菜单中的选项更改布局。 例如,如果我有一个控件将三个图像图标添加到 JPanel ,则这些图标的大小和位置应由框架的当前布局管理器确定。 因此,如果我将 3 个图像图标添加到边框布局(将它们添加到南、东和中心位置),将布局切换到流布局应该使它们按从右到左的顺序显示,无需调整大小。

我很困惑如何去做。 有没有办法像这样在同一个 JPanel 中切换布局?

要在每个菜单操作后动态更改布局,请使用其约束设置新布局并调用 revalidate() 方法。 检查以下代码的 actionPerformed() 方法。

public class LayoutController extends JFrame implements ActionListener {

    JMenuItem flowLayout;
    JMenuItem borderLayout;
    JMenuItem gridLayout;

    JPanel panel;

    JButton button1;
    JButton button2;
    JButton button3;

    public LayoutController() {
        setSize(600, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        panel = new JPanel();
        panel.setLayout(null); // no default layout
        panel.setSize(600, 600);

        flowLayout = new JMenuItem("Flow Layout");
        flowLayout.addActionListener(this);
        borderLayout = new JMenuItem("Border Layout");
        borderLayout.addActionListener(this);
        gridLayout = new JMenuItem("Grid Layout");
        gridLayout.addActionListener(this);

        // menu to change layout dynamically
        JMenu fileMenu = new JMenu("Layout");
        fileMenu.add(flowLayout);
        fileMenu.add(borderLayout);
        fileMenu.add(gridLayout);
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);

        // Customize your components
        button1 = new JButton("IMAGE1");
        button2 = new JButton("IMAGE2");
        button3 = new JButton("IMAGE3");

        panel.add(button1);
        panel.add(button2);
        panel.add(button3);

        add(panel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LayoutController().setVisible(true);
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //Customize your code here
        if (e.getSource() == flowLayout) {
            //flow layout with right alignment
            panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        } else if (e.getSource() == borderLayout) {
            // border layout with constraints
            BorderLayout layout = new BorderLayout();
            layout.addLayoutComponent(button1, BorderLayout.SOUTH);
            layout.addLayoutComponent(button2, BorderLayout.EAST);
            layout.addLayoutComponent(button3, BorderLayout.CENTER);
            panel.setLayout(layout);
        } else if (e.getSource() == gridLayout) {
            // grid layout with 2 rows and 2 columns
            panel.setLayout(new GridLayout(2, 2));
        }
        panel.revalidate();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM