How to make Start button start the game? - java

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.
}

Related

Align icon and JCheckbox in JPopupmenu

I have a Problem with some icons and check-boxes in a JPopupMenu. The Check-boxes and Icons are not aligned
The Items are created like:
JMenuItem deleteAttributeMenuItem = new JMenuItem(locale.getString("TREE_AttrDelete"), iconDelete);
JMenuItem primaryKeyAttributeMenuItem = new JCheckBoxMenuItem(locale.getString("TREE_AttrChkBoxPK"));
Please take a look at the picture:
Any tips?
Have a look at this, in order to achieve what you wanted, I did this,
JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem("Check Me", null, true);
cbmi.setMargin(new java.awt.Insets(5, 25, 5, 5));
cbmi.setIconTextGap(15);
cbmi.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
helpMenu.add(cbmi);
And here is the OUTPUT of the said thingy :
right now I can't found the right way how to re_layout JCheckBoxMenuItem,
but do you agree with this standars output from Swing by using (default) Metal Look and Feel???, just to avoiding any missunderstand by using another Look and Feel(s), because there are some differencies in the API betweens Swing's Standard Look and Feels too
from tutorials code (modified and removed balasts and noises)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuLookDemo {
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
private JTextArea output;
private JScrollPane scrollPane;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItem;
private JRadioButtonMenuItem rbMenuItem;
private JCheckBoxMenuItem cbMenuItem;
public JMenuBar createMenuBar() {
menuBar = new JMenuBar();
menu = new JMenu("A Menu");
menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
menuBar.add(menu);
menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon", errorIcon);
menu.add(menuItem);
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Another one", infoIcon);
group.add(rbMenuItem);
menu.add(rbMenuItem);
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item", warnIcon);
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
menu.add(cbMenuItem);
menu.addSeparator();
return menuBar;
}
public Container createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("MenuLookDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MenuLookDemo demo = new MenuLookDemo();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
frame.setSize(450, 260);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
these methods talking about possitions in pixels

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

JToolBar not showing

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.

JFrame Background covering menu bar

Whenever I add a background (Image img) to my JFrame I am unable to see my menu bar .... Any help would be greatly appreciated ... I'm just learning JFrames and am probably overlooking something stupid.
class GameFrame extends JFrame {
private JLabel statusbar;
Image img = new ImageIcon("splash.png").getImage();
public GameFrame() {
initUI();
menuUI();
BackgroundLoader bg = new BackgroundLoader();
}
#Override
public void paint(Graphics g) {
try {
Image img = ImageIO.read(new File("splash.png"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
} catch (IOException e) {
e.printStackTrace();
}
}
public final void initUI() {
setTitle("Super RPG Hero: The Quest for Fame and Fortune");
setSize(800, 480);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//JLabel background = new JLabel(splash);
//background.setBounds(0, 0, splash.getIconWidth(), splash.getIconHeight());
//getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
}
public final void menuUI() {
JMenuBar menubar = new JMenuBar();
//Creates file menu item
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
//Creates Object for New Game toolbar
JMenuItem newItem = new JMenuItem("New Game");
newItem.setMnemonic(KeyEvent.VK_C);
newItem.setToolTipText("New Game");
newItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String playerName = "Peter";
CharacterCreator characterOne = new CharacterCreator(playerName);
characterOne.statBuilder();
}
});
//Creates Object for Save Game toolbar
JMenuItem saveItem = new JMenuItem("Save");
saveItem.setMnemonic(KeyEvent.VK_C);
saveItem.setToolTipText("Save Game");
//Creates Object for Load Game toolbar
JMenuItem loadItem = new JMenuItem("Load");
loadItem.setMnemonic(KeyEvent.VK_C);
loadItem.setToolTipText("Load Game");
//Creates Object for Exit Game toolbar
//And creates method for the game to exit
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_C);
exitItem.setToolTipText("Exit Game");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
//Adds created objects to GUI
file.add(newItem);
file.add(saveItem);
file.add(loadItem);
file.add(exitItem);
menubar.add(file);
setJMenuBar(menubar);
}
}
You should implement paintComponent() and not paint().
By overriding paint and not delegating up, you're not letting the JFrame paint what it needs to paint.
Also, look at this answer.

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