//使用Swing組件顯示一個整數的個、十、百位數字。
//使用JOptionPane消息框作爲對話框。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DigitJFrame extends JFrame implements ActionListener
{
private JTextField texts[];
public DigitJFrame()
{
super("顯示整數的各位數字");
this.setBounds(400,400,160,140);
this.setResizable(false); //窗口大小不能改變
this.setColor.lightGray);< /p>
this.setDefaultCloseOperation(EXIT_ON_CLOSE); //單擊窗口關閉按鈕時,結束程序運行
this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT)); //流佈局且左對齊
String labelstr[]={"整數","百位","十位","個位"};
texts = new JTextField[labelstr.length];
for (int i=0; i<texts.length; i++)
{
this.getContentPane().add(new JLabel(labelstr[i]));
texts[i] = new JTextField(10);
texts[i].setEditable(false); //只能顯示,不允許編輯
this.getContentPane().add(texts[i]);
}
texts[0].setEditable(true); //允許編輯
texts[0].setText("123");
texts[0].addActionListener(this); //註冊單擊事件監聽器
this.actionPerformed(null);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) //文本行中單擊回車鍵
{
try
{
int i = Integer.parseInt(texts[0].getText());
texts[1].setText(""+(i / 100)); //百位
texts[2].setText(""+(i/10 % 10)); //十位
texts[3].setText(""+(i % 10)); //個位
}
catch(NumberFormatException nfe)
{
JOptionPane.showMessageDialog(this,"\""+texts[0].getText()+"\" 不能轉換成整數,請重新輸入!");
}
finally{}
}
public static void main(String arg[])
{
new DigitJFrame();
}
}