1
我想創建一個帶有JMenubar和JPanel的JFrame與背景圖像。我迄今爲止創建的代碼創建了兩個窗口,一個JFrame和一個JPanel,JFrame具有JMenuBar,JPanel具有背景,我可以將它們放在一個窗口中嗎?JFrame與JMenuBar和java中的背景Netbeans
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);
}
}