光标经过按钮没有反应,点击也没有反应;
(jp1是gp的Panel,jp1放有对战按钮。背景和jp1的组件(对战按钮)先绘制到offScreenImage1上,再绘制到界面(双缓存))
ActionListener也设置了,requireFocus也试过了,究竟是为什么呢?谢谢!
用代码块功能插入代码,请勿粘贴截图
public class Main {
public static void main(String[] args) {
GameFrame gf = new GameFrame();
gf.launch();
}
}
// GameFrame类
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class GameFrame extends JFrame {
final int width = 600;
final int height = 1000;
int state = 0;//0:initial 1:battle
int card = 0;
JPanel jp1 = new JPanel(true);
//JPanel jp2 = new JPanel(true);
Image offScreenImage1 = null;
//Image offScreenImage2 = null;
ArrayList<GameObject> gameObjects = new ArrayList<>();
public void launch() {
setTitle("Clash Royale");
setSize(width, height);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
inital();
//this.addMouseListener();
//gameObjects.add(new witch(245, 500, "images/witch_NE.png", this));
//((witch)(gameObjects.get(0))).myThread.start();
while (true) {
repaint();
try {
Thread.sleep(25);
}catch (Exception e) {
e.printStackTrace();
}
}
}
public void inital() {
//绘制背景
offScreenImage1 = this.createImage(width, height);
Graphics offScreenImage1Graphics = offScreenImage1.getGraphics(); //浅克隆
offScreenImage1Graphics.setColor(Color.gray);
offScreenImage1Graphics.fillRect(0, 0, width, height);
offScreenImage1Graphics.setColor(Color.orange);
offScreenImage1Graphics.setFont(new Font("微软雅黑", Font.BOLD, 50));
offScreenImage1Graphics.drawString("Clash Royale", 150, 100);
//设置ToBattleButton
Image ToBattleImage = Toolkit.getDefaultToolkit().getImage("images/ToBattleImage.jpg");
Image ToBattleImage_temp = ToBattleImage.getScaledInstance(200, 100, 1);
ImageIcon ToBattleButtonIcon = new ImageIcon(ToBattleImage_temp);
JButton ToBattleButton = new JButton(ToBattleButtonIcon);
ToBattleButton.setVisible(true);
ToBattleButton.setBounds(200, 600,200, 100);
ActionListener_ToBattle actionListener_toBattle = new ActionListener_ToBattle();
ToBattleButton.addActionListener(actionListener_toBattle);
//
jp1.setOpaque(false);
jp1.add(ToBattleButton, BorderLayout.CENTER);
this.add(jp1);
jp1.paintComponents(offScreenImage1Graphics);
}
@Override
public void paint(Graphics g) {
if (state==0) {
g.drawImage(offScreenImage1, 0, 0, null);
}
}
public class ActionListener_ToBattle implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
state = 1;
System.out.println(1);//用来检测点击功能
}
}
}
运行结果
运行结果是光标经过对战按钮没有反应,点击也没有输出1;