How to make MouseClicked event work in java
I am pretty sure this is very easy and that I am only missing one line or two but I just cannot make this work despite searching for solutions over the internet. I am fairly new to java and my problem is in a desktop application.
I have a pretty simple desktop application with one text area, one menu bar with one menu and 3 menu item. I want to edit the text of the text area when I click on the Statistic menu item in a JFrame.
Here is the part of the code where I create the menu bar, menu and menu items (as well as their events):
//menu
mnuRevision.setText("Revision");
mnuitmStats.setText("Statistique");
mnuitmStats.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
mnumnuitmStatsMouseClicked(evt);
}
});
mnuRevision.add(mnuitmStats);
mnuitmOrthographe.setText("Grammaire et orthographe");
mnuitmOrthographe.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
mnuitmOrthographeMouseClicked(evt);
}
});
mnuRevision.add(mnuitmOrthographe);
mnuitmAnalyse.setAc开发者_高级运维tionCommand("Analyse");
mnuitmAnalyse.setText("Analyse");
mnuRevision.add(mnuitmAnalyse);
jMenuBar1.add(mnuRevision);
setJMenuBar(jMenuBar1);
Here is the Mousclicked function:
private void mnumnuitmStatsMouseClicked(java.awt.event.MouseEvent evt){
this.txtTexte.setText("asdf");
this.repaint();
}
What I want to do is when I click on mnuitemStats, the txtTexte will get the text "asdf" written in it. Somehow, this is not working. It looks like the program is not even getting into the function. I looked on some tutorials and they pretty much have the same code as me except for the objects names since most tutorials uses JButton instead of JMenuItem.
I can provide my whole code if it is needed, but I thought the rest would be irrelevant since it does not touch the menu bar or the textarea. I am using Eclipse Java EE IDE.
I usually write something like
mnuitemStats.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{// your logic here;
}});
Assuming mnuitmStats is a JMenuItem, it should be. A little more code would be helpful but given that assumption you should use ActionListener not a MouseListener for this.
Something like:
class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//do something
}
}
and
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem newMenuItem = new JMenuItem("New");
newMenuItem.addActionListener(new MenuActionListener());
fileMenu.add(newMenuItem);
精彩评论