第一次实际在堆栈溢出时提出问题。这真的让我很困惑。基本上,我有一个用于娱乐的时钟代码,但是在第一次绘制后,它不会更新。我在代码中有一个注释,希望在其中运行更新,但是无论我放在哪里,它实际上都不会调用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();
效果很好。