JOptionPane not showing up (null parameter, called from inner class) - java

I am completely new to JAVA, I am trying to make a simple application and there is no way I can get my JOptionPane to show correctly and I guess I am missing something:
here's the code:
import java.awt.Color;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Frame extends JFrame
{
private static final long serialVersionUID = 1L;
final static int WIDTH = 400;
final static int HEIGHT = 400;
public Frame()
{
super("Convert to Dxf alpha ver. - survey apps 2014");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setResizable(false);
setLocation(100, 100);
setBackground(Color.WHITE);
setVisible(true);
WelcomePanel welcomePanel = new WelcomePanel(this);
add(welcomePanel);
}
public void createMenuPanel()
{
MenuPanel menu = new MenuPanel();
setJMenuBar(menu.createMenu(this));
}
}
class MenuPanel extends JPanel implements ActionListener
{
private JMenuItem open,save,close;
private JMenu file,about;
private Frame frame;
private static final long serialVersionUID = 1L;
public JMenuBar createMenu(Frame frame)
{
this.frame = frame;
JMenuBar menuBar = new JMenuBar();
file = new JMenu("File");
about = new JMenu("About");
menuBar.add(file);
menuBar.add(about);
open = new JMenuItem("Open");
save = new JMenuItem("Save");
close = new JMenuItem("Close");
file.add(open);
file.add(save);
file.addSeparator();
file.add(close);
open.addActionListener(this);
save.addActionListener(this);
close.addActionListener(this);
about.addActionListener(this);
return menuBar;
}
public MenuPanel()
{
setVisible(true);
setOpaque(true);
setBackground(Color.WHITE);
setSize(Window.WIDTH,Window.HEIGHT);
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == open)
{
frame.dispose();
}
if(source == save)
{
}
if(source == close)
{
}
if(source == about)
{
JOptionPane.showMessageDialog(frame, "EasyDxfCreator - alpha version");
}
}
}
(I skipped the WelcomeFrame because it's just like a welcome screen that disappears after a mouse click)

JMenu does not operate in that way. TO get JMenu Events you need to implement MenuListener instead of ActionListener. ActionListener is good for JMenuItem.
Hope this helps.

Related

JDialog only load at the end of the program

I am using a JDialog for a project, which is load when I click on a button located inside a JFrame.
This JDialog is supposed to display an image, but the image appears only when the code called by the JFrame class is executed. My problem is that I want the image to be displayed when I call it, not at the end of my programm.
Here is my code of the JDialog :
public class LoadingWindow {
private JDialog dialog;
public LoadingWindow() {
this.dialog = new JDialog();
this.dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.dialog.setTitle("Veuillez patienter");
this.dialog.setSize(300, 200);
URL url = LoadingWindow.class.getResource("/images/wait.gif");
ImageIcon icon = new ImageIcon(url);
JLabel imageLabel = new JLabel();
imageLabel.setIcon(icon);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setVerticalAlignment(JLabel.CENTER);
this.dialog.getContentPane().add(imageLabel);
this.dialog.setLocationRelativeTo(null);
this.dialog.setVisible(true);
}
public void stop() {
this.dialog.dispose();
}
}
Inside my JFrame, I call the JDialog this way :
MyJDialog mjd = new MyJDialog ();
[CODE]
mjd.stop();
Thanks !
Here's an example of a GUI that opens a JDialog.
Here's the image I used.
I create a JFrame and a JPanel with a JButton. The JButton has an ActionListener that opens a JDialog. The JDialog displays the car image.
Here's the complete runnable code I used.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JDialogTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTest());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
150, 100, 150, 100));
panel.setPreferredSize(new Dimension(400, 400));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new CalculateDecor(frame, "Spash Screen");
}
}
public class CalculateDecor extends JDialog {
private static final long serialVersionUID = 1L;
public CalculateDecor(JFrame frame, String title) {
super(frame, true);
Image image = getImage();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setIcon(new ImageIcon(image));
panel.add(label);
add(panel);
pack();
setLocationRelativeTo(frame);
setVisible(true);
System.out.println(getDecorationSize());
}
private Dimension getDecorationSize() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
private Image getImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/car.jpg"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}

Using button in a panel class to call ActionListener in the frame class

I started codig Java last weekend and I've read most of the basic stuff. I'm trying to separate my frame from main method, and panels from the frame so they are all in separate class files. I have trouble calling ActionLister in "Frame1" class with a button (buttonBack) in the "TheGame" class. The button should trigger the Listener which in turn should remove theGame panel and add mainMenu panel to frame1. I know that CardLayout is better suited for swapping panels but i want to learn the limits and workarounds before i go do it the "easy" way, i feel that you learn much more that way.
Here is some of my code:
Main:
public class Main {
public static void main(String[] args){
Frame1 frame1 = new Frame1();
frame1.frame1();
}
}
Frame1:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
class Frame1 {
private JFrame frame1 = new JFrame("Name");
public void frame1() {
TheGame theGame = new TheGame();
MainMenu mainMenu = new MainMenu();
// Frame options
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLocationRelativeTo(null);
// Creating a top menu
JMenuBar menubar = new JMenuBar();
frame1.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenu help = new JMenu("Help");
menubar.add(help);
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
JMenuItem about = new JMenuItem("About");
help.add(about);
// Creating action for the menuitem "exit".
class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
exit.addActionListener(new exitaction());
// Creating listener for the menuitem "about".
class aboutaction implements ActionListener{
public void actionPerformed (ActionEvent e){
JDialog dialogabout = new JDialog();
JOptionPane.showMessageDialog(dialogabout, "Made by: ");
}
}
about.addActionListener(new aboutaction());
// Add the panels, pack and setVisible
theGame.theGame();
mainMenu.mainMenu();
frame1.add(theGame.getGUI());
// This is the ActionListener i have trouble connecting with the buttonBack in the "theGame" class
class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
frame1.remove(theGame.getGUI());
frame1.add(MainMenu.getGUI());
}
}
frame1.pack();
frame1.setVisible(true);
}
public JFrame getGUI() {
return frame1;
}
}
MainMenu:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class MainMenu {
private JPanel mainMenu = new JPanel (new GridBagLayout());
public void mainMenu() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating Label
JLabel introduction = new JLabel("Name");
grid.gridx = 1;
grid.gridy = 3;
mainMenu.add(introduction, grid);
// Creating buttons Start Game, Highscore and Exit Game
JButton buttonNewGame = new JButton("New Game");
buttonNewGame.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 5;
mainMenu.add(buttonNewGame, grid);
JButton buttonHighscore = new JButton("Highscore");
buttonHighscore.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 6;
mainMenu.add(buttonHighscore, grid);
JButton buttonExit = new JButton("Exit Game");
buttonExit.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 7;
mainMenu.add(buttonExit, grid);
}
public JComponent getGUI() {
return mainMenu;
}
}
TheGame:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class TheGame {
private JPanel theGame = new JPanel (new GridBagLayout());
public void theGame() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating a label
JLabel label1 = new JLabel("Press the BACK button to go back to Main Menu");
label1.setVisible(true);
grid.gridx = 1;
grid.gridy = 0;
theGame.add(label1,grid);
// Creating BACK button
JButton buttonBack = new JButton("BACK");
buttonBack.setVisible(true);
grid.gridx = 1;
grid.gridy = 1;
buttonBack.addActionListener(new --); // This is the button i want to connect with the ActionListener on Frame1 class
theGame.add(buttonBack, grid);
}
public JComponent getGUI() {
return theGame;
}
}
I've tried moving the ActionListener outside of methods, inside the Main, declaring it static, but haven't been able to call it anyways. I've also looked at other posts like this: Add an actionListener to a JButton from another class but have not been able to implement it in to my code.
Any help is appreciated.
The best answer -- use MVC (model-view-controller) structure (and CardLayout) for the swapping of your views. If you don't want to do that, then your listener should have a reference to the container that does the swapping, and so that the listener can notify this container that a swap should occur. The container will then call its own code to do the swapping. To do this you need to pass references around including a reference to the main GUI to wherever it is needed. This can get messy, which is why MVC, which is more work, is usually better -- fewer connections/complexity in the long term.
Side note -- don't pass a JDialog into a JOptionPane as a JOptionPane is a specialized JDialog, and you shouldn't have a top level window displaying a top level window. Instead pass in a JPanel.
For example:
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PassRef {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
MyMain mainPanel = new MyMain();
JFrame frame = new JFrame("Pass Reference");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class MyMain extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 450;
private CardLayout cardLayout = new CardLayout();
private MenuView menuView = new MenuView(this);
private ActionView1 actionView1 = new ActionView1(this);
public MyMain() {
setLayout(cardLayout);
add(menuView, MenuView.NAME);
add(actionView1, ActionView1.NAME);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
return new Dimension(PREF_W, PREF_H);
}
}
public void showCard(String key) {
cardLayout.show(this, key);
// or swap by hand if you don't want to use CardLayout
// but remember to revalidate and repaint whenever doing it by hand
}
}
class MenuView extends JPanel {
public static final String NAME = "Menu View";
public MenuView(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder("Menu"));
add(new JButton(new GoToAction("Action 1", ActionView1.NAME, myMain)));
}
}
class ActionView1 extends JPanel {
public static final String NAME = "Action View 1";
public ActionView1(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder(NAME));
add(new JButton(new GoToAction("Main Menu", MenuView.NAME, myMain)));
}
}
class GoToAction extends AbstractAction {
private String key;
private MyMain myMain;
public GoToAction(String name, String key, MyMain myMain) {
super(name);
this.key = key;
this.myMain = myMain;
}
#Override
public void actionPerformed(ActionEvent e) {
myMain.showCard(key);
}
}

