我有这两个类,一个是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);
}
}
我确信这是可能的,但是当我尝试这样做时,我一直都会遇到错误。 任何想法的家伙?
谢谢!
答案 0 :(得分:0)
如果您的意思是想要将这些类放入同一个文件中,则需要从public
horse
修饰符
文件:RacePanel.java
public class RacePanel extends JPanel {
}
class horse {
}
或者你可以将is作为内部类
public class RacePanel {
// all other panel code
private class horse{
}
}