How can I change the content of a JFrame to an appropriate click?

I am working on a simple desktop application with java. There is a menu bar when the user clicks on menu item 1, then the contents will change to form A. When the user clicks on menu item 2, the content displays form B.

How could I achieve this?

using the same window and only changing the content.

+3
source share
3 answers

A sample for you, I just did to refresh my knowledge of swing.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class FrmChange extends JFrame{

private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();

public FrmChange(){
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    initMenu();
    panel1.setBackground(Color.BLUE);
    panel2.setBackground(Color.RED);
    setLayout(new BorderLayout());
}

private class MenuAction implements ActionListener {

    private JPanel panel;
    private MenuAction(JPanel pnl) {
        this.panel = pnl;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        changePanel(panel);

    }

}

private void initMenu() {
    JMenuBar menubar = new JMenuBar();
    JMenu menu = new JMenu("Menu");
    JMenuItem menuItem1 = new JMenuItem("Panel1");
    JMenuItem menuItem2 = new JMenuItem("Panel2");
    menubar.add(menu);
    menu.add(menuItem1);
    menu.add(menuItem2);
    setJMenuBar(menubar);
    menuItem1.addActionListener(new MenuAction(panel1));
    menuItem2.addActionListener(new MenuAction(panel2));

}

private void changePanel(JPanel panel) {
    getContentPane().removeAll();
    getContentPane().add(panel, BorderLayout.CENTER);
    getContentPane().doLayout();
    update(getGraphics());
}

public static void main(String[] args) {
    FrmChange frame = new FrmChange();
    frame.setBounds(200, 200, 300, 200);
    frame.setVisible(true);

}

}

+3
source

You can use CardLayout or simply remove the panel that is displayed and add the one you want to display in the frame's content panel.

ActionListener , ech, .

Swing. Swing Tutorial.

+5
frame.getContentPane().remove() or removeAll();

frame.getContentPane().add(allTheNewComponents);

frame.revalidate();
frame.repaint();
+3
source

Source: https://habr.com/ru/post/1793834/


All Articles