如果你讀過關於效率或時間管理的文章,大概聽過番茄工作法(Pomodoro Technique)。它的核心很簡單:
多數人會依自己的節律微調,例如每 2 個番茄鐘就長休一次,剛開始實踐時尤其如此。
它的價值不在計時本身,而在強迫你為「一次專注」設定明確邊界——倒數計時的壓力會讓人自動關掉不相關的分心來源。
這個小工具涉及幾個實用的桌面開發技巧:圓角視窗、自訂標題列、系統托盤、以及倒數計時。
// 圓角
AWTUtilities.setWindowShape(this,
new RoundRectangle2D.Double(0.0D, 0.0D,
getWidth(), getHeight(), 26.0D, 26.0D));
setUndecorated(true);
隱藏之後視窗就沒有標題列了,因此必須自己做一個,並加上拖曳移動的功能。
public class MouseMoveListener extends MouseAdapter implements MouseMotionListener {
private Component parentComponent; // 被拖動的視窗
private Component dragCom; // 可按下拖曳的元件(標題列)
private Point offset; // 按下位置相對元件的偏移
public synchronized void install(Component comp, Component dragCom) {
uninstall();
parentComponent = comp;
this.dragCom = dragCom;
dragCom.addMouseListener(this);
dragCom.addMouseMotionListener(this);
}
public synchronized void uninstall() {
if (dragCom != null) {
dragCom.removeMouseListener(this);
dragCom.removeMouseMotionListener(this);
dragCom = null;
}
}
@Override
public void mousePressed(MouseEvent e) {
if (e.getSource() == dragCom) {
offset = e.getPoint(); // 記下按下時的位置
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (e.getSource() != dragCom) return;
final int x = parentComponent.getX();
final int y = parentComponent.getY();
final Point lastAt = e.getPoint();
parentComponent.setLocation(x + lastAt.x - offset.x,
y + lastAt.y - offset.y);
}
}
使用方式:
MouseMoveListener mouseMoveListener = new MouseMoveListener(); mouseMoveListener.install(this, titlePanel);
兩個參數分別是「要移動的視窗」與「可以按住拖曳的元件」。
這裡有個關鍵設計:用 offset 記錄按下瞬間的滑鼠位置,拖動時用差值計算位移。如果直接 setLocation(e.getPoint()),視窗左上角會黏在滑鼠上,拖起來會有跳動感。
private void initTrayIcon() {
PopupMenu popup = new PopupMenu();
MenuItem showItem = new MenuItem("顯示視窗");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(true);
setExtendedState(Frame.NORMAL);
SystemTray.getSystemTray().remove(trayIcon);
}
};
showItem.addActionListener(listener);
popup.add(showItem);
MenuItem exitItem = new MenuItem("退出");
exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SystemTray.getSystemTray().remove(trayIcon);
System.exit(0);
}
});
popup.add(exitItem);
// 依圖示、提示文字、選單建立 TrayIcon
this.trayIcon = new TrayIcon(Icon.icon16.getImage(), "番茄時間管理", popup);
this.trayIcon.addActionListener(listener);
}
public void minimizeToTray() {
SystemTray tray = SystemTray.getSystemTray();
try {
tray.add(this.trayIcon);
} catch (AWTException ex) {
ex.printStackTrace();
}
}
使用 Timer 搭配 TimerTask:每秒觸發一次,減去剩餘秒數並更新顯示,歸零時響鈴並進入休息階段。
用多層 JPanel 嵌套搭配 BorderLayout,三個按鈕(開始/暫停/重設)放在使用 CardLayout 的面板中切換顯示。
-Dfile.encoding=GB18030(或 UTF-8)即可。setDefaultCloseOperation 的替代處理。tray.add() 同一個圖示兩次會拋 AWTException,切換顯示/最小化時要記得先 remove。