Trouble adding JMenuBar to extended JFrame - java

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

Related

JMenuItem Action Listener didn't wok properly

so I want to open a new frame when the user presses jmenuitem, the actionlistener logOut manages to open a new frame, but the actionlistener for buyGames doesn't open a new frame, I've tried to change the class name of the frame but it still doesn't have any effect, here is my code created.
I hope someone can help me, thank you so much
public class Player extends JFrame implements ActionListener {
JMenuBar menu = new JMenuBar();
JLabel stim = new JLabel("Stim");
JPanel mai = new JPanel();
JMenu acc, games;
JMenuItem logOut, ownedGames, buyGames;
public Player(){
// TODO Auto-generated constructor stub
stim.setForeground(Color.BLACK);
stim.setFont(new Font("Arial",Font.BOLD + Font.ITALIC,40));
//construct components
menu.setBackground(Color.BLACK);
acc = new JMenu("Account");
acc.setForeground(Color.white);
games= new JMenu("Manage");
games.setForeground(Color.white);
logOut= new JMenuItem("Log Out");
logOut.setBackground(Color.BLACK);
logOut.setForeground(Color.white);
logOut.addActionListener(this);
buyGames= new JMenuItem("Buy Games");
buyGames.setBackground(Color.BLACK);
buyGames.setForeground(Color.white);
ownedGames= new JMenuItem("Owned Genres");
ownedGames.setBackground(Color.BLACK);
ownedGames.setForeground(Color.white);
acc.add(logOut);
games.add(buyGames);
games.add(ownedGames);
menu.add(acc);
menu.add(games);
stim.setBounds(190,120,110,110);
//frame
setTitle("Stim Database");
setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
setSize(510, 400);
setLayout(null);
setResizable(false);
setVisible(true);
setJMenuBar(menu);
add(stim);
}
public static void main(String[] args) {
new Player();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==logOut) {
LoginPage log = new LoginPage();
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
if(e.getSource()==buyGames) {
BuyGames buy = new BuyGames();
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
if(e.getSource()==ownedGames) {
//is not created yet
}
}
}

Voice Over utility anounce Swing application as Java

I have a Swing application, And when i run VoiciOver Utility it announce Swing Application as Java.
For example:
import javax.swing.*;
import java.awt.event.*;
public class Menu extends JFrame{
public Menu()
{
super("Menu example");
JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem newItem = new JMenuItem("New");
newItem.setMnemonic('N');
file.add(newItem);
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('O');
file.add(openItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.add(exitItem);
//adding action listener to menu items
newItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("New is pressed");
}
}
);
openItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Open is pressed");
}
}
);
exitItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Exit is pressed");
}
}
);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(file);
getContentPane();
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args)
{
Menu app = new Menu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
If we try this example with voiceOver utility,it announces the application as "java Menu example window".
can some one help me in resolving this issue?
You can set the com.apple.mrj.application.apple.menu.about.name property to change the displayed name, as shown here.

Java menu item enabling within event listener

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);
}
}

How to enable copy/cut/paste jMenuItem

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();

Display java JPanel in a JFrame

I'm having problems getting my JPanel to display properly. I want to use different extended JPanels to display what I want the user to do with this program (which is ultimately to display photographs). Below is the code for the only two classes that exist at this point. Unfortunately, I'm having problems just getting this to work right out of the gate with the first panel which was to present the user with the ability to select different graphic images.
What's happening is, I can't get my JPanel to display until I click the "Open" menu item in the File menu. Once that JOptionPane shows, so does my JPanel (NewAlbum).
class PhotoGallery {
static JPanel transientPanel = null;
static final JFrame mainFrame = new JFrame("Photo Gallery");
public static void main(String[] args) {
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem open = new JMenuItem("Open");
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(mainFrame, "Hello World");
}
});
fileMenu.add(open);
JMenuItem newAlbum = new JMenuItem("New Album");
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AssignToTransientPanel((JPanel) new NewAlbum());
Container content = mainFrame.getContentPane();
content.removeAll();
content.add(transientPanel);
content.validate();
content.repaint();
}
});
fileMenu.add(newAlbum);
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
fileMenu.add(exit);
JMenuBar pgMenu = new JMenuBar();
pgMenu.add(fileMenu);
mainFrame.setJMenuBar(pgMenu);
mainFrame.setSize(640, 480);
mainFrame.setLocation(20, 45);
mainFrame.validate();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public static void AssignToTransientPanel(JPanel jp) {
if(transientPanel != null)
mainFrame.remove(transientPanel);
transientPanel = jp;
}
}
}
class NewAlbum extends JPanel {
JButton selectImages = new JButton("Select Images");
JFileChooser jfc;
File[] selectedFiles;
public NewAlbum() {
selectImages.setLocation(25, 25);
add(selectImages);
selectImages.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent ae) {
jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(true);
jfc.showOpenDialog(getParent());
selectedFiles = jfc.getSelectedFiles();
}
});
this.validate();
}
public int getHeight() {
return getParent().getSize().height - 20;
}
public int getWidth() {
return getParent().getSize().width - 20;
}
public Dimension getPreferredSize() {
return new Dimension(this.getWidth(), this.getHeight());
}
}
You have not added any components to the mainFrame's content pane in the main method. The only time a panel gets added is in this ActionListener:
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AssignToTransientPanel((JPanel) new NewAlbum());
Container content = mainFrame.getContentPane();
content.removeAll();
content.add(transientPanel);
content.validate();
content.repaint();
}
});
This is only getting called when "Open" is clicked as you have, I assume accidentally, added the ActionListener to the open JMenuItem rather than the newAlbum JMenuItem. To add content on startup you need to add something like this before the mainFrame.setVisible(true) line:
mainFrame.add(new NewAlbum());
BTW, the convention is for all methods in Java source code to start with a lower case letter. assignToTransientPanel would be a better name for your method.

Categories

Resources