shashank
shashank

Reputation: 1

java desktop application

i am creating a desktop application in netbeans and i want that in my menu bar if i select a new menu item than o nly the below panel is change not full frame.so it will look like that i m working on a single frame.can anyone help me out

Upvotes: 0

Views: 274

Answers (1)

YoK
YoK

Reputation: 14505

You can use Card Layout Managers to achieve such functionality.

Here is complete example:

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());

        }
    }
}

Hope this helps

Upvotes: 2

Related Questions