?? digitalclock.java
字號:
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class DigitalClock extends JPanel
{
public DigitalClock()
{
//指定一個UI對象
this.setUI(DigitalClockPanelUI.createUI(this));
//設定panel為不透明
this.setOpaque(true);
}
public static void main(String []args)
{
JFrame frame=new JFrame();
frame.setLocation(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DigitalClock panel=new DigitalClock();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
//繼承PanelUI類,該類在所有平臺都能用
class DigitalClockPanelUI extends PanelUI implements ActionListener
{
protected final static Font clockFont=new Font("Arial",Font.BOLD,24);
//時間顯示格式
protected final static SimpleDateFormat dateFormat=new SimpleDateFormat("hh::mm::ss a");
protected final static FontRenderContext frc=new FontRenderContext(null,true,true);
//字體之間空格
protected final static int FUDGE=6;
//含當前時間的AttribuedString
protected AttributedString timeString=null;
protected TextLayout textLayout=null;
//每秒一次的timer控件
protected javax.swing.Timer timer=new javax.swing.Timer(1000,this);
protected DigitalClock panel;
private DigitalClockPanelUI(DigitalClock panel)
{
this.panel=panel;
panel.setBackground(Color.BLACK);
actionPerformed(null);
timer.start();
}
public static ComponentUI creatUI(JComponent component)
{
return new DigitalClockPanelUI((DigitalClock)component);
}
public void paint(Graphics g,JComponent c)
{
//沒有時間或沒有textLayout時,不進行重繪
if(this.timeString==null||this.textLayout==null)
return;
Graphics2D g2=( Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
//在textLayout指示位置上顯示字符串
g2.drawString(timeString.getIterator(),1,(int)(textLayout.getAscent()));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_DEFAULT);
}
//當間隔時間到時,timer會自動調用此方法
public void actionPerformed(ActionEvent event)
{
timeString=new AttributedString (dateFormat.format(new Date()));
timeString.addAttribute(TextAttribute.FONT,clockFont);
timeString.addAttribute(TextAttribute.FOREGROUND,Color.red);
timeString.addAttribute(TextAttribute.FOREGROUND,Color.yellow,2,3);
timeString.addAttribute(TextAttribute.FOREGROUND,Color.yellow,5,6);
textLayout=new TextLayout(timeString.getIterator(),frc);
panel.repaint();
}
public Dimension getPreferredSize(JComponent c)
{
Dimension size=textLayout.getBounds().getBounds().getSize();
size.height+=FUDGE;
size.width+=(FUDGE+2);
return size;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -