请看看我的代码。不知道在JPanel上正确刷新我的变量elapsed
。我使用g.drawString(var,x,y)
但根本没有重新粉饰。
数字是一个在另一个上面写的。
我该如何解决这个问题?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CCrono {
public static void main(String[] a) {
TimeFrame frame = new TimeFrame();
frame.setDefaultCloseOperation(3);
frame.setVisible(true);
}
}
/**
* Frame with Time Panel
*/
class TimeFrame extends JFrame {
//Constructor
public TimeFrame() {
//Dimentions
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screen = kit.getScreenSize();
int height = screen.height;
int wide = screen.width;
//Size
setSize(wide / 2, height / 2);
//Localization
setLocation(wide / 4, height / 4);
//Title
setTitle("Cronometer");
//Panel
TimePanel panel = new TimePanel();
Container container = getContentPane();
container.add(panel);
}
}
/**
* Panel showing elapsed time
*/
class TimePanel extends JPanel {
String elapsed = "";
int coo_x;
int coo_y;
int sec = 0;
int min = 0;
int hou = 0;
TimePanel() {
this.coo_x = 100;
this.coo_y = 100;
RepaintMethod paintMe = new RepaintMethod();
Timer timer = new Timer(100, paintMe);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
sec++;
if (sec == 60) {
min++;
sec = 0;
}
if (min == 60) {
hou++;
min = 0;
}
if (hou == 24) {
hou =0 ;
}
elapsed = (hou < 10 ? "0" : "") + hou + ":" + (min < 10 ? "0" : "") + min + ":" + (sec < 10 ? "0" : "") + sec;
g.drawString(elapsed, coo_x, coo_y);
}
private class RepaintMethod implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
repaint();
}
}
}
有什么建议吗?
谢谢你们所有人。
答案 0 :(得分:3)
致电
super.paintComponent(g);
paintComponent
方法中的
public void paintComponent(Graphics g) {
super.paintComponent(g); // call here
...
}
从oracle网站
阅读paint mechanism