这星期编了一个界面,“小闹钟”。以下是基本组件的编程实现。
package 小闹钟;
import java.awt.Component; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.Date; import java.util.Formatter;
import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField;
public class AlarmClock { private Date today; private JLabel Label[]; private GridBagLayout gridBag; private JFrame jfrmMain; private Container con; private JLabel intervalRadio; private JCheckBox chkBox; private JTextField minuteText,timeText; private JButton jbutOK, jbutCancel;
/*设置字符串,元素为界面显示的组件名称*/ private final String msg[] = { "当前时间","","订于","分钟后","订于","提醒","现在还差","0秒" };
/*设置函数将目标组obj件加入容器c*/ private void addComponents(Component obj, GridBagConstraints c) { gridBag.setConstraints(obj,c); con.add(obj); }
/*函数实现将时间类型编程字符串类型*/ private String TimeToString(Date day) { Formatter fmt = new Formatter(); fmt.format("%tT",day); return fmt.toString(); } public AlarmClock() { initAlarmClock(); }
/*函数实现所有界面初始化*/ private void initAlarmClock() { int i; today = new Date(); jfrmMain = new JFrame("小闹钟"); gridBag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; con = jfrmMain.getContentPane(); con.setLayout(gridBag); jfrmMain.setSize(400, 400); Label = new JLabel[msg.length]; for(i = 0; i < Label.length; i++) Label[i] = new JLabel(msg[i], JLabel.CENTER); c.gridwidth = 1; c.gridheight = 2; c.insets = new Insets(0 , 0, 5, 0); addComponents(Label[0],c);
c.gridwidth = GridBagConstraints.REMAINDER; Label[1].setText(TimeToString(today)); addComponents(Label[1],c); c.gridwidth = 1; intervalRadio = new JLabel("间隔时间"); addComponents(intervalRadio,c); addComponents(Label[2],c); minuteText = new JTextField("10",6); addComponents(minuteText,c); c.gridwidth = GridBagConstraints.REMAINDER; addComponents(Label[3], c); c.gridwidth = 1; addComponents(Label[6],c); c.gridwidth = GridBagConstraints.REMAINDER; addComponents(Label[7], c); c.gridwidth = 1; chkBox = new JCheckBox("蹦出来", true); addComponents(chkBox, c); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); jbutOK = new JButton("确定"); jbutCancel = new JButton("取消"); panel.add(jbutOK); panel.add(jbutCancel); c.gridwidth = GridBagConstraints.REMAINDER; addComponents(panel, c); jfrmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfrmMain.setVisible(true); } public static void main(String[] args) { new AlarmClock(); }
}
以上只完成了界面整个组件的创建,没有时间事件编程,真正的功能实现方法我还在思考中。
界面效果图如下: