I am making text editor in netbeans and have added jMenuItems called Copy,Cut & Paste in the Edit menu.
How do I enable these buttons to perform these functions after actionPerformed()
Here is my attempt:
private void CopyActionPerformed(java.awt.event.ActionEvent evt) {
JMenuItem Copy = new JMenuItem(new DefaultEditorKit.CopyAction());
}
private void PasteActionPerformed(java.awt.event.ActionEvent evt) {
JMenuItem Paste = new JMenuItem(new DefaultEditorKit.PasteAction());
}
private void CutActionPerformed(java.awt.event.ActionEvent evt) {
JMenuItem Cut = new JMenuItem(new DefaultEditorKit.CutAction());
}
simple editor example with cut ,copy ,paste:
public class SimpleEditor extends JFrame {
public static void main(String[] args) {
JFrame window = new SimpleEditor();
window.setVisible(true);
}
private JEditorPane editPane;
public SimpleEditor() {
editPane = new JEditorPane("text/rtf","");
JScrollPane scroller = new JScrollPane(editPane);
setContentPane(scroller);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
setSize(600,500);
JMenu editMenu = new JMenu("Edit");
Action cutAction = new DefaultEditorKit.CutAction();
cutAction.putValue(Action.NAME, "Cut");
editMenu.add(cutAction);
Action copyAction = new DefaultEditorKit.CopyAction();
copyAction.putValue(Action.NAME, "Copy");
editMenu.add(copyAction);
Action pasteAction = new DefaultEditorKit.PasteAction();
pasteAction.putValue(Action.NAME, "Paste");
editMenu.add(pasteAction);
bar.add(editMenu);
}
}
Hope this helps!
JEditorPane edit=... your instance;
Then use one of the
edit.cut();
edit.copy();
edit.paste();
Related
im making this one game and i have menu created for it that opens first when starting the program but the menu buttons wont do anything. How do i link this menu window to the game so that when i press "new game" the game starts?
P.S
Yes i did try to find solution from several youtube videos and javas own help site but i couldnt find how to link button click action to start up action in game so that it basicly opens up game screen and starts the game.
All kind of help would be appreciated!
Code:
public class Menu {
JTextArea output;
JScrollPane scrollPane;
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
//Create the menu bar.
menuBar = new JMenuBar();
//Build the first menu.
menu = new JMenu("Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("New Game",
KeyEvent.VK_T);
//menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(menuItem);
ImageIcon icon = createImageIcon("");
menuItem = new JMenuItem("Score history", icon);
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(menuItem);
menuItem = new JMenuItem(icon);
menuItem.setMnemonic(KeyEvent.VK_D);
menu.add(menuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("Options");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("Sounds");
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Exit Game");
submenu.add(menuItem);
menu.add(submenu);
//Build second menu in the menu bar.
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Menu.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("BlockBreaker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Menu demo = new Menu();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
//Display the window.
frame.setSize(450, 260);
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();
}
});
}
}
Here is how i imagined it in my mind:
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(menuItem);
menuItem = new MouseAction(MouseEvent.PRESS_LMB)
if (PRESS_LMB.menuItem("New Game")) {
start Gameplay.java;
}
Use AbstractAction class with your JMenuItem as below.
Replace your line of code:
menuItem = new JMenuItem("New Game", KeyEvent.VK_T);
By:
menuItem = new JMenuItem((new AbstractAction("New Game") {
public void actionPerformed(ActionEvent e) {
System.out.print("clicked");
}
}));
Use separate name for different game menu otherwise you can't add diffrent action to them.
Action performed using anonymous class or ActionListener. I'm showing for anonymous class.
See This for more Information: How to use JMenu
Using anonymous class:
final JMenuItem newGame;
newGame = new JMenuItem("New Game",
KeyEvent.VK_T);
menu.add(newGame);
newGame.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame();
frame.setSize(500, 100);
frame.setTitle("Game on Fire");
frame.show();
}
});
Using ActionListener:
public YourClass implements ActionListener, ItemListener {
#Override
public void actionPerformed(ActionEvent e) {
//...Get information from the action event...
//...Display it in the text area...
}
}
If you want to run game on same window, use JPanel inside actionPerformed. Here is an Example:
public class GameClass extends JPanel{
///Game Logic Here
}
then add this too your actionPerformed.
public void actionPerformed(ActionEvent e) {
GameClass game = new GameClass();
menuPanel.setVisible(false); /// menuPanel is a selection window.
mainPanel.add(game); // Now add your Game Window to same Frame.
}
I'm a newbie for java and learning for past two months from a book. I've tried a JApplet Menu program from the book.
MenuDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MenuDemo implements ActionListener {
JLabel jlab;
MenuDemo() {
JFrame jfrm = new JFrame("Menu Demo");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 200);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlab = new JLabel();
JMenuBar jmb = new JMenuBar();
JMenu jmFile = new JMenu("File");
JMenuItem jmiOpen = new JMenuItem("Open");
JMenuItem jmiClose = new JMenuItem("Close");
JMenuItem jmiSave = new JMenuItem("Save");
JMenuItem jmiExit = new JMenuItem("Exit");
jmFile.add(jmiOpen);
jmFile.add(jmiClose);
jmFile.add(jmiSave);
jmFile.addSeparator();
jmFile.add(jmiExit);
jmb.add(jmFile);
JMenu jmOptions = new JMenu("Options");
JMenu jmColors = new JMenu("Colors");
JMenuItem jmiRed = new JMenuItem("Red");
JMenuItem jmiGreen = new JMenuItem("Green");
JMenuItem jmiBlue = new JMenuItem("Blue");
jmColors.add(jmiRed);
jmColors.add(jmiGreen);
jmColors.add(jmiBlue);
jmOptions.add(jmColors);
JMenu jmPriority = new JMenu("Priority");
JMenuItem jmiHigh = new JMenuItem("High");
JMenuItem jmiLow = new JMenuItem("Low");
jmPriority.add(jmiHigh);
jmPriority.add(jmiLow);
jmOptions.add(jmPriority);
JMenuItem jmiReset = new JMenuItem("Reset");
jmOptions.addSeparator();
jmOptions.add(jmiReset);
jmb.add(jmOptions);
JMenu jmHelp = new JMenu("Help");
JMenuItem jmiAbout = new JMenuItem("About");
jmHelp.add(jmiAbout);
jmb.add(jmHelp);
jmiOpen.addActionListener(this);
jmiClose.addActionListener(this);
jmiSave.addActionListener(this);
jmiExit.addActionListener(this);
jmiRed.addActionListener(this);
jmiGreen.addActionListener(this);
jmiBlue.addActionListener(this);
jmiHigh.addActionListener(this);
jmiLow.addActionListener(this);
jmiReset.addActionListener(this);
jmiAbout.addActionListener(this);
jfrm.add(jlab);
jfrm.setJMenuBar(jmb);
jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String comStr = ae.getActionCommand();
if (comStr.equals("Exit"))
System.exit(0);
jlab.setText(comStr + " Selected");
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MenuDemo();
}
});
}
}
But it gives the below exception.
load: MenuDemo is not public or has no public constructor.
java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a
member of class MenuDemo with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.Class.newInstance(Class.java:436)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:799)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:728)
at sun.applet.AppletPanel.run(AppletPanel.java:378)
at java.lang.Thread.run(Thread.java:745)
So I changed first three lines from class as below:
public class MenuDemo extends JApplet implements ActionListener {
JLabel jlab;
public void MenuDemo() {
Now the applet window is visible but without menus. As a newbie how can I resolve it.
Thank you.
A constructor does not have a return type. Remove void from the following line.
EDIT
Class definition:
public class MenuDemo extends JApplet implements ActionListener {
Change public MenuDemo() to public void init()
Create two functions in your class as follows.
public void start(){}
public void stop(){}
change
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to
jfrm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
My Main class extends JFrame and for some reason, I can't get my MenuBar and items to show correctly. Is there a special way of adding the menubar?
public class Main extends JFrame
{
// DRIVER
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private JMenuBar menuBar;
private JMenu menu,
menuFile;
private JMenuItem menuItemNew,
menuItemExit;
...
// CONSTRUCTOR
public Main()
{
initializeWindow();
initializeMenu();
}
private void initializeWindow()
{
setTitle(TITLE + " " + VERSION);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setBackground(Color.DARK_GRAY);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
backgroundColor = new GradientBackground(WINDOW_WIDTH, WINDOW_HEIGHT);
}
private void initializeMenu()
{
// Menubar
menuBar = new JMenuBar();
menuBar.setBounds(0, 0, WINDOW_WIDTH, 72);
menuBar.setBackground(Color.LIGHT_GRAY);
menuBar.setVisible(true);
setJMenuBar(menuBar);
// Menu title
menu = new JMenu();
menu.setForeground(Color.BLACK);
menuBar.add(menu);
// File Option
menuFile = new JMenu("FILE");
menuFile.setForeground(Color.BLACK);
menuFile.setBackground(Color.DARK_GRAY);
menuBar.add(menuFile);
// New File
menuItemNew = new JMenuItem("New");
menuItemNew.setForeground(Color.BLACK);
menuItemNew.setBackground(Color.DARK_GRAY);
menuFile.add(menuItemNew);
// New File
menuItemExit = new JMenuItem("Exit");
menuItemExit.setForeground(Color.BLACK);
menuItemExit.setBackground(Color.DARK_GRAY);
menuItemExit.setEnabled(true);
menuFile.add(menuItemExit);
getContentPane().add(menuBar);
} // END initializeMenu()
I think that you looking for JFrame.setMenuBar instead of add(JMenuBar)
there no required getContentPane() for Java 5 and newer version
don't to extend JFrame, create this Object as local variable
Hello im trying to enable my JMenuItem from within an event listener but it seems to be out of scope. im new to java so how would i properly go about this. the said event listener will change to a new view and enable the disabled menu items.
//Create and add MenuItems
JMenuItem fileItem0 = new JMenuItem("Load");
collMenu.add(fileItem0);
JMenuItem fileItem1 = new JMenuItem("Add");
fileItem1.setEnabled(false);
collMenu.add(fileItem1);
JMenuItem fileItem2 = new JMenuItem("Delete");
fileItem2.setEnabled(false);
collMenu.add(fileItem2);
//Add Menu bar to frame
menubar.add(collMenu);
//Menu Item Functions
fileItem0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JOptionPane.showMessageDialog(null,"You selected: Load.");
//Enable fileitem1 & 2 here ??
}
});
I hope this small example will help you clear your doubts...
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MenuExample extends JFrame {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenu menu1 = new JMenu("Edit");
JMenuItem item1 = new JMenuItem("New");
JMenuItem item2 = new JMenuItem("Open");
public MenuExample() {
setJMenuBar(menuBar);
setVisible(true);
setSize(400, 200);
menuBar.add(menu);
menuBar.add(menu1);
menu.add(item1);
menu.add(item2);
item1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
}
});
item2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
}
});
}
public static void main(String[] args) {
MenuExample ex = new MenuExample();
}
}
Don't declare these menu items (fileitem1 and fileitem2) in the same method. Just Declare your fileitem1 and fileitem2 outside of your method.
This solves your problem...
Delcare the JMenuItems you are trying to access as final to be accessed from within an inner class (addActionListener(new ActionListener() {...}).
Inner class needs JMenuItems accessed within ActionListener
to be final. To avoid strange side-effects with closures in java
variables referenced by an anonymous delegates.
Here is an example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.pack();
frame.setVisible(true);
}
private void initComponents(JFrame frame) {
JMenuBar menuBar = new JMenuBar();
JMenu menu1 = new JMenu("File");
JMenuItem itemLoad = new JMenuItem("Load");
//delcare them as final to be accessed from within an inner class
final JMenuItem itemAdd = new JMenuItem("Add");
final JMenuItem itemDel = new JMenuItem("Del");
itemAdd.setEnabled(false);
itemDel.setEnabled(false);
itemLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
itemAdd.setEnabled(true);
itemDel.setEnabled(true);
}
});
menu1.add(itemLoad);
menu1.add(itemAdd);
menu1.add(itemDel);
menuBar.add(menu1);
frame.setJMenuBar(menuBar);
}
}
I had a simple drawing application. I need to add a menu and a toolbar on the left side.
So now, instead of using a simple JFrame, I'm creating a simple class that extends JFrame. I was able to add the menu following some examples online, but can't figure out how to add a JToolBar. I've tried a few different ways, but nothing works. I don't get an error, everything complies just fine, but I don't see any JToolBar.
Here's the code for my JFrame, I hope you can help.
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
public Menu(String title) {
openItem = new JMenuItem("Open...");
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveAsItem = new JMenuItem("Save As...");
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
// (2) Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
menubar.add(fileMenu);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
// (3) Add listeners to menu items
openItem.addActionListener(new OpenAction()); // TODO change
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
// JPanel panel = new JPanel();
// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton newb = new JButton("new");
toolbar.add(newb);
// toolbar.setOpaque(true);
toolbar.setLocation(100, 100);
toolbar.setVisible(true);
// toolbar.setMinimumSize(new Dimension(100, 100));
// toolbar.setAlignmentX(0);
// panel.add(toolbar);
add(toolbar, BorderLayout.NORTH);
getContentPane().add(toolbar, BorderLayout.NORTH);
// getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
setTitle(title);
pack();
setLocationRelativeTo(null); // Center window.
}
// OpenAction
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
}
}
}
its work fine, and you don't need to setVisible tool bar because its showing by default, also don't add the tool bar two time in the same place (NORTH)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MenuDemo {
public static void main(String... args) {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
JFrame menu = new Menu("Testing");
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setVisible(true);
}
}
);
}
}
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
public Menu(String title) {
openItem = new JMenuItem("Open...");
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveAsItem = new JMenuItem("Save As...");
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
// (2) Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
menubar.add(fileMenu);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
// (3) Add listeners to menu items
openItem.addActionListener(new OpenAction()); // TODO change
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
JButton newb = new JButton("new");
toolbar.add(newb);
add(toolbar, BorderLayout.NORTH);
setTitle(title);
setLocationRelativeTo(null);
pack();
}
// OpenAction
private class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
}
}
}
My problem was that I was the way I was instantiating my JFrame. I was using a helper function like this one:
public static JFrame openInJFrame(Container content, int width, int height,
String title, Color bgColor) {
// ...
frame.setContentPane(content);
frame.setVisible(true);
return (frame);
}
So my JToolBar was getting replaced by the Container object...
Thanks guys! Your answers helped me figure out my problem.