为什么paintComponent()方法总是在执行?
我仿照Java核心技术里面的一个程序,输入小时和分钟,在一个圆里面实现时针和分针。现在程序可以运行,但是在Debug的时候,由于我在画时钟的类的paintcomponent设置了一个断点,只要从代码切换到图形,就会停在这个地方。paintcomponent方法不是应该就在初始化的时候调用一次码,为什么总要执行。
下面是我的代码:
import java.awt.*;
import java.awt.geom.*;
import java.awt.geom.Ellipse2D.Double;
import javax.swing.event.*;
import javax.swing.*;
public class TextTest {
public static void main(String[] args) {
// Add a frame
TextTestFrame frame = new TextTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
// Create a clock frame
class TextTestFrame extends JFrame {
public TextTestFrame() {
setTitle("TextTest");
// Draw the bottom line
JPanel panel = new JPanel();
JLabel label = new JLabel("Hours:");
panel.add(label);
hour_text = new JTextField("12", 3);
panel.add(hour_text);
JLabel label2 = new JLabel("Minutes:");
panel.add(label2);
minute_text = new JTextField("00", 3);
panel.add(minute_text);
add(panel, BorderLayout.SOUTH);
// Add the listener
clockFieldListener listener = new clockFieldListener();
hour_text.getDocument().addDocumentListener(listener);
minute_text.getDocument().addDocumentListener(listener);
// Draw clock panel
clockPanel = new DrawPanel();
add(clockPanel, BorderLayout.CENTER);
pack();
}
public void DrawClock() {
try {
clockPanel.setTime(Integer.parseInt(hour_text.getText()), Integer
.parseInt(minute_text.getText()));
clockPanel.repaint();
} catch (NumberFormatException e) {
//
}
}
public JTextField hour_text;
public JTextField minute_text;
public DrawPanel clockPanel;
public class clockFieldListener implements DocumentListener {
public void insertUpdate(DocumentEvent event) {
DrawClock();
}
public void changedUpdate(DocumentEvent event) {
}
public void removeUpdate(DocumentEvent event) {
DrawClock();
}
}
}
class DrawPanel extends JPanel {
public DrawPanel() {
setPreferredSize(new Dimension(2 * RADIUS + 1, 2 * RADIUS + 1));
}
public void paintComponent(Graphics g) { --就是这里了,Debug的时候只要切换出去就会又停在这里
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// Draw the circle
Ellipse2D elli = new Ellipse2D.Double();
elli.setFrameFromCenter(new Point2D.Double(RADIUS, RADIUS),
new Point2D.Double(0, 0));
g2.draw(elli);
// Draw the hour hand and minute hand
double hourAngle = Math.toRadians(90 - 360 * minute / (12 * 60));
DrawHand(g2, hourAngle, HOUR_HAND_LENGTH);
// Draw the minute hand
double minuteAngle = Math.toRadians(90 - 360 * minute / 60);
DrawHand(g2, minuteAngle, MINUTE_HAND_LENGTH);
}
public void DrawHand(Graphics2D g2, double angle, double length) {
Point2D p = new Point2D.Double(RADIUS + length * Math.cos(angle),
RADIUS - length * Math.sin(angle));
g2.draw(new Line2D.Double(p, new Point2D.Double(RADIUS, RADIUS)));
}
public void setTime(int h, int m) {
minute = h * 60 + m;
}
public static final int RADIUS = 100;
private double minute = 0;
private double HOUR_HAND_LENGTH = 0.6 * RADIUS;
private double MINUTE_HAND_LENGTH = 0.8 * RADIUS;
}