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.setActionCommand("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);
Related
I've read several topics showing how to create a KeyBinding, however, none of them fully worked for me. My JFrame has a JMenuBar and for the items of the menu NetBeans is correctly generating code such as:
mniExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
mniExit.setText(bundle.getString("Menu.File.Exit")); // NOI18N
mniExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniExitActionPerformed(evt);
}
});
mnuFile.add(mniExit);
However, only this binding is not visible when the menu is hidden. I've tried something like:
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(mniExit.getAccelerator(), "exit");
getRootPane().getActionMap().put("exit", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
mniExit.doClick();
}
});
But it simply does not work. What am I doing wrong?
Thanks in advance!
You state that
However, only this binding is not visible when the menu is hidden. I've tried something like:
I'm guessing here, but I'm not sure that a button or menu can be clicked if its not visible. To simplify, I would create an ExitAction class, a class that extends from AbstractAction, that is assigned as an Action to any JMenuItems, JButtons, or Key Bindings that need it. If they all share the same ExitAction object, then the Action (and the corresponding menu items and buttons) can be disabled all at once if need be.
If this does not help, again create and post a minimal example program where you create the smallest program that runs, compiles, requires no outside dependencies (images, database) and that demonstrates your problem for us.
can i call actionperformed method with jmenu using swing
i am using the following code
JMenu menu1= new JMenu("File");
MenuBar mb= new MenuBar();
mb.add(menu1);
set JmenuBar(mb)
menu1.addActionListener(this);
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessaageDialog(null,"menu clicked");
// but its not working
}
thanks in Advance
The action a JMenu is designed to perform is to open a popup with JMenuItems, it doesn't support doing anything else (and even if it did, it would confuse your users). Custom actions are supposed to be handled by JMenuItems in the popup. Install them with something like:
JMenu menu ..
Action myAction = new AbstractAction("Do XY") {
public void actionPerformed(..) {
// implement doing XY
}
};
menu.add(myAction);
I've looked at other JLabel threads and though similar, a few just don't seem to apply to what I'm experiencing. First, I want to say I am a novice when it comes to Java. Next, I am trying to follow tutorials and demos at the docs.oracle.com site. Now, I can update the label when I type something into a JTextField and there is an ActionListener on that...
But I also have a Menu, and when I select a Menu Item, that Action does not want to update the label.
Questions -
How do I have action listeners on both JTextFields and JMenuItems? Are there two ActionEvent methods or do I use one method and somehow identify each type of action?
If I use the same basic code in the JTextField ActionEvent and JMenuItem ActionEvent, the JLabel updates correctly with the JTextField event but not JMenuItem event. They both use the messageField.setText property. Could the JMenuItem action be doing something to block the setText?
I can easily copy code in here, but it's pretty spaghetti-like at the moment, so if you want to see anything, let me know specifically and I'll post it.
I would appreciate any assistance that anyone would be able to provide.
---edit---
Wow!! Thanks for all of the comments and suggestions.
1 - I know it has to be my code. As I mentioned, I am really just cobbling stuff together from demos and tutorials, and trying to learn Java along the way. I've just never gotten the hang of object oriented....
2 - I do know the individual Listeners are working. I'm using System.out.println to validate, as well as inspecting those labels in debug mode to see they have indeed changed.
3 - I will look at the various links and code posted here and see if I can figure out what's wrong with my code.
Really, thanks again!
---edit---
Here is what I originally had in my createAndShowGUI method....
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Create XML for Photo Gallery");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CreateGalleryXML window = new CreateGalleryXML();
frame.setJMenuBar(window.createMenuBar());
frame.add(new CreateGalleryXML());
frame.pack();
frame.setVisible(true);
}
Seems like you yourself are doing something wrong, in your code. Without a proper SSCCE it's hard to say what thing you doing wrong, since it works perfectly, using same ActionListener for both JMenuItem and JTextField.
Here is a sample program to match with yours :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UpdateLabel
{
private JLabel label;
private String labelText;
private ActionListener action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
setLabelText((String) ae.getActionCommand());
label.setText(getLabelText());
}
};
private void setLabelText(String text)
{
labelText = text;
}
private String getLabelText()
{
return labelText;
}
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("Update Label");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JMenuBar menuBar = new JMenuBar();
JMenu programMenu = new JMenu("Program");
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
frame.dispose();
}
});
JMenu labelMenu = new JMenu("Label");
JMenuItem updateMenuItem = new JMenuItem("Update Label");
updateMenuItem.setActionCommand("Updated by JMenuItem");
updateMenuItem.addActionListener(action);
programMenu.add(exitMenuItem);
labelMenu.add(updateMenuItem);
menuBar.add(programMenu);
menuBar.add(labelMenu);
frame.setJMenuBar(menuBar);
JPanel contentPane = new JPanel();
label = new JLabel("I am the LABEL which will be updated!!");
contentPane.add(label);
JTextField tfield = new JTextField(10);
tfield.setActionCommand("Updated by JTextField");
tfield.addActionListener(action);
frame.add(contentPane, BorderLayout.CENTER);
frame.add(tfield, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new UpdateLabel().createAndDisplayGUI();
}
});
}
}
And here is the output in both the cases :
and
Do check out the main method, might be you had failed to put your code inside EDT - Event Dispatcher Thread, that can lead to such issues too. All updates on the Swing GUI, must be done on the Event Dispatcher Thread.
LATEST EDIT
It seems to me that CreateGalleryXML extends JPanel by the look of it. See at Line 3 of this below code taken from your update, here you are initializing a new Object of CreateGalleryXML inside, when you already had one Object window created at Line 1:
CreateGalleryXML window = new CreateGalleryXML();
frame.setJMenuBar(window.createMenuBar());
frame.add(new CreateGalleryXML());
So try to change the above thingy to this
CreateGalleryXML window = new CreateGalleryXML();
frame.setJMenuBar(window.createMenuBar());
frame.add(window);
and see what happens and Please do revert back again :-)
Use Action to encapsulate common functionality that must be shared by menus and related components. See this example that extends AbstractAction.
Pretty much everything you could need to know is in the Java tutorials. Down the bottom they have demo's on how to do both menu's and text fields. They include source code to look at as well.
There's not much more I can say that they don't say better, but in answer to your questions:
Both, you can have separate listener's on each component, or one that figures out what component is responsible for causing the action event. I would suggest you use separate ones for each thing.
Can't really say with out seeing the code, are you sure that the action on the JMenu is even firing? Does it print something to the console etc if you use System.out.println somewhere?
I'm creating a simple sticky note app. I want to make a JPopupMenu to show when ever I click on the JTextArea . Because it's a sticky note so obviously the whole app will be a textArea
Short Code:
//I've tried my best to follow SSCE
private JTextArea textArea = new JTextArea();
private JPopupMenu popup = new JPopupMenu("Popup Menu");
private JMenuItem hideBar = new JMenuItem("Hide Bar");
private JMenuItem hideTitle = new JMenuItem("Hide Item");
public mySticky(){
add(textArea); //Text Area is using the whole Frame "Sticky Note"
popup.add(hideBar); //adding MenuItem
popup.add(hideTitle); //adding MenuItem
//addMouseListener(new popupTriggerListener());
textArea.addMouseListener(new popupTriggerListener());
}
private class popupTriggerListener extends MouseAdapter{
public void MousePressed(MouseEvent e){
if(e.isPopupTrigger())
popup.show(textArea,e.getX(),e.getY()); //I've added texArea I'm not sure what to add inside.
}
public void MouseReleased(MouseEvent e){
if(e.isPopupTrigger())
popup.show(textArea,e.getX(),e.getY()); //I've added texArea I'm not sure what to add inside.
}
public void MouseClicked(MouseEvent e){
}
}
I've tried my best to follow SSCE
How can this possibly be a SSCCE given that the code doesn't even compile? Try reading the link again.
I suggest you start by read the section from the Swing tutorial on Bringing Up a Popup Menu for a working example.
hmmm I'm missing something here
You are missing the #Override statement which should preceed the method signature when you override a method. This will prevent you from making typing mistakes.
menuBar = new JMenuBar();
// File Menu
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// File->New
JMenuItem newMenuItem = new JMenuItem("New");
frame.setJMenuBar(menuBar);
newMenuItem.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
btnExample.setText("Clicked");
btnExample.doClick();
//---------->SOME HOW TO EXECUTE btnExample<---------//
}
});
fileMenu.add(newMenuItem);
final JButton btnExample = new JButton("SD");
frame.getContentPane().add(btnExample, "cell 4 0,growx,aligny top");
btnExample.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
spinnerForVar.setValue(4);//default value for spinner
spinnerForFunc.setValue(4);//default value for spinner
...
}
});
Hello! I hope someone can help me. Here it is the problem: I have Menu item "New" and have button btnExample. I want the following: When i click on "File->New" it executes btnExample. My code is able only to change the button title and show visual affect of clicking. But how can I actually execute it?
I have only one advice - don't do that. Don't bind GUI components in this way.
If you want two components to execute the same operation, simply pack this operation in a method and call the method from both components.
Also, use ActionListener - are you sure the user is going to press it using mouse and not keyboard? what if you add shortcuts to those buttons/components?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//My button to click on it
jButton1ActionPerformed(evt);//this is the call for the other button to execut it
}
You should not be using a MouseListener for this.
You should be using Actions. Then you can add the Action to both the JButton and the JMemuItem.
Read the section from the Swing tutorial on How to Use Actions.
Amazing, I found my solution in your codes!
btnExample.doClick();
This did the job for me