gpt4 book ai didi

java - 合并 JPanel 类和对象声明类

转载 作者:行者123 更新时间:2023-12-01 04:11:44 25 4
gpt4 key购买 nike

我有这两个类,一个是 JPanel 类,一个是用于在 JPanel 上设置对象的类,为了简单起见,我想合并这两个类,以便与在 JPanel 上进行的操作有关的所有内容JPanel 位于一处。

不用说,我不明白该怎么做:

public class RacePanel extends JPanel  {

private boolean reset = false;
private horse h1, h2, h3;
private int increase;
public RacePanel(){

h1 = new horse(20,10);
h2 = new horse(20,55);
h3 = new horse(20,100);

new PausableThread(new readySet(){
public void go(){
try {

Random randomNum = new Random();

increase = randomNum.nextInt(10);
h1.setPosition(h1.getPosition() + increase);
increase = randomNum.nextInt(10);
h2.setPosition(h2.getPosition() + increase);
increase = randomNum.nextInt(10);
h3.setPosition(h3.getPosition() + increase);
Thread.sleep(50);

if(reset){
h1.setPosition(20);
h2.setPosition(20);
h3.setPosition(20);
reset=false;
}
if(h1.getPosition() >= 415){

PausableThread.pause();
JOptionPane.showMessageDialog(getRootPane(),"Horse one is the winner", "We Have A Winner!", JOptionPane.PLAIN_MESSAGE);
setReset(true);
}
else if(h2.getPosition() >= 415){

PausableThread.pause();
JOptionPane.showMessageDialog(getRootPane(),"Horse two is the winner", "We Have A Winner!", JOptionPane.PLAIN_MESSAGE);
setReset(true);
}
else if(h3.getPosition() >= 415){

PausableThread.pause();
JOptionPane.showMessageDialog(getRootPane(),"Horse three is the winner", "We Have A Winner!", JOptionPane.PLAIN_MESSAGE);
setReset(true);
}

repaint();

} catch(InterruptedException e) {

e.printStackTrace();
}
}

});


}

public void setReset(boolean bool){
reset = bool;
}

@Override
public void paintComponent(Graphics image){
super.paintComponent(image);
image.setColor(Color.GRAY);
image.fillRect(40,20,415,4);
h1.draw(image);
image.fillRect(40,65,415,4);
h2.draw(image);
image.fillRect(40,110,415,4);
h3.draw(image);
}

}

设置马对象的类是:

public class horse {


private int xPosition, yPosition;
private Image horse;

public horse(int x, int y){

horse = getImage("mustang.gif");
xPosition = x;
yPosition = y;
}

private Image getImage(String filename) {
URL url = getClass().getResource( filename );
ImageIcon icon = new ImageIcon( url );
return icon.getImage();
}

public void draw(Graphics image){
image.drawImage(horse, this.xPosition, this.yPosition, null);
}

public void setPosition(int value){
xPosition = value;
}

public int getPosition(){
return xPosition;
}

public void drawhorse(Graphics image){
image.drawImage(horse, xPosition, yPosition, null);
}

}

我确信这是可能的,但是当我尝试这样做时,我不断收到错误。大家有什么想法吗?

谢谢!

最佳答案

如果您想将这些类放入同一个文件中,则需要从 horse 中删除 public 修饰符

文件:RacePanel.java

public class RacePanel extends JPanel {

}

class horse {

}

或者你可以将 is 作为内部类

public class RacePanel {

// all other panel code

private class horse{

}
}

关于java - 合并 JPanel 类和对象声明类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19864814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com