import java.awt.*; import javax.swing.*; import java.awt.Event.*; import java.awt.geom.*; import javax.swing.event.*; public class TextTest { public static void main(String[] args){ new TextFrame(); } } class TextFrame extends JFrame { private ClockPanel clock; private JTextField hourField; private JTextField minuteField; public TextFrame(){ clock = new ClockPanel(); add(clock,BorderLayout.CENTER); JPanel input = new JPanel(); add(input,BorderLayout.SOUTH); hourField = new JTextField("3",2); minuteField = new JTextField("0",2); ClockListener listener = new ClockListener(); hourField.getDocument().addDocumentListener(listener); minuteField.getDocument().addDocumentListener(listener); input.add(new JLabel("Hour:")); input.add(hourField); input.add(new JLabel("Minute:")); input.add(minuteField); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocation(300,300); setSize(400,450); setVisible(true); } private class ClockListener implements DocumentListener { public void insertUpdate(DocumentEvent e){ setClock(); } public void removeUpdate(DocumentEvent e) { setClock(); } public void changedUpdate(DocumentEvent e){ setClock(); } } private void setClock(){ int hour = 0; int min = 0; try { hour = Integer.parseInt(hourField.getText()); min = Integer.parseInt(minuteField.getText()); } catch (NumberFormatException e){ return;} clock.setTime(hour,min); } } class ClockPanel extends JPanel { private int hour; private int minute; public ClockPanel(){ this.hour = 3; this.minute = 0; } public void paintComponent(Graphics g ) { double hourangle; double minuteangle; System.out.println("draw"+hour+":"+minute); super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; Ellipse2D circle = new Ellipse2D.Double(0, 0, 380, 380); g2.draw(circle); //注意int计算,类型转换问题 hourangle = (60.0*hour+minute)/(12*60)*2*(Math.PI); minuteangle = minute/60.0*2*(Math.PI); //System.out.println("angle"+hourangle+":"+minuteangle); Point2D hourpoint = new Point2D.Double(190+100*Math.sin(hourangle),190-100*Math.cos(hourangle)); Point2D minutepoint = new Point2D.Double(190+180*Math.sin(minuteangle),190-180*Math.cos(minuteangle)); Point2D center = new Point2D.Double(190,190); g2.draw(new Line2D.Double(center, hourpoint)); g2.draw(new Line2D.Double(center, minutepoint)); } public void setTime(int hour,int minute){ this.hour = hour; this.minute = minute; repaint(); } }