三、綜合應(yīng)用題
本題的功能是用文本框來設(shè)定表盤中指針的位置。窗口中有一個畫板和兩個文本框,畫板中繪制了一個表盤和時針、分針,通過文本框分別設(shè)定“時”和“分”,表盤中的時針和分針就會指到對應(yīng)的位置上。
import java.awt.*;
import java.awt.event*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
public class java3
{
public static void main(String[]args)
{
TextTestFrame frame=new TextTestFrame():
frame.setDefauhCloseOperation(JFrame.EXIT_
0N_CLOSE);
frame.show();
}
}
class TextTestFrame extends JFrame
{
public TextTestFrame()
{
setTitle("java3"):
setSize(DEFAULT_WIDTH,DEFAULT_
HElGHT);
Container contentPane=getContentPane();
DocumentListener listener=new DoeumentListen-
er();
JPanel panel=new JPanel();
hourField=new JTextField("12",3);
panel.add(hourField);
hourField.getDocument().addDocumentListener
(this);
minuteField=new JTextField("00",3):
panel.add(minuteField);
minuteField.getDocument().addDocumentListener
(listener);
contentPane.add(panel,BorderLayout.S()UTH);
clock=new ClockPanel();
contentPane.add(clock,BorderLayout.CEN-
TER);
}
public void setClock()
{
try
{
int hours
=Integer.parseInt(hourField.getText().trim
()):
int minutes
=Integer.parseInt(minuteField.getText().trim
());
clock.setTime(hours,minutes);
}
catch(NumberFormatExcepfion e){}
}
public static final int DEFAULT_WIDTH=300;
public static final int DEFAULT_HEIGHT
=300;
private J TextField hourField;
private JTextField minuteField;
private ClockPanel clock;
private class clockFieldListener extends Docu-
mentListener
{
public void insertUpdate(DocumentEvent e){ set-
Clock();}
public void removeUpdate(DocumentEvent e){
setClock();}
public void changedUpdate(DocumentEvent e){}
}
}
class ClockPanel extends JPanel
{
pubhc void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphies2D g2=(Graphics2D)g;
Ellipse2D circle
=new Ellipse2D.Double(0,0,2* RADIUS,2
*RADIUS);
g2.draw(circle);
double hourAngle
=Math.toRadians(90-360*minutes/(12
*60));
drawHand(92,hourAngle,HOUR_HAND_
LENGTH);
double minuteAngle
=Math.toRadians(90-360*minutes/60);
drawHand(g2,minuteAngle,MINUTE_HAND_
LENGTH):
}
punic void drawHand(Graphics2D g2,
double angle,double handLength)
{
Point2D end=new Point2D.Double(
RADIUS+handLength*Math.cos(angle),
RADIUS-handLength*Math.sin(angle));
Point2D center=new Point2D.Double(RADIUS,
RADIUS):
g2.draw(new Line2D.Double(center,end));
}
public void setTime(int h,int m)
{
minutes=h*60+m;
repaint();
}
private double minutes=0;
private double RADIUS=100;
private double MINUTE_HAND_LENGTH=
0.8*RADIUS;
private double HOUR_HAND_LENGTH=0.6
*RADIUS:
}
相關(guān)推薦:北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內(nèi)蒙古 |