我正在用java编写游戏。这里的问题是我写了我的游戏在JFrame中运行,而不是认为我想要添加菜单和结果屏幕以及所有好东西。游戏本身在JFrame中运行良好。不过我决定做的是将我的JFrame转换为JPanel,为我的JFrame创建一个单独的类,然后将我的JPanel添加到框架中。除了我的MouseListener不再做一件令人讨厌的事情之外,一切都工作得很好。有人可以告诉我如何完成这项工作或不知道如何做到这一点?
///// UPDATE 显然我在重新创建问题时找到了答案....我只需要弄清楚我的游戏代码和测试代码之间的区别。
这是我写的试图重现问题的例子。奇怪的是,这有效。现在我更加困惑。显然这没关系:
//Class for the JFrame
package mousetest;
import java.awt.Color;
import javax.swing.JFrame;
public class MouseTest extends JFrame{
public static void main(String[] args) {
MouseTest test = new MouseTest();
}
public MouseTest(){
//create teh board
Board game = new Board();
//framestuff
setSize(406, 630);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
setBackground(Color.black);
add(game); // add it
}
}
=============================================== =========================
//Class for the JPanel that my game is in
package mousetest;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Board extends JPanel{
JLabel testlabel = new JLabel("testtext");
//CONSTRUCTOR
public Board(){
setBackground(Color.WHITE);
testlabel.addMouseListener(new Mousehandle());
setVisible(true);
add(testlabel);
}
// control ALLTHECLICKS!!!!!
class Mousehandle implements MouseListener{
public Mousehandle(){
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if(e.getSource() == testlabel){
System.out.println("mouse down");
}
}
public void mouseReleased(MouseEvent e) {
if(e.getSource() == testlabel){
System.out.println("mouse up");
}
}
public void mouseEntered(MouseEvent e) {
if(e.getSource() == testlabel){
System.out.println("rollover");
}
}
public void mouseExited(MouseEvent e) {
if(e.getSource() == testlabel){
System.out.println("roll off");
}
}
public void mouseDragged(MouseEvent e){
}
}
}