Drawing on JPanel with JButton, JSpinner, etc

So i am trying to make a graphical interface for school, which involves a JMenuBar, JSpinner, and 2 JButtons. Below these objects I'm trying to draw a simple rectangle. I've already tried using the paintComponent method in the class which extends JPanel but it stil doesn't appear.
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class A1 {
public final static int DEFAULT_WIDTH = 640;
public final static int DEFAULT_HEIGHT = DEFAULT_WIDTH /12*9;
public static void main(String[] args) {
JFrame frame = new JFrame("A1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT));
frame.requestFocus();
frame.setLayout(new FlowLayout());
frame.setLocationRelativeTo(null);
frame.setResizable(false);
lePanel panel = new lePanel();
frame.add(panel);
frame.setJMenuBar(panel.getMenuBar());
frame.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
public class lePanel extends JPanel {
JMenuBar menuBar;
JButton submit;
JButton check;
JSpinner spinner;
public String test;
public lePanel() {
menuBar = new JMenuBar();
menuBar.add(createFileMenu(new JMenu("File")));
menuBar.add(createHelpMenu(new JMenu("Help")));
spinner = new JSpinner(new SpinnerNumberModel(1, 1, 10, 1));
add(spinner);
submit = new JButton("Submit");
add(submit);
check = new JButton("Check");
add(check);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit)
{
test = spinner.getValue().toString();
System.out.println("Spinner Submitted");
}
}
});
check.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == check)
{
JOptionPane.showMessageDialog(lePanel.this, test, "Information",JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
private JMenu createHelpMenu(JMenu jMenu) {
JMenu menu = jMenu;
JMenuItem helpItem = new JMenuItem("Help");
menu.add(helpItem);
return menu;
}
private JMenu createFileMenu(JMenu jMenu) {
JMenu menu = jMenu;
JMenuItem newItem = new JMenuItem("New");
JMenuItem clearItem = new JMenuItem("Clear");
JMenuItem chooseFileItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(newItem);
menu.add(clearItem);
menu.add(chooseFileItem);
menu.add(saveItem);
menu.add(exitItem);
return menu;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.drawRect(200, 200, 50, 50);
}
public JMenuBar getMenuBar() {
return menuBar;
}
}
Your problem is here:
frame.setLayout(new FlowLayout());
By doing this, your lePanel JPanel sizes to its preferred size, a size much too small to show the rectangle. Delete this line and your JFrame's contentPane will use its default BorderLayout, and the drawing JPanel will fill the lower part of your GUI, as per the BordrLayout rules, and you'll see the drawing.
Note a useful debugging technique is to add a border around a component of interest to see where it is and how big it is. For example, I placed this in your lepanel constructor
setBorder(BorderFactory.createTitledBorder("le panel"));
and it visually showed me your problem.
Other unrelated issues:
You will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
Remember to use the #Override annotation above any methods that you think might be overriding another, such as your paintComponent method. This will allow the compiler to notify you if you are in fact overriding things incorrectly.

Menubar not added in a java split pane

I have written a small test program which creates a split pane in which one of the pane's is a text area. I have added a meubar and menuitems to the pane but i donot see them in the gui that is created.
Could anyone pls point out what the wrong thing did i do over here in the below program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenuBar;
import java.util.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.io.IOException;
//SplitPaneDemo itself is not a visible component.
public class SplitPaneDemo extends JFrame
implements ActionListener {
private JTextArea ta;
private JMenuBar menuB;
private JMenu dbM;
private JMenuItem cnadb,bsmdb,cdmdb;
private JLabel picture;
private JSplitPane splitPane;
public SplitPaneDemo() {
ta = new JTextArea(); //textarea
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke )
{
int code = ke.getKeyCode();
int modifiers = ke.getModifiers();
if(code == KeyEvent.VK_ENTER && modifiers == KeyEvent.CTRL_MASK)
{
System.out.println("cmd in table:");
}
}
});
JScrollPane taPane = new JScrollPane(ta);
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
JScrollPane pictureScrollPane = new JScrollPane(picture);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
taPane, pictureScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(450);
//Provide minimum sizes for the two components in the split pane.
Dimension minimumSize = new Dimension(100, 100);
taPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
//Provide a preferred size for the split pane.
splitPane.setPreferredSize(new Dimension(900, 900));
menuB = new JMenuBar(); //menubar
dbM = new JMenu("DB"); //file menu
cnadb = new JMenuItem("CNA");
bsmdb = new JMenuItem("BSM");
cdmdb = new JMenuItem("CDM");
setJMenuBar(menuB);
menuB.add(dbM);
dbM.add(cnadb);
dbM.add(bsmdb);
dbM.add(cdmdb);
cnadb.addActionListener(this);
bsmdb.addActionListener(this);
cdmdb.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
public void valueChanged(ListSelectionEvent e) {
}
public JSplitPane getSplitPane() {
return splitPane;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SplitPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
frame.getContentPane().add(splitPaneDemo.getSplitPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You add the JMenuBar in your SplitPaneDemo class, but when you actually call createAndShowGUI, you make a new JFrame and only add the SplitPane to it with the call to getSplitPane. This new frame has no knowledge of the menu bar.
If you are extending JFrame in SplitPaneDemo, why not use that to make the frame for your gui?

JMenuItem: how to set an Accelerators with 3 keys?

Please have a look at the following code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuActions extends JFrame
{
private JMenuBar jmb;
private JMenu file;
private JMenuItem open;
public MenuActions()
{
jmb = new JMenuBar();
file = new JMenu("File");
open = new JMenuItem("Open");
open.addActionListener(new MenuAction());
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,KeyEvent.VK_P,ActionEvent.CTRL_MASK));
file.add(open);
jmb.add(file);
this.setJMenuBar(jmb);
getContentPane().add(new JPanel());
this.setSize(200,200);
this.setVisible(true);
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class MenuAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(null,"OK");
}
}
public static void main(String[]args)
{
new MenuActions();
}
}
In here, I need to fire the EventHandler of the JMenuItem when CTRL+O+P is pressed together, so it will display JOptionPane saying "OK". But as you can see, my attempt is
giving an error! How can I do this when three of these keys are pressed together? Please help!
It looks like you are using wrong version of KeyStroke.getKeyStroke() method - can't even find one taking 3 int parameters. Though, if you want you can use CTL + ALT + P instead of CTL + O + P
Try using this version:
http://docs.oracle.com/javase/7/docs/api/javax/swing/KeyStroke.html#getKeyStroke(java.lang.String)
like this: KeyStroke.getKeyStroke("control alt P")
Here try this code example :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuActions extends JFrame
{
private JMenuBar jmb;
private JMenu file;
private JMenuItem open;
public MenuActions()
{
jmb = new JMenuBar();
file = new JMenu("File");
open = new JMenuItem("Open");
open.setAction(new MenuAction("Open", null, "Click to Open an Existing File.", KeyStroke.getKeyStroke("control alt P")));
open.setAccelerator(KeyStroke.getKeyStroke("control alt P"));
file.add(open);
jmb.add(file);
this.setJMenuBar(jmb);
getContentPane().add(new JPanel());
this.setSize(200,200);
this.setVisible(true);
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class MenuAction extends AbstractAction
{
public MenuAction(String title, ImageIcon image
, String toolTipText
, KeyStroke acceleratorKey)
{
super(title, image);
putValue(SHORT_DESCRIPTION, toolTipText);
putValue(SHORT_DESCRIPTION, toolTipText);
putValue(ACCELERATOR_KEY, acceleratorKey);
}
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(null,"OK");
}
}
public static void main(String[]args)
{
new MenuActions();
}
}
to #Pete
you can combine any non_chars accelerators but not possible for keys in range [a-z] && [0-9]
for JMenu(Item) accelerator you can use
KeyEvent or Character.valueOf('char') for characters [a-z] && [0-9]
and as second parameter
Event or ActionEvent or InputEvent, notice each of API implemets different keyboards maps
is possible to combine KeyStroke but with bitwise | or & but returns strange KeyStrokes
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class MenuExample extends JPanel {
private static final long serialVersionUID = 1L;
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
private Icon questIcon = UIManager.getIcon("OptionPane.questionIcon");
private JTextPane pane;
private JMenuBar menuBar;
public MenuExample() {
menuBar = new JMenuBar();
JMenu formatMenu = new JMenu("Justify");
formatMenu.setMnemonic('J');
MenuAction leftJustifyAction = new MenuAction("Left", errorIcon);
MenuAction rightJustifyAction = new MenuAction("Right", infoIcon);
MenuAction centerJustifyAction = new MenuAction("Center", warnIcon);
MenuAction fullJustifyAction = new MenuAction("Full", questIcon);
JMenuItem item;
item = formatMenu.add(leftJustifyAction);
item.setMnemonic('L');
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK));
item = formatMenu.add(rightJustifyAction);
item.setMnemonic('R');
item.setAccelerator(KeyStroke.getKeyStroke(ActionEvent.CTRL_MASK | KeyEvent.VK_N, ActionEvent.CTRL_MASK & KeyEvent.VK_B));// CTRL +N
item = formatMenu.add(centerJustifyAction);
item.setMnemonic('C');
item.setAccelerator(KeyStroke.getKeyStroke(InputEvent.ALT_MASK | Character.valueOf('p'), InputEvent.ALT_MASK & Character.valueOf('o')));//ALT+F9
item = formatMenu.add(fullJustifyAction);
item.setMnemonic('F');
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK | Event.SHIFT_MASK));
menuBar.add(formatMenu);
menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));
}
class MenuAction extends AbstractAction {
public MenuAction(String text, Icon icon) {
super(text, icon);
}
public void actionPerformed(ActionEvent e) {
try {
pane.getStyledDocument().insertString(0, "Action [" + e.getActionCommand() + "] performed!\n", null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String s[]) {
MenuExample example = new MenuExample();
example.pane = new JTextPane();
example.pane.setPreferredSize(new Dimension(250, 250));
example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));
JFrame frame = new JFrame("Menu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(example.menuBar);
frame.getContentPane().add(example.pane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}

Categories

Resources