Java - need help recreating a JMenuBar
Ok, this is what I have in mind. A menu gets created with 3 options when the program runs. Elsewhere on the page is a button. I would like to re-create the menu when I hit the button, but with new options. Everything I've tried so far has failed. Does anyone have any ideas? Below is the code.
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.awt.Window;
import javax.swing.*;
import javax.swing.border.*;
public class test extends Frame implements ActionListener {
public JPanel menuBar = new JPanel();
public myMenu freqMenu;
public double testArr[] = new double[10];
public test() {
super("Testing");
setSize(500,500);
addWindowListener(new BasicWindowMonitor());
testArr[0] = 1.0;
testArr[1] = 1.1;
testArr[2] = 1.2;
menuBar.setLayout(new FlowLayout(FlowLayout.LEFT));
JButton testBtn = new JButton("Change Menu");
testBtn.addActionListener(this);
menuBar.add(testBtn);
freqMenu = new myMenu(testArr);
menuBar.add(freqMenu);
add(menuBar, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent event) {
// Create the new menu options
double newArr[] = new double[10];
newArr[0] = 5.0;
newArr[1] = 5.1;
newArr[2] = 5.2;
newArr[3] = 5.3;
newArr[4] = 5.4;
// I'm trying to make a new menu, and put it in place of the old one.
menuBar.remove(freqMenu);
freqMenu = new myMenu(newArr);
menuBar.add(freqMenu);
menuBar.repaint();
// This just removes the old menu, and doesn't replace it with a new one.
}
public class myMenu extends JMenuBar {
public myMenu(double[] hz) {
JMenu menu = new JMenu("Frequency");
int i = 0;
while(hz[i] != 0.0) {
JMenuItem item = new JMenuItem(hz[i] + " MHz");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Ding");
}
});
i++;
menu.add(item);
}
add(menu);
}
}
public static void main(String args[]) {
test myTest = new test();
myTest.setVisible(true);
}
public class BasicWindowMonitor extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window w = e.getWindow();
w.setVisible(false);
w.dispose();
System.exit(0);
}
}
}
|