第一次真正提出有关堆栈溢出的问题。这件事实在是让我难住了。 基本上,我有一个时钟的代码,我只是为了好玩而制作的,但是在第一次绘制之后,它不会更新。我在代码中有一条注释,我希望运行更新,但无论我在那里放什么,它实际上都不会调用paint方法(否则它会打印“day be light”)。不过,时钟确实在运行(我剪掉了实际打印时间的部分,以节省上传时的空间)。你怎么认为? 您应该能够复制并运行该代码,从而在窗口中生成一个实心圆圈和一个整数。如果图形更新,理论上该整数会改变......但事实并非如此。 是的,我正在尝试调整大小但保持方形。这可能是我的问题的一部分。
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.text.DecimalFormat;
import java.time.Clock;
import javax.swing.JFrame;
public class toUpload extends Canvas {
static Clock tickClock;
static long dmillis;
static String lastTick;
private static final long serialVersionUID = -3836576462912965111L;
private static Rectangle rect;
static JFrame mainFrame;
static DecimalFormat df = new DecimalFormat("00");
static double numberDistance;
static double sDistance;
static double mDistance;
static double hDistance;
static int Hour = 0;
static int Minute = 0;
static int Second = 0;
static int testing = 0;
public static void main(String[] args) {
toUpload t = new toUpload();
mainFrame = new JFrame();
mainFrame.setTitle("Metric Clock");
mainFrame.setResizable(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(400, 400);
rect = mainFrame.getBounds();
mainFrame.add(t);
mainFrame.setVisible(true);
mainFrame.pack();
resize();
mainFrame.addComponentListener(new ComponentListener()
{ public void componentResized(ComponentEvent evt) {
int size = evt.getComponent().getSize().width;
/*try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
mainFrame.setSize(size, size);
resize();
}
@Override public void componentMoved(ComponentEvent e) {}
@Override public void componentShown(ComponentEvent e) {}
@Override public void componentHidden(ComponentEvent e) {}
});
startTic();
while(true) {
tic();
//repaint, but for some reason I can't get it to repaint
testing++; //just something to change to show whether or not the graphics are updating.
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void resize() {
rect.height = mainFrame.getBounds().height-39;
rect.width = mainFrame.getBounds().width-16;
mainFrame.repaint();
}
public void paint(Graphics g) {
System.out.println("day be light");
g.clearRect(rect.x, rect.y, rect.width, rect.height);
g.fillOval(50,50,100,100);
g.drawString(String.valueOf(testing),50,200);
//does more stuff with painting
}
public static void tic() {
//does stuff
}
public static void startTic() {
//does stuff
}
}
最佳答案
弄清楚了(从昨天开始就一直在研究这个问题,直到现在才想起来......我创建了一个名为“t”的对象,正如你在代码中看到的那样。从来没有打算直接调用它,所以我使它成为一个非描述性的名称。千万不要这样做,伙计们。
调用t.repaint();
工作正常。
关于java - 我如何让这个公制时钟重新绘制每个节拍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58630153/