JFrame Background covering menu bar - java

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.

Related

How to make Start button start the game?

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

add Graphics to JFrame

I just started to learn Graphics in Java.
can someone explain that what is different between super() and JFrame?
when I used super() I can draw Graphics, but I can't draw in JFrame.
public class Screen extends JFrame {
public JFrame fra = new JFrame();
private static final long serialVersionUID = 1L;
BufferedImage img=null;
public void paint(Graphics g){
try{
img=ImageIO.read(new File("D:/strawberry.jpg"));
}catch (IOException e){}
try{
g.drawImage(img, 100,100, null);
}catch (Exception e){}
}
public Screen()
{
/*
super ("kingdom");
setSize(700,700);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
*/
// normal JFrame--------------------------------------------------
fra.setTitle("kingdom");
fra.setSize(600,600);
fra.setResizable(false);
fra.setDefaultCloseOperation(EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenu option = new JMenu("Option");
JMenuItem open = new JMenuItem("Open");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem controlkey = new JMenuItem("Control key");
JMenuItem sound = new JMenuItem("Sound");
fra.setJMenuBar(bar);
bar.add(file);
bar.add(edit);
bar.add(option);
file.add(open);
file.add(save);
file.add(exit);
edit.add(controlkey);
edit.add(sound);
fra.setVisible(true);
//-------------------------------------------------------------
}
public static void main(String[] a){
new Screen();
}
}
Do the drawing in a class that extends JPanel, then set an instance of that class as the content pane of the frame, or add it to the content pane whatever suits you. You can also do this with a class that extends a bare JComponent of course.
The drawing in that class would be done in an override of paintComponent.

Trouble adding JMenuBar to extended JFrame

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

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.

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