我觉得我在某处看到了类似的东西:
这是我Details...
的所在
我觉得我看到的是,如果我的public static String iron = IronCount + " iron";
改变了,那么弦铁会改变,但它不会改变,至少在计时器中改变IronCount时不会改变。
我的完整代码在这里(没有所有public int IronCount
s):
g.fillRect()
我认为随着IronCount的改变,铁会改变,但它看不到import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class GeneratorAndGraphics extends JComponent {
private static final long serialVersionUID = 1L;
public int IronCount = 0, GoldCount = 0, DiamondCount = 0;
public String iron = IronCount + " iron"; //$NON-NLS-1$
public void paint(Graphics g) {
// vertical lines
Graphics2D g2d = (Graphics2D) g;
// iron generator
g.setColor(Color.BLACK);
g.drawRect(20, 20, 40, 40);
g.drawLine(20, 30, 60, 30);
g.setFont(new Font("Arial", Font.PLAIN, 9)); //$NON-NLS-1$
g.drawString("Iron Gen", 22, 30); //$NON-NLS-1$
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
IronCount++;
iron = IronCount + " iron"; // doesn't do anything
System.out.println(iron); // doens't print
}
},
500
);
g.drawString(iron, 25, 45);
}
}
总是说:g.drawString(iron, 25, 45);
在我的JFrame上。
也许这是Timer的一个错误,我想有一个更好的替代方案 - 比如减慢for循环的重复速度。
答案 0 :(得分:2)
建议:
super.paintComponent(g)
。repaint()
java.util.Timer
,因为这不是Swing线程安全,而是Swing Timer,例如javax.swing.Timer
。谷歌的教程。这个是一个MCVE:
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
public class Mcve extends JPanel {
private static final int TIMER_DELAY = 1000;
private static final String IRON_FORMAT = "%03d iron";
private int ironCount = 0;
public Mcve() {
setPreferredSize(new Dimension(400, 300));
new Timer(TIMER_DELAY, e -> {
ironCount++;
repaint();
}).start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(String.format(IRON_FORMAT, ironCount), 25, 45);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Mcve");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Mcve());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}