我正在研究这个小赛马模拟器并坚持下去。我希望用户首先选择比赛中的马匹数量(2-6),然后单击“开始”按钮。然后,我想绘制/绘制赛道和马(用圆圈表示)。出于某种原因,当代码达到创建 Horse 实例的程度时,它永远不会被绘制到框架中。下面是代码。我错过了什么?
主.java:
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
RaceTrack myRace = new RaceTrack();
myRace.setVisible(true);
}
});
}
}
RaceTrack.java:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;
public class RaceTrack extends JFrame implements Runnable {
public RaceTrack() {
initUI();
}
public static int selectedRaceSize = 2;
private void initUI() {
final Container pane = getContentPane();
String horseNum[] = { "2", "3", "4", "5", "6" };
JPanel buttonPanel = new JPanel();
Border border = BorderFactory.createTitledBorder("Please select number of horses:");
buttonPanel.setBorder(border);
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton aRadioButton;
// For each String passed in:
// Create button, add to panel, and add to group
for (int i = 0, n = horseNum.length; i < n; i++) {
if (i == 0) {
// Default selection
aRadioButton = new JRadioButton(horseNum[i], true);
} else {
aRadioButton = new JRadioButton(horseNum[i]);
}
buttonPanel.add(aRadioButton);
buttonGroup.add(aRadioButton);
}
pane.add(buttonPanel, BorderLayout.PAGE_START);
final JPanel raceTrackPanel = new JPanel(null);
final JButton startButton = new JButton("Start!");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
startButton.setEnabled(false);
Horse horse1 = new Horse("horse1");
raceTrackPanel.add(horse1);
pane.add(raceTrackPanel, BorderLayout.CENTER);
repaint();
}
});
pane.add(startButton, BorderLayout.PAGE_END);
startButton.setBounds(50, 200, 300, 30);
setTitle("Horse Race v1.0");
setSize(400, 300);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void run() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
}
马.java:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Horse extends JPanel implements Runnable {
Thread runner;
public Horse() {
}
public Horse(String threadName) {
runner = new Thread(this, threadName);
runner.start();
}
public void run() {
this.repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(252, 211, 61));
g2d.drawOval(20, 25, 10, 10);
g2d.fillOval(20, 25, 10, 10);
}
}