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.
Related
I have started working with JFrames and am creating a simple programme with 3 panels that are different colours and I was just wondering what would be the best way to switch between panels for my programme. The panels are to be changed when a JMenuItem with the colours name is selected. I was looking at cards and was wondering if they would be a good solution and if it would be possible to implement them into my programme? Any other suggestions would be greatly appreciated & apologies if I have done anything wrong ive only started on stack overflow and am quite a newcomer to Java :)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Colour extends JFrame
{
CardLayout card;
JPanel childPanel = new JPanel(), redPanel, bluePanel, greenPanel;
Container c;
public Colour(){
// Get Container
c=getContentPane();
//Create Menu and items
childPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu customer = new JMenu("Colour");
customer.setMnemonic(KeyEvent.VK_U);
JMenuItem blue = new JMenuItem("Blue");
JMenuItem red = new JMenuItem("Red");
JMenuItem green = new JMenuItem("Green");
customer.add(blue);
customer.add(red);
customer.add(green);
menuBar.add(customer);
this.setJMenuBar(menuBar);
//Adding panel to container
c.add(childPanel);
childPanel.setBackground(Color.PINK);
//Action Listeners for switching panels
blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );}
//Creating my different panels and adding them to childPanel
public void redC() {
redPanel = new JPanel();
redPanel.setBackground(Color.RED);
childPanel.add(redPanel, "Red");
}
public void blueC() {
bluePanel = new JPanel();
bluePanel.setBackground(Color.BLUE);
childPanel.add(bluePanel, "Blue");
}
public void greenC() {
greenPanel = new JPanel();
greenPanel.setBackground(Color.GREEN);
childPanel.add(greenPanel, "Green");
}
public static void main(String[] args) {
Colour cl=new Colour();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
You are almost done with you code.
Here is the working code.
You need to revalidate the childPanel after adding/removing a panel so that it will be repainted:
//Action Listeners for switching panels
blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() >0)
childPanel.remove(0);
blueC();
childPanel.revalidate();
}
});
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() > 0)
childPanel.removeAll();
redC();
childPanel.revalidate();
}
});
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() > 0)
childPanel.remove(0);
greenC();
childPanel.revalidate();
}
});
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.
}
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);
}
}
My code works correctly, except for the submenu. The "Import" button is supposed to expand into newsfeed, bookmarks, and mail. However, the program doesn't even display "Import". It displays the first submenu entry ("newsfeed") which cannot be hovered. What am I doing wrong?
import javax.swing.*;
import java.awt.event.*;
public class test extends JFrame{
private static final long serialVersionUID = 1L;
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
test ex = new test();
ex.setVisible(true);
}
});
}
public test()
{
initGUI();
}
public final void initGUI()
{
JMenuBar menubar = new JMenuBar();
ImageIcon exitIcon = new ImageIcon("icons/exit.png");
ImageIcon openIcon = new ImageIcon("icons/open.png");
ImageIcon newIcon = new ImageIcon("icons/new.png");
ImageIcon saveIcon = new ImageIcon("icons/save.png");
JMenu file = new JMenu("File");
JMenuItem importMenu = new JMenuItem("Import");
importMenu.setMnemonic(KeyEvent.VK_M);
JMenuItem newsfeedMenu = new JMenuItem("Import newsfeed list...");
JMenuItem bookmarksMenu = new JMenuItem("Import bookmarks...");
JMenuItem mailMenu = new JMenuItem("Import mail...");
importMenu.add(newsfeedMenu);
importMenu.add(bookmarksMenu);
importMenu.add(mailMenu);
JMenuItem newMenu = new JMenuItem("New", newIcon);
newMenu.setMnemonic(KeyEvent.VK_N);
newMenu.setToolTipText("Start new document");
JMenuItem openMenu = new JMenuItem("Open", openIcon);
openMenu.setMnemonic(KeyEvent.VK_O);
openMenu.setToolTipText("Open document");
JMenuItem saveMenu = new JMenuItem("Save", saveIcon);
saveMenu.setMnemonic(KeyEvent.VK_S);
saveMenu.setToolTipText("Save document");
JMenuItem exitMenu = new JMenuItem("Exit", exitIcon);
exitMenu.setMnemonic(KeyEvent.VK_X);
exitMenu.setToolTipText("Exit application");
exitMenu.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
exitMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
KeyEvent.CTRL_MASK));
file.add(newMenu);
file.add(openMenu);
file.add(saveMenu);
file.addSeparator();
file.add(importMenu);
file.addSeparator();
file.add(exitMenu);
menubar.add(file);
setJMenuBar(menubar);
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton button = new JButton("Quit");
button.setBounds(100,60,80,40);
button.setToolTipText("Press");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
panel.add(button);
setSize(300, 200);
setTitle("testGUI");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Change it to a JMenu
JMenu importMenu = new JMenu("Import");
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.