Java Menu Mnemonics in Resource Files - java

I would like to assign a mnemonic to a JMenu using resource bundles (or the ResourceMap). So for example, the code without resource file would be...
JMenu fileMenu = new JMenu();
fileMenu.setText("File"); // this would be read from a resource file
fileMenu.setMnemonic('F'); // but the docs say this is obsolete
fileMenu.setMnemonic(KeyEvent.VK_F);
So how do I put the KeyEvent.VK_F in a resource file?
For a JMenuItem I can do it with actions, but this is JMenu.

Java's javax.swing.KeyStroke class bridges the gap:
JMenu fileMenu = new JMenu();
String mnemonic = // string from localization
fileMenu.setMnemonic(KeyStroke.getKeyStroke(mnemonic).getKeyCode());
Accelerators are not supported for JMenus, only for JMenuItems (which makes sense, since these invoke an action without using the menu at all).

Inside the resource file use the accelerator
add.Action.accelerator = control A

You could do it in a similar way, and treat "FileMenu" as a (fake) action?

Related

JMenuItem shortcut alignment

I have a JMenuBar with the standard items and shortcuts. But I noticed that the shortcut description is left-aligned, which looks ugly. Is there a way to right-align it?
PS: "Umschalt" means shift. Is there a way to force it to say shift instead of Umschalt?
[UPDATE: Locale.setDefault(Locale.ENGLISH); fixes the problem, but a solution to only affect specific components would be better.. ]
PSPS: With UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); I have set the look and feel to be OS default. But now I would like to make some small adjustments to the look on top of the standard OS Look. For example I would like to make the JMenuBar black. The interwebs told me to use UIManager.put("tMenuBar.background", Color.BLACK); but it doesn't seem to do anything..
[UPDATE: It seems like this is not possible with Windows Look and feel :/]
Here the code:
private JMenuBar tMenuBar;
private JMenu mbEdit;
private JMenuItem mCut, mCopy, mPaste, mDo, mUndo;
tMenuBar = new JMenuBar();
mbEdit = new JMenu("Edit");
tMenuBar.add(mbEdit);
// EDIT
mUndo = new JMenuItem("Undo");
mDo = new JMenuItem("Redo");
mCut = new JMenuItem("Cut");
mCut.setIcon(iCut);
mCopy = new JMenuItem("Copy");
mCopy.setIcon(iCopy);
mPaste = new JMenuItem("Paste");
mPaste.setIcon(iPaste);
mbEdit.add(mUndo);
mbEdit.add(mDo);
mbEdit.addSeparator();
mbEdit.add(mCut);
mbEdit.add(mCopy);
mbEdit.add(mPaste);
// Undo
mUndo.setAccelerator(KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
// Redo
mDo.setAccelerator(KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Z, ((Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | java.awt.event.InputEvent.SHIFT_MASK))));
// Cut
mCut.setAccelerator(KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
// Copy
mCopy.setAccelerator(KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
// Paste
mPaste.setAccelerator(KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
Already tried:
applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
I would like to make the JMenuBar black.
It should be (with the "t")
UIManager.put("MenuBar.background", Color.BLACK);
You need to set the UIManager properties "before" you create the component.
Also, the property may not be supported on all LAF's. Check out UIManager Defaults for more information and a list of the properties support by LAF.
Take a look at this post regarding the german words. I do realize that this was probably a comment rather than an answer but I'm still unable to do those due to the lack of reputation and I want to help.

FileChooser in actionListeners

I am trying to code a small text editor and I was building the GUI.
I added a JMenu and added a JMenuItem to it. I gave the menu item the value of "open".
The reason is because I want that when "open" is pressed a JFileChooser appears on the screen
Here is what I have:
public void mousePressed(MouseEvent me) {
JFileChooser fs = new JFileChooser();
}
This method is in a class called listener which implements MouseListener. This is the step that I'm stuck at.
getContentPane()
..does not work:
Is it good code practice the way I'm approaching this? Is there a better way? If not how do I go around doing this?
While in general your approach could work, you might want to look into the Swing concept of Actions. JMenuItem has direct support for actions, you would not need a MouseListener (which is a bit to low-level for your usecase).
Try to look at the examples, it might look a little overwhelming at first, but in the end it is a nice and clean encapsulation of what you want. And it is reusable, meaning you could use the action on a different menu (maybe the context menu) as well.
And for your code, you are missing the call to fs.showOpenDialog(component).
Firstly, don't use a MouseListener for JMenuItem or JButton, this is not the appropriate means for managing these components, instead, use an ActionListener.
The main reason for this is that your menu item could be triggered via a keyboard shortcut or programmatically.
Secondly "does not work" is not information about what you problem is, but I assume it's because the method does not exist.
A simply solution would be to check the source the event to determine if it's a Component or not and use it instead, or null if the source of the event is not a Component...
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
Component parent = null;
if (source instanceof Component) {
parent = (Component)source;
}
// Show file chooser dialog...
}
Take a look at How to use menus for more details
You may also find How to use actions of some interest
Have a look at the Javadoc on the JFileChooser class. It has an example of how to open it.
The following code pops up a file chooser for the user's home directory that sees only .jpg and .gif images:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}

JMenuBar Cannot Find Symbol

I am just started learning Java and I've been reading through this documentation. I don't like to copy a bunch of code and paste it. So I have been trying to work my way through the documentation one thing at at time.
I already have a working JFrame and decided I would start by adding a menu.
HERE IS MY CODE:
package mainframe;
import javax.swing.*;
public class menuBar extends JMenuBar {
JMenuBar mainMenu = JMenuBar("Menu");
}
MY ERROR:
error: cannot find symbol
JMenuBar mainMenu = JMenuBar("Menu");
symbol: method JMenuBar(String)
location: class menuBar
1 error
So anyways. I am not really sure what the "cannot find symbol error" means. Maybe I am searching wrong. But every time I Google it it takes me to more complex questions with no clear answer. Any advice as to what I am doing wrong and or to what the cannot find symbol error means would be very much appreciated. Thanks in advance.
In response to your particular code here, I suggest that you do not extend the JMenuBar class. You may have seen it in many tutorials or examples where the JFrame class is extended, although that is considered bad practice. To add a JMenuBar to your window, I would suggest doing the following:
public class MyProgram {
JFrame frame;
public MyProgram() {
...
frame = new JFrame();
JMenuBar mainMenu = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.add(new JMenuItem("Open..."));
mainMenu.add(fileMenu); // adds a single JMenu to the menubar
frame.setJMenuBar(mainMenu); // adds the entire menubar to the window
...
frame.setVisible();
...
}
The only reason you would extend the JMenuBar class would be if you wanted to make a class that had additional functionality in terms of methods defined in your subclass, but that seems unlikely especially given the fact that you're just learning Swing.
The constructor for JMenuBar never takes any arguments. Also remember to use the new keyword when you instantiate (create an instance of) a new object. Consider using the following code:
JMenuBar mainMenu = new JMenuBar();
JMenu fileMenu = new JMenu("File");
mainMenu.add(fileMenu);
JMenuBar mainMenu = JMenuBar("Menu");
should be
JMenuBar mainMenu = new JMenuBar("Menu");
You forgot the new keyword. You must always use new when creating a new object with a constructor. Otherwise, Java will think that it is a method, which it is not.
Furthermore, if you look at the documentation here. you will find that JMenuBar's constructor does not take any arguments. Therefore, don't pass anything:
JMenuBar mainMenu = new JMenuBar();

How to merge JOptionPane and Frame into one

Currently I have a very basic file viewer working as follows :
- in JOptionPane I browse for files, and set some variables to display (colors, line connecting etc)
- previous windows loads a frame with drawn points
alt text http://img190.imageshack.us/img190/4443/104bu.jpg
Code :
http://paste.pocoo.org/show/220066/
Now I'd like to throw it into one window, with JMenu for selecting files and changing display parameters. How to get started ? Should I rewrite everything to JDialog ?
alt text http://img684.imageshack.us/img684/5264/lab10db.jpg
If you want the JOPtionPane as a child of the main JFrame, then add it as a child. Of course it will then cover your dots. Hence you will have to not draw your dots directly in the content pane of the main JFrame, but rather in a new JPanel that you have also added to the JFRame's content pane. Let me know if I've understood the question whatsoever.
Here's some code for how I see the setup (I'm leaving the layout problem out of this, partly because it depends on what you want to see):
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(new Dimension(400,400));
frame.getContentPane().add(new JOptionPane());
JPanel canvasForDots = new JPanel();
frame.getContentPane().add(canvasForDots);
You might also like to look at How to Use Tool Bars and How to Use Menus. ImageApp is a typical implementation that associates menu items with the corresponding Action instances.
private class ClearAction extends AbstractAction {…}
private class ImageOpenAction extends AbstractAction {}
private Action openAction = new ImageOpenAction("Open");
private Action clearAction = new ClearAction("Clear");
…
JMenu menu = new JMenu("File");
menu.add(new JMenuItem(openAction));
menu.add(new JMenuItem(clearAction));
This related example adds the file chooser directly to the main frame. Here's a more elaborate example of connecting lines and shapes using the same principles.

Java JMenu setAccelerator() problem

When I set setAccelerator() to Control + A or Control + P and I run the program it doesn't detect the keystroke.
Here's the code:
menuItem = new JMenuItem("About");
menuItem.setActionCommand("About");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK));
menuItem.setMnemonic(KeyEvent.VK_A);
menuItem.addActionListener(this);
menu.add(menuItem);
Then when it's pressed it should invoke the Action Listener:
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("About")) {
System.out.println("About");
}
}
I'm running it in Eclipse on a Mac if that matters.
Control-A and Control-P are both keystrokes that may already be intercepted, depending on your platform and depending on what has keyboard focus. Control-A may already be intercepted and interpreted as "select all", and Control-P may already be intercepted and interpreted as "paste".
What if you select a less commonly-used keystroke instead of "Control-A", such as "Control-Shift-A" or "Control-B"? Here's a modified version of your code that uses Control-Shift-A instead of Control-A:
menuItem = new JMenuItem("About");
menuItem.setActionCommand("About");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK | Event.SHIFT_MASK));
menuItem.setMnemonic(KeyEvent.VK_A);
menuItem.addActionListener(this);
menu.add(menuItem);
I tested this change on my own system using the JMenu demo from the Swing tutorial, and I found (exactly as you did) that registering Control-A as the accelerator had no effect. However, registering Control-Shift-A as the accelerator worked perfectly.
not sure if it will help, but you're using Event.CTRL_MASK instead of KeyEvent.CTRL_MASK

Categories

Resources