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 content will change to form A. When a user clicks on menu item 2 then the content will display form B.
How could i achieve this?
using the same window and just the content change.
A sample for you, I just did to refresh my swing knowledge..
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);
}
}
You could use a CardLayout, or simply remove the displayed panel and add the one you want to display the the frame content pane.
You need to add an ActionListener
to each menu item in order to trigger the appropriate change ech time a menu item is clicked.
This is really basic Swing functionality. You should read the Swing Tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With