0

I have problem with this code when I click on file and click on new ,new panel comes to screen and when I want to change JRadioBox status to change Label status,Label status changes but also the panel goes away :(

public class MainClass {

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

class Toolbar extends JPanel {

    private JRadioButton Status1;
    private JRadioButton Status2;
    private ButtonGroup radioButtonGroup;

    public Toolbar() {
        super();
        setLayout(new FlowLayout());
        Status1 = new JRadioButton("Status1");
        Status2 = new JRadioButton("Status2");

        radioButtonGroup = new ButtonGroup();
        radioButtonGroup.add(Status2);
        radioButtonGroup.add(Status1);

        Status1.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                MainFrame m = new MainFrame();
                m.l.setText("Status1");
            }
        });
        Status2.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                MainFrame m = new MainFrame();
                m.l.setText("Status2");
            }
        });

        add(Status1);
        add(Status2);
    }
}

 class Panel extends JPanel {

    public Panel() {
        super();
        setBackground(Color.MAGENTA);
    }

}

 class MenuBar extends JMenuBar {

    private JMenu menu;
    private JMenuItem fileItems;
    public boolean panel = false;

    public MenuBar() {
        super();
        menu = new JMenu("File");
        add(menu);
        fileItems = new JMenuItem("New");
        menu.add(fileItems);
        fileItems.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                MainFrame mf = new MainFrame();
                Panel p = new Panel();
                mf.addPanel(p);
                mf.add(new Toolbar(), BorderLayout.NORTH);
                repaint();
            }
        });
    }

}

 class MainFrame extends JFrame {

    public static JLabel l;
    public MainFrame() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 400);
        l = new JLabel("No Status");
        add(l, BorderLayout.SOUTH);
        MenuBar mb = new MenuBar();
        setJMenuBar(mb);
        setVisible(true);
    }

    public void addPanel(Panel p) {
        add(p, BorderLayout.CENTER);
    }

}
4

1 回答 1

1

停止到处制造新的 MainFrame。创建一次并在需要时维护它的句柄。

于 2013-04-01T13:25:48.770 回答