修改以下代码,要求能够以图片做背景,并且在按钮点击后,窗口不消失,直接改变为下一界面 private JButton SimpleButton; private JButton HardButton; int mode=0; public ChengYuJieLong() { panel= new JPanel(); SimpleButton = new JButton("娱乐模式"); SimpleButton.addActionListener(this); panel.add(SimpleButton); HardButton = new JButton("挑战模式"); HardButton.addActionListener(this); panel.add(HardButton); add(panel); revalidate(); repaint(); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == SimpleButton) { mode = 1; System.out.println("娱乐模式已选中"); Gameplay(mode); } if (e.getSource() == HardButton) { mode = 2; System.out.println("挑战模式已选中"); Gameplay(mode); } try { ChengYuJieLong frame = new ChengYuJieLong(); frame.setVisible(true); } catch (Exception e1) { e1.printStackTrace(); } }
时间: 2024-02-14 10:15:35 浏览: 86
以下是修改后的代码,实现了以图片做背景,并且在按钮点击后,窗口不消失,直接改变为下一界面:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChengYuJieLong extends JFrame implements ActionListener {
private JButton SimpleButton;
private JButton HardButton;
private JPanel panel;
private JLabel backgroundLabel;
int mode = 0;
public ChengYuJieLong() {
panel = new JPanel();
panel.setLayout(null);
// 设置背景图片
ImageIcon background = new ImageIcon("background.jpg");
backgroundLabel = new JLabel(background);
backgroundLabel.setBounds(0, 0, background.getIconWidth(), background.getIconHeight());
panel.add(backgroundLabel);
SimpleButton = new JButton("娱乐模式");
SimpleButton.setBounds(100, 100, 200, 50);
SimpleButton.addActionListener(this);
backgroundLabel.add(SimpleButton);
HardButton = new JButton("挑战模式");
HardButton.setBounds(100, 200, 200, 50);
HardButton.addActionListener(this);
backgroundLabel.add(HardButton);
add(panel);
setSize(background.getIconWidth(), background.getIconHeight());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == SimpleButton) {
mode = 1;
System.out.println("娱乐模式已选中");
Gameplay(mode);
}
if (e.getSource() == HardButton) {
mode = 2;
System.out.println("挑战模式已选中");
Gameplay(mode);
}
}
public void Gameplay(int mode) {
// 在这里添加下一界面的代码
// 窗口不消失,直接改变为下一界面
// 例如:new NextFrame(mode);
}
public static void main(String[] args) {
ChengYuJieLong frame = new ChengYuJieLong();
}
}
```
需要注意的是,在设置背景图片时,需要将按钮添加到 `backgroundLabel` 上,而非 `panel` 上。此外,为了实现窗口不消失,直接改变为下一界面,需要在 `Gameplay` 方法中添加下一界面的代码。
阅读全文