package personal.wt.clock;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.Timer;
/**
* Created by wt on 2018/9/28.
*/
public class ClockPanel extends JPanel {
public static final int WIDTH = 450;
public static final int HEIGHT = 300;
private JButton exitBtn = null;
private JLabel label = null;
private Calendar calendar;
public ClockPanel(){
this.setLayout(null);
calendar = Calendar.getInstance();
calendar.setTime(new Date());
this.label = new JLabel(Utils.getTimeStr());
this.label.setBounds(330,15,150,25);
this.add(label);
this.exitBtn = new JButton("退出程序");
this.exitBtn.setBackground(Color.GREEN);
this.exitBtn.addActionListener(e->System.exit(0));
this.exitBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
Random random = new Random();
int locationX = random.nextInt(400);
int locationY = random.nextInt(120);
System.out.println("locationX:"+locationX+" locationY:"+locationY);
System.out.println(e.getX());
if(e.getX()>50){
ClockPanel.this.exitBtn.setBounds(locationX,locationY,80,25);
}
}
});
this.exitBtn.setBounds(360,260,80,25);
this.add(this.exitBtn);
this.setPreferredSize(new Dimension(WIDTH,HEIGHT));
this.setBackground(new Color(200,235,250));
TimerTask task = new TimerTask() {
@Override
public void run() {
ClockPanel.this.calendar.setTime(new Date());
ClockPanel.this.label.setText(Utils.getTimeStr());
ClockPanel.this.repaint();
}
};
Timer timer = new Timer();
//每隔一秒重新绘制表盘
timer.schedule(task,0,1000);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int centerR = 4;
g.setColor(new Color(43,25,126));
g.fillOval(WIDTH/2-centerR,HEIGHT/2-centerR,centerR*2,centerR*2);
int centerX = WIDTH/2;
int centerY = HEIGHT/2;
int clockR = 120;
int time = 0;
double degree = -Math.PI/2;
double degreeStep = Math.PI*2/12;
//绘制0-11刻度值
while(time<12){
double strX = centerX + clockR * Math.cos(degree);
double strY = centerY + clockR * Math.sin(degree);
g.drawString(time+"",(int)strX,(int)strY);
degree += degreeStep;
time += 1;
}
//绘制圆环
int innerOval = 217;
int outerOval = 267;
g.drawOval(centerX-innerOval/2, centerY-innerOval/2, innerOval, innerOval);
g.drawOval(centerX-outerOval/2, centerY-outerOval/2, outerOval, outerOval);
//时针
ClockPointer2 pot = new ClockPointer2(50,Color.BLACK);
double dH = Utils.getDegree(calendar,"H");
pot.rorate(dH);
pot.drawPointer(g);
//分针
ClockPointer2 pot1 = new ClockPointer2(80,Color.RED);
double dM = Utils.getDegree(calendar,"M");
pot1.rorate(dM);
pot1.drawPointer(g);
//秒针
ClockPointer2 pot2 = new ClockPointer2(105,Color.YELLOW);
double dS = Utils.getDegree(calendar,"S");
pot2.rorate(dS);
pot2.drawPointer(g);
}
}
java GUI时钟小程序
需积分: 50 113 浏览量
2018-09-30
10:12:32
上传
评论 2
收藏 46KB ZIP 举报
普通网友
- 粉丝: 4
- 资源: 4