class counter extends JFrame
{
public counter()
{
super("計算器");
this.setSize(400,100);
this.setLocation(300,240);
this.setLayout(new FlowLayout()); //肯定窗口格式爲流輸入
TextField text1=new TextField(4);
text1.setText("1");
this.add(text1);
String proList[] = { "+","-","x" ,"%"}; //將"+","-","x" ,"%"做爲列表元素
TextField text;
JComboBox comboBox; //建立下拉複選框
Container conPane = getContentPane(); //建立一個名爲conPane的容器
comboBox = new JComboBox(proList); //把列表元素加入下拉複選框
comboBox.setEditable(true); //使複選框變爲可操做
conPane.add(comboBox); //將複選框加入容器中
TextField text2=new TextField(4);
text2.setText("1");
this.add(text2);
JButton button = new JButton("=");
this.add(button);
TextField text3=new TextField(4);
text3.setText("2");
button.addActionListener(new ActionListener(){ //添加按鈕監聽事件
public void actionPerformed(ActionEvent e) //建立事件響應函數
{
String s=comboBox.getEditor().getItem().toString(); //獲取複選框中的元素
double a= Integer.parseInt(text1.getText()); //將兩個文本框中的字符串強制轉換成浮點型,以便於以後的計算
double b= Integer.parseInt(text2.getText());
if(s.equals("+")) { //判斷複選框中的元素種類
double t=a+b;
String m=String.valueOf(t); //因爲文本框中的數據流只能爲字符串,這裏就須要將計算獲得的浮點型數據強制轉換成字符串型
text3.setText(m); //將最後的結果放在文本框中
}
else if(s.equals("-")) //後面的與以前的相似,不在註釋
{double t=a-b;
String m=String.valueOf(t);
text3.setText(m);}
else if(s.equals("x"))
{double t=a*b;
String m=String.valueOf(t);
text3.setText(m);}
else
{double t=a/b;
String m=String.valueOf(t);
text3.setText(m);}
}});
conPane.add(text3);
this.setVisible(true); //將窗口設置爲可視化
}
}
public class Counter {
public static void main(String[] args)
{
new counter();
}函數
}佈局
心得:this
1.在作圖形化界面設計時必定要給按鈕組件設置監聽器設計
2.應該掌握swing包和awt包中的內容,以便可以正常使用orm
3.應該設置界面的大小尺寸與佈局blog