我有一个带有JMenuBar和JMenu的JFrame。在JMenu中,有几个JMenuItem。我只是想为这些JMenuItem添加一个监听器,所以当我点击其中一个时,会发生一些事情。 代码是:
public class FinestraOrario extends JFrame
{
private int semester;
private DBConnection connection = new DBConnection();
private Container c = this.getContentPane();
private JMenu subjMnu = new JMenu("Insegnamento");
private JMenu classMnu = new JMenu("Aula");
private JMenu profMnu = new JMenu("Docente");
public FinestraOrario(int i)
{
semester = i;
//Define menus
JMenuBar bar = new JMenuBar();
JMenu choice = new JMenu("Visualizza Orario per..");
//Define frame features
this.setSize(1150,650);
this.setLocationRelativeTo(null);
this.setJMenuBar(bar);
//Add JMenu
bar.add(choice);
choice.add(classMnu);
choice.add(subjMnu);
choice.add(profMnu);
//populate Menus
populateMenu();
private void populateMenu ()
{
//data from database which populate the JMenu as JmenuItem
ArrayList<String[]> subjctesAndClasses= connection.getSemesterData(semester, "");
ArrayList<String[]> teachers = connection.getSemesterData(semester, "keep theachers");
Iterator<String[]> i=subjctesAndClasses.iterator();
Iterator<String[]> j=teachers.iterator();
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
Set<String> set3 = new HashSet<String>();
while(i.hasNext()) //check values
{
String[] value=i.next();
String subject = value[1]; //value contains at subjects at index 1 and classes at index 2
String class=value[2];
set1.add(subject); //erase duplicate
set2.add(class);
}
//getting value without duplicates
for (String s: set1)
{
JMenuItem item = new JMenuItem(s);
subjMnu.add(item);
}
for (String s: set2)
{
JMenuItem item = new JMenuItem(s);
classMnu.add(item);
}
while(j.hasNext()) //idem for teacher
{
String[] value=j.next();
String teacher = value[0];
set3.add(teacher);
}
for (String s: set3)
{profMnu.add(new JMenuItem(s));}
}
}
如何向每个JMenuItem添加侦听器?
答案 0 :(得分:2)
在JMenuItem item = new
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});