I am trying to create a JFrame with a JMenubar and a JPanel in it with a background image. The code I have so far create 2 window, a JFrame and a JPanel, the JFrame has the JMenuBar and the JPanel has the background, can I put these together into 1 window?
package RPGPackage;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.JMenuBar;
public class RPG extends JFrame {
public RPG() {
JFrame frame = new JFrame("RPG");
frame.setVisible(true);
frame.setSize(1005,710);
frame.setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
frame.add(panel);
setLocation(0,0);
setVisible(true);
setSize(1005,710);
setResizable(false);
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_A);
menubar.add(file);
JMenuItem Load = new JMenuItem("Load",KeyEvent.VK_L);
file.add(Load);
JMenuItem Save = new JMenuItem("Save",KeyEvent.VK_S);
file.add(Save);
JMenuItem exit = new JMenuItem(new AbstractAction("Quit"){//Adds Exit button
public void actionPerformed(ActionEvent e) {//adds an action to the JMenuItem "Exit"
System.exit(0);}//when action is performed program will exit
});
file.add(exit);//adds the JMenuitem to the JMenuBar thats above.
Background background = new Background();
add(background);
}
public static void main(String[] args) {
RPG window = new RPG();
}
}
package RPGPackage;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Background extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon background = new ImageIcon("Image.png");
background.paintIcon(this, g, 0, 0);
}
}
1) your
RPG
class extendsJFrame
, you needn't to create another instance of frame(
JFrame frame = new JFrame("RPG");
). Use yourRPG
instance.2) Use
BufferedImage
instead ofImageIcon
, and draw image like next :3) call
setVisible(true);
at the end of interface construction or like next :4) setResizable(false); it's bad practice. Manage component resizing with help of
LayoutManager
.5)use
pack();
method instead ofsetSize(...)
I have fixed your code, examine it :
Also instead of painting image you can use
JLabel
for holding and painting that, it helps you to get some features from the box :