我正在netbeans中创建一个桌面应用程序,如果我选择一个新的菜单项,然后希望在菜单栏中显示该菜单项,然后下面的面板将更改为不全帧。帮帮我

最佳答案

您可以使用Card Layout Managers实现此类功能。

这是完整的示例:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class JMenuExample extends JFrame implements ActionListener {

    JMenu menu;
    JPanel panelMain;
    JPanel panelRed;
    JPanel panelBlue;

    CardLayout layout;

    public void createUI() {
        createMenu();
        createPanels();

    }

    private void createPanels() {
        panelMain = new JPanel();
        layout = new CardLayout();
        panelMain.setLayout(layout);

        panelRed = new JPanel();
        panelRed.setBackground(Color.RED);
        panelMain.add(panelRed, "Red");
        panelBlue = new JPanel();
        panelBlue.setBackground(Color.BLUE);
        panelMain.add(panelBlue, "Blue");

        add(panelMain);

    }

    private void createMenu() {
        menu = new JMenu("Change To");
        JMenuItem miRed = new JMenuItem("Red");
        miRed.addActionListener(this);
        menu.add(miRed);
        JMenuItem miBlue = new JMenuItem("Blue");
        miBlue.addActionListener(this);
        menu.add(miBlue);

        JMenuBar bar = new JMenuBar();
        bar.add(menu);

        setJMenuBar(bar);

    }

    public static void main(String[] args) {

        JMenuExample frame = new JMenuExample();
        frame.createUI();
        frame.setSize(150, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JMenuItem) {
            JMenuItem mi = (JMenuItem) e.getSource();
            layout.show(panelMain, mi.getText());

        }
    }
}


希望这可以帮助

09-15 17:46