这里是我的代码:我删除了一些我认为不必要的内容。可能我也删掉了一些括号,但我只是想展示我有的内容。
问题是,当我运行程序时,背景图像被绘制出来(它是资源中的PNG文件),只有一个按钮出现(我的PLAY按钮),这是第一个按钮 - 它是自动选择的。
实际上我有四个按钮,但我只在代码中包含了PLAY和INSTRUCTIONS。其他三个按钮除非我将鼠标悬停在它们上面否则不会显示出来。我知道这可能与paint方法有关,但我不知道该如何修复它。
如果我选择另一个按钮并最小化窗口,然后再打开它,那么选定的按钮就是唯一显示的按钮。我必须将鼠标悬停在上面才能让其他按钮显示出来。
我还在paint方法中添加了super.paint()
,我得到了所有的按钮,但背景是灰色的。我认为问题是super.paint()
会绘制出所有的按钮,而g.drawImage(bg, 0, 0, null)
只会绘制出我的背景,我不能做到两者兼顾。
如果这段话有点乱,请原谅。我是Java的新手,我很难表达我的意思。
public class MainMenu extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
//variables
public static Image bg;
public static void main(String[] args) {
MainMenu mainFrame = new MainMenu();
mainFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
mainFrame.setResizable(false);
mainFrame.setLocationRelativeTo(null);
mainFrame.setTitle ("Zumby");
mainFrame.setLayout(null);
// Loads the background image and stores in bg object.
try {
bg = ImageIO.read(new File("zumby.png"));
} catch (IOException e) {
}
mainFrame.setVisible(true);
}
/**
* Overrides the paint method.
* MONDAY
*/
public void paint(Graphics g)
{
// Draws the img to the BackgroundPanel.
System.out.println("paint");
g.drawImage(bg, 0, 0, null);
}
/**
*/
public MainMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setOpaque(false);
setContentPane(contentPane);
contentPane.setLayout(null);
//create buttons
JButton btnPlay = new JButton("PLAY");
btnPlay.setBackground(Color.BLACK);
btnPlay.setForeground(Color.WHITE);
btnPlay.setFont(font);
btnPlay.setBorder(border);
btnPlay.setFocusPainted(false);
//if "Play" is clicked
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent click) {
setVisible(false);
new GamePlay(); //opens up GamePlay window
}
});
btnPlay.setBounds(600, 64, 141, 61);
contentPane.add(btnPlay);
JButton btnInstructions = new JButton("INSTRUCTIONS");
btnInstructions.setBounds(600, 160, 141, 61);
btnInstructions.setBackground(Color.BLACK);
btnInstructions.setFocusPainted(false);
// btnInstructions.setEnabled(true);
contentPane.add(btnInstructions);
repaint();
pack();
setVisible(true);
}
}