用戶什麼都不輸入就直接按下按鈕的情況
這時再去獲得文本域的內容顯然就是一個空字元串
接下來又把空字元串轉化成數字程序就崩潰了開始拋異常
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChangeTest extends JFrame implements ActionListener {
private JButton btn1, btn2; // 定義兩個按鈕
private JTextField tf1, tf2;// 定義兩個文本框
public ChangeTest() {
setTitle("溫度轉換器");
JPanel p1 = new JPanel();
p1.add(new JLabel("華氏度"));
p1.add(tf1 = new JTextField(5));
p1.add(new JLabel("攝氏度"));
p1.add(tf2 = new JTextField(5));
JPanel p2 = new JPanel();
p2.add(btn1 = new JButton("華氏轉為攝氏"));
p2.add(btn2 = new JButton("攝氏轉為華氏"));
btn1.addActionListener(this);
btn2.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
setSize(250, 100);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// 當按鈕1被按下
if (e.getSource() == btn1) {
// 獲得攝氏度
String celsius = tf1.getText();
// 若為空則返回(什麼都不做)
if (celsius == null | celsius.equals("")) {
return;
}
// 將tf1收到的字元串轉化為數字
Float num1 = Float.parseFloat(celsius);
// 網上搜到的轉換公式
num1 = (num1 * 9 / 5) + 32;
// 顯示華氏度
tf2.setText(num1.toString());
}
// 當按鈕2被按下
if (e.getSource() == btn2) { // 同上
// 獲得華氏度
String fahrenheit = tf2.getText();
// 若為空則返回(什麼都不做)
if (fahrenheit == null | fahrenheit.equals("")) {
return;
}
// 將tf2收到的字元串轉化為數字
Float num2 = Float.parseFloat(fahrenheit);
// 轉換公式
num2 = (num2 - 32) * 5 / 9;
// 顯示攝氏度
tf1.setText(num2.toString());
}
}
public static void main(String args[]) {
new ChangeTest();
}
}
『貳』 java awt編程
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Awt extends Frame{
TextField tf = new TextField();
int year,month;
public static void main(String[] args) {
new Awt();
}
public Awt() {
setLayout(null);
setBounds(300, 200, 400, 400);
setTitle("按鍵事件");
// 設置窗口是否可變大小
setResizable(false);
setVisible(true);
//關閉窗口功能
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
tf.setBounds(40, 40, 50, 20);
//為輸入框增加事件監聽,輸入數字,敲回車響應事件
tf.addActionListener(new TfListener());
add(tf);
}
private class TfListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str = tf.getText().trim();
year = Integer.parseInt(str);
System.out.println(year);
tf.setText("");
}
}
}
上面的代碼可以給你參考,執行main方法,在輸入框中輸入數字,敲回車,數字就會傳到後台的成員變數"year"中,然後你可以做想要的操作
『叄』 Java AWT支持下的編程
/**
*
*/
package com.dianziermu.els.ui;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* 學生信息
* @author 點子二木
* @date 2009-5-20
* @version 1.0
*/
public class TestMainFrame extends JFrame {
private static final int DEFAULT_WIDTH = 600;
private static final int DEFAULT_HIGHT = 700;
/**
* @param args
*/
public static void main(String[] args) {
TestMainFrame frame = new TestMainFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TestMainFrame() {
setTitle("學生信息");
setSize(DEFAULT_WIDTH, DEFAULT_HIGHT);
////////form中加入頁面屬性//////////
JLabel lbName = new JLabel("姓名");
JTextField tfName = new JTextField(20);
JLabel lbSex = new JLabel("性別");
JRadioButton rbSex = new JRadioButton("sex");
JRadioButtonMenuItem rbmMale = new JRadioButtonMenuItem("男");
JRadioButtonMenuItem rbmFeMale = new JRadioButtonMenuItem("女");
rbSex.add(rbmMale);
rbSex.add(rbmFeMale);
JLabel lbNO = new JLabel("學號");
JTextField tfNO= new JTextField(20);
JLabel lbID = new JLabel("身份證號");
JTextField tfID= new JTextField(20);
JLabel lbRemark = new JLabel("備注");
JTextArea tfRemark= new JTextArea(20,30);
JButton btnNew = new JButton("新增");
JButton btnExit = new JButton("取消");
Panel panel = new Panel();
panel.add(lbName);
panel.add(tfName);
panel.add(lbSex);
panel.add(rbSex);
panel.add(lbNO);
panel.add(tfNO);
panel.add(lbID);
panel.add(tfID);
panel.add(lbRemark);
panel.add(tfRemark);
panel.add(btnNew);
panel.add(btnExit);
add(panel);
}
}
class Panel extends JPanel {
}
『肆』 求大神利用Java AWT組件編寫一個如下圖的程序,要求能求正方形或者長方形的面積,布局要類型
按照你的要求,用Java AWT組件編寫的Java程序如下:
importjava.awt.Button;
importjava.awt.Checkbox;
importjava.awt.CheckboxGroup;
importjava.awt.Color;
importjava.awt.Frame;
importjava.awt.Label;
importjava.awt.Panel;
importjava.awt.TextField;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.ItemEvent;
importjava.awt.event.ItemListener;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
,ItemListener{
CheckboxGroupcg=newCheckboxGroup();
Checkboxcb1=newCheckbox("正方形",true,cg);
Checkboxcb2=newCheckbox("長方形",false,cg);
Labell1=newLabel("正方形邊長");
Labell2=newLabel("長方形長");
Labell3=newLabel("長方形寬");
TextFieldtf1=newTextField(5);
TextFieldtf2=newTextField(5);
TextFieldtf3=newTextField(5);
TextFieldtfArea=newTextField(5);
Buttonb=newButton("面積");
Panelp=newPanel();
booleanflag=true;
AFC(){
super("求面積");
p.setBackground(Color.CYAN);
b.setBackground(Color.RED);
p.setLayout(null);
cb1.setBounds(20,5,100,30);
cb2.setBounds(150,5,100,30);
l1.setBounds(20,50,100,30);
tf1.setBounds(150,50,100,30);
b.setBounds(20,100,80,30);
tfArea.setBounds(150,100,100,30);
b.addActionListener(this);
cb1.addItemListener(this);
cb2.addItemListener(this);
p.add(cb1);p.add(cb2);
p.add(l1);p.add(tf1);
p.add(b);p.add(tfArea);
add(p);
setSize(300,250);
addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEventwe){
System.exit(0);
}});
setVisible(true);
}
@Override
publicvoiditemStateChanged(ItemEventie){
if(ie.getStateChange()==ItemEvent.SELECTED){
if(ie.getItem().equals("正方形")){
p.remove(l2);
p.remove(tf2);
p.remove(l3);
p.remove(tf3);
l1.setBounds(20,50,100,30);
tf1.setBounds(150,50,100,30);
b.setBounds(20,100,80,30);
tfArea.setBounds(150,100,100,30);
tf1.setText("");
tfArea.setText("");
p.add(l1);
p.add(tf1);
p.validate();
flag=true;
}
if(ie.getItem().equals("長方形")){
p.remove(l1);
p.remove(tf1);
l2.setBounds(20,50,100,30);
tf2.setBounds(150,50,100,30);
l3.setBounds(20,100,100,30);
tf3.setBounds(150,100,100,30);
b.setBounds(20,150,80,30);
tfArea.setBounds(150,150,100,30);
tf2.setText("");
tf3.setText("");
tfArea.setText("");
p.add(l2);
p.add(tf2);
p.add(l3);
p.add(tf3);
p.validate();
flag=false;
}
}
}
@Override
publicvoidactionPerformed(ActionEventae){
if(ae.getSource()==b){
if(flag==true){
doubled=Double.parseDouble(tf1.getText().trim());
tfArea.setText(String.valueOf(d*d));
}else{
doubled1=Double.parseDouble(tf2.getText().trim());
doubled2=Double.parseDouble(tf3.getText().trim());
tfArea.setText(String.valueOf(d1*d2));
}
}
}
publicstaticvoidmain(String[]args){
newAFC();
}
}
運行結果:
『伍』 如何運行java的awt寫的程序
這個也太簡單了,你寫一個main方法,
public static void main(String args[]){
//這里寫你的awt類的程序
}
然後把你寫的awt類的程序放到mian方法裡面,
然後點擊右鍵--》run as-->Java Application 就OK了
『陸』 java.awt 程序
你是怎麼運行的
是在命令提示行里javac ...編譯後 java...的么?
可以運行啊 沒問題 要不是你沒編譯 要不是你的classpath沒設好?
前面有.么 如果有 重起下 在打java led 就應該可以吧
『柒』 java中如何用AWT組件來設計實現計算器程序
package book.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* 一個計算器,與Windows附件自帶計算器的標准版功能、界面相仿。
* 但還不支持鍵盤操作。
*/
public class Calculator extends JFrame implements ActionListener {
/** 計算器上的鍵的顯示名字 */
private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6",
"*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
/** 計算器上的功能鍵的顯示名字 */
private final String[] COMMAND = { "Backspace", "CE", "C" };
/** 計算器左邊的M的顯示名字 */
private final String[] M = { " ", "MC", "MR", "MS", "M+" };
/** 計算器上鍵的按鈕 */
private JButton keys[] = new JButton[KEYS.length];
/** 計算器上的功能鍵的按鈕 */
private JButton commands[] = new JButton[COMMAND.length];
/** 計算器左邊的M的按鈕 */
private JButton m[] = new JButton[M.length];
/** 計算結果文本框 */
private JTextField resultText = new JTextField("0");
// 標志用戶按的是否是整個表達式的第一個數字,或者是運算符後的第一個數字
private boolean firstDigit = true;
// 計算的中間結果。
private double resultNum = 0.0;
// 當前運算的運算符
private String operator = "=";
// 操作是否合法
private boolean operateValidFlag = true;
/**
* 構造函數
*/
public Calculator(){
super();
//初始化計算器
init();
//設置計算器的背景顏色
this.setBackground(Color.LIGHT_GRAY);
this.setTitle("計算器");
//在屏幕(500, 300)坐標處顯示計算器
this.setLocation(500, 300);
//不許修改計算器的大小
this.setResizable(false);
//使計算器中各組件大小合適
this.pack();
}
/**
* 初始化計算器
*/
private void init() {
// 文本框中的內容採用右對齊方式
resultText.setHorizontalAlignment(JTextField.RIGHT);
// 不允許修改結果文本框
resultText.setEditable(false);
// 設置文本框背景顏色為白色
resultText.setBackground(Color.WHITE);
//初始化計算器上鍵的按鈕,將鍵放在一個畫板內
JPanel calckeysPanel = new JPanel();
//用網格布局器,4行,5列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
calckeysPanel.setLayout(new GridLayout(4, 5, 3, 3));
for (int i = 0; i < KEYS.length; i++) {
keys[i] = new JButton(KEYS[i]);
calckeysPanel.add(keys[i]);
keys[i].setForeground(Color.blue);
}
//運算符鍵用紅色標示,其他鍵用藍色表示
keys[3].setForeground(Color.red);
keys[8].setForeground(Color.red);
keys[13].setForeground(Color.red);
keys[18].setForeground(Color.red);
keys[19].setForeground(Color.red);
//初始化功能鍵,都用紅色標示。將功能鍵放在一個畫板內
JPanel commandsPanel = new JPanel();
//用網格布局器,1行,3列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
commandsPanel.setLayout(new GridLayout(1, 3, 3, 3));
for (int i = 0; i < COMMAND.length; i++) {
commands[i] = new JButton(COMMAND[i]);
commandsPanel.add(commands[i]);
commands[i].setForeground(Color.red);
}
//初始化M鍵,用紅色標示,將M鍵放在一個畫板內
JPanel calmsPanel = new JPanel();
//用網格布局管理器,5行,1列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
calmsPanel.setLayout(new GridLayout(5, 1, 3, 3));
for (int i = 0; i < M.length; i++) {
m[i] = new JButton(M[i]);
calmsPanel.add(m[i]);
m[i].setForeground(Color.red);
}
//下面進行計算器的整體布局,將calckeys和command畫板放在計算器的中部,
//將文本框放在北部,將calms畫板放在計算器的西部。
//新建一個大的畫板,將上面建立的command和calckeys畫板放在該畫板內
JPanel panel1 = new JPanel();
//畫板採用邊界布局管理器,畫板里組件之間的水平和垂直方向上間隔都為3象素
panel1.setLayout(new BorderLayout(3, 3));
panel1.add("North", commandsPanel);
panel1.add("Center", calckeysPanel);
//建立一個畫板放文本框
JPanel top = new JPanel();
top.setLayout(new BorderLayout());
top.add("Center", resultText);
//整體布局
getContentPane().setLayout(new BorderLayout(3, 5));
getContentPane().add("North", top);
getContentPane().add("Center", panel1);
getContentPane().add("West", calmsPanel);
//為各按鈕添加事件偵聽器
//都使用同一個事件偵聽器,即本對象。本類的聲明中有implements ActionListener
for (int i = 0; i < KEYS.length; i++) {
keys[i].addActionListener(this);
}
for (int i = 0; i < COMMAND.length; i++) {
commands[i].addActionListener(this);
}
for (int i = 0; i < M.length; i++) {
m[i].addActionListener(this);
}
}
/**
* 處理事件
*/
public void actionPerformed(ActionEvent e) {
//獲取事件源的標簽
String label = e.getActionCommand();
if (label.equals(COMMAND[0])){
//用戶按了"Backspace"鍵
handleBackspace();
} else if (label.equals(COMMAND[1])) {
//用戶按了"CE"鍵
resultText.setText("0");
} else if (label.equals(COMMAND[2])){
//用戶按了"C"鍵
handleC();
} else if ("0123456789.".indexOf(label) >= 0) {
//用戶按了數字鍵或者小數點鍵
handleNumber(label);
// handlezero(zero);
} else {
//用戶按了運算符鍵
handleOperator(label);
}
}
/**
* 處理Backspace鍵被按下的事件
*/
private void handleBackspace() {
String text = resultText.getText();
int i = text.length();
if (i > 0) {
//退格,將文本最後一個字元去掉
text = text.substring(0, i - 1);
if (text.length() == 0) {
//如果文本沒有了內容,則初始化計算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
} else {
//顯示新的文本
resultText.setText(text);
}
}
}
/**
* 處理數字鍵被按下的事件
* @param key
*/
private void handleNumber(String key) {
if (firstDigit) {
//輸入的第一個數字
resultText.setText(key);
} else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0)){
//輸入的是小數點,並且之前沒有小數點,則將小數點附在結果文本框的後面
resultText.setText(resultText.getText() + ".");
} else if (!key.equals(".")) {
//如果輸入的不是小數點,則將數字附在結果文本框的後面
resultText.setText(resultText.getText() + key);
}
//以後輸入的肯定不是第一個數字了
firstDigit = false;
}
/**
* 處理C鍵被按下的事件
*/
private void handleC() {
//初始化計算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
}
/**
* 處理運算符鍵被按下的事件
* @param key
*/
private void handleOperator(String key) {
if (operator.equals("/")) {
//除法運算
//如果當前結果文本框中的值等於0
if (getNumberFromText() == 0.0){
//操作不合法
operateValidFlag = false;
resultText.setText("除數不能為零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("1/x")) {
//倒數運算
if (resultNum == 0.0){
//操作不合法
operateValidFlag = false;
resultText.setText("零沒有倒數");
} else {
resultNum = 1 / resultNum;
}
} else if (operator.equals("+")){
//加法運算
resultNum += getNumberFromText();
} else if (operator.equals("-")){
//減法運算
resultNum -= getNumberFromText();
} else if (operator.equals("*")){
//乘法運算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
//平方根運算
resultNum = Math.sqrt(resultNum);
} else if (operator.equals("%")){
//百分號運算,除以100
resultNum = resultNum / 100;
} else if (operator.equals("+/-")){
//正數負數運算
resultNum = resultNum * (-1);
} else if (operator.equals("=")){
//賦值運算
resultNum = getNumberFromText();
}
if (operateValidFlag) {
//雙精度浮點數的運算
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
resultText.setText(String.valueOf(t1));
} else {
resultText.setText(String.valueOf(resultNum));
}
}
//運算符等於用戶按的按鈕
operator = key;
firstDigit = true;
operateValidFlag = true;
}
/**
* 從結果文本框中獲取數字
* @return
*/
private double getNumberFromText() {
double result = 0;
try {
result = Double.valueOf(resultText.getText()).doubleValue();
} catch (NumberFormatException e){
}
return result;
}
public static void main(String args[]) {
Calculator calculator1 = new Calculator();
calculator1.setVisible(true);
calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package book.gui;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.;
import javax.swing.plaf.metal.MetalLookAndFeel;
import com.sun.java.swing.plaf.motif.MotifLookAndFeel;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
/**
* 更改窗體、組件的外觀
*/
public class LookAndFeel {
public static void main(String[] args) {
/**
* Metal風格——"javax.swing.plaf.metal.MetalLookAndFeel"
* Motif風格——"com.sun.java.swing.plaf.motif.MotifLookAndFeel"
* Windows風格——"com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
*/
Calculator calculator1 = new Calculator();
calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//3個不同的風格
/**
* LookAndFeel是一個抽象類,除了提供了一些static方法,還定義了一些抽象的個性化設置方法來由子類實現。
從JDK1.1.3開始,Sun提供了三個LookAndFeel的子類
*/
String lnfName = "javax.swing.plaf.metal.MetalLookAndFeel";
// String lnfName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
// String lnfName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
try {
// UIManager負責跟蹤當前的外觀及其默認設置,setLookAndFeel方法將設置它的LookAndFeel的類全名
UIManager.setLookAndFeel(lnfName);
// setLookAndFeel還可以直接設置設置對象
UIManager.setLookAndFeel(new MetalLookAndFeel());
// UIManager.setLookAndFeel(new MotifLookAndFeel());
// UIManager.setLookAndFeel(new WindowsLookAndFeel());
//SwingUtilities是一個Swing的工具類,提供了很多靜態方法。
//updateComponentTreeUI將更新calculator1中所有組件的外觀
SwingUtilities.updateComponentTreeUI(calculator1);
}
catch ( ex1) {
System.err.println("Unsupported LookAndFeel: " + lnfName);
}
catch (ClassNotFoundException ex2) {
System.err.println("LookAndFeel class not found: " + lnfName);
}
catch (InstantiationException ex3) {
System.err.println("Could not load LookAndFeel: " + lnfName);
}
catch (IllegalAccessException ex4) {
System.err.println("Cannot use LookAndFeel: " + lnfName);
}
calculator1.setVisible(true);
}
}
『捌』 第一次提問求助~JAVA語言編程,AWT組件,謝謝各位大神~
這個你可以湊合著用了。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.Panel;
import java.awt.TextArea;
public class Student extends Frame {
public Student() {
final Checkbox cbReg = new Checkbox("注冊");
final CheckboxGroup cbgSex = new CheckboxGroup();
Checkbox cbBoy = new Checkbox("男", cbgSex, true);
Checkbox cbGirl = new Checkbox("女", cbgSex, false);
final List grade = new List();
grade.add("一年級");
grade.add("二年級");
grade.add("三年級");
grade.add("四年級");
grade.select(0);
final Choice xi = new Choice();
xi.add("數學系");
xi.add("計算機系");
final TextArea info = new TextArea();
Button btn = new Button("確定");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = "";
if (cbReg.getState()) {
str = "已注冊\n";
} else {
str = "未注冊\n";
}
// 性別
str += cbgSex.getSelectedCheckbox().getLabel() + "\n";
// 系別
str += xi.getSelectedItem() + "\n";
// 年級
str += grade.getSelectedItem() + "\n";
info.setText(str);
}
});
Panel main = new Panel(new BorderLayout());
Panel top = new Panel(new GridLayout(1, 5));
top.add(cbReg);
top.add(cbBoy);
top.add(cbGirl);
top.add(xi);
top.add(grade);
top.add(btn);
main.add(top, BorderLayout.NORTH);
main.add(info, BorderLayout.CENTER);
add(main);
setSize(500, 500);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new Student().setVisible(true);
}
}
『玖』 JAVA編程題(AWT計算器)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.LinkedList; //工具包
import java.text.NumberFormat; //文本包
public class Calculator extends Frame implements ActionListener //計算器類
{
JTextField result;
NumberButton numberButton[];
OperatorButton operatorButton[];
Button radixpoint,positiveminus,backspace,reciprocal,equal,clear; //聲明成員變數
//小數點按鈕,正負號按鈕,退格按鈕,求倒數按鈕,等號按鈕,清零按鈕
Panel panel;
String operator[]={"+","-","*","/"};
LinkedList linklist;
boolean pressequal=false;
public Calculator() //構造方法
{
super("計算器");
linklist=new LinkedList();
numberButton=new NumberButton[10];
for(int i=0;i<=9;i++)
{
numberButton[i]=new NumberButton(i);
numberButton[i].addActionListener(this);
}
operatorButton=new OperatorButton[4];
for(int i=0;i<4;i++)
{
operatorButton[i]=new OperatorButton(operator[i]);
operatorButton[i].addActionListener(this);
}
radixpoint=new Button(".");
positiveminus=new Button("+/-");
backspace=new Button("CE");
reciprocal=new Button("1/x");
equal=new Button("=");
clear=new Button("C");
radixpoint.setForeground(Color.red);
positiveminus.setForeground(Color.red);
backspace.setForeground(Color.red);
reciprocal.setForeground(Color.red);
equal.setForeground(Color.red);
clear.setForeground(Color.red);
radixpoint.addActionListener(this);
positiveminus.addActionListener(this);
backspace.addActionListener(this);
reciprocal.addActionListener(this);
equal.addActionListener(this);
clear.addActionListener(this);
result=new JTextField(10);
result.setHorizontalAlignment(JTextField.RIGHT);
result.setForeground(Color.black);
result.setBackground(Color.white);
result.setFont(new Font("TimesRoman",Font.PLAIN,14));
result.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
result.setEditable(false);
panel=new Panel();
panel.setLayout(new GridLayout(4,5));
panel.add(numberButton[1]);
panel.add(numberButton[2]);
panel.add(numberButton[3]);
panel.add(backspace);
panel.add(clear);
panel.add(numberButton[4]);
panel.add(numberButton[5]);
panel.add(numberButton[6]);
panel.add(operatorButton[0]);
panel.add(operatorButton[2]);
panel.add(numberButton[7]);
panel.add(numberButton[8]);
panel.add(numberButton[9]);
panel.add(operatorButton[1]);
panel.add(operatorButton[3]);
panel.add(numberButton[0]);
panel.add(positiveminus);
panel.add(reciprocal);
panel.add(radixpoint);
panel.add(equal);
add(result,"North");
add(panel,"Center");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setSize(270,200);
setLocation(300,230);
setVisible(true);
}
public void actionPerformed(ActionEvent e) //按鈕的單擊事件處理方法
{
if(e.getSource() instanceof NumberButton) //數字按鈕
{
NumberButton b=(NumberButton)e.getSource();
if(linklist.size()==0)
{
int number=b.getNumber();
linklist.add(""+number);
result.setText(""+number);
pressequal=false;
}
else if(linklist.size()==1&&pressequal==false)
{
int number=b.getNumber();
String num=(String)linklist.getFirst();
String s=num.concat(""+number);
linklist.set(0,s);
result.setText(s);
}
else if(linklist.size()==1&&pressequal==true)
{
int number=b.getNumber();
linklist.removeFirst();
linklist.add(""+number);
pressequal=false;
result.setText(""+number);
}
else if(linklist.size()==2)
{
int number=b.getNumber();
linklist.add(""+number);
result.setText(""+number);
}
else if(linklist.size()==3)
{
int number=b.getNumber();
String num=(String)linklist.getLast();
String s=num.concat(""+number);
linklist.set(2,s);
result.setText(s);
}
}
else if(e.getSource() instanceof OperatorButton) //操作按鈕
{
OperatorButton b=(OperatorButton)e.getSource();
if(linklist.size()==1)
{
String fuhao=b.getOperator();
linklist.add(fuhao);
}
else if(linklist.size()==2)
{
String fuhao=b.getOperator();
linklist.set(1,fuhao);
}
else if(linklist.size()==3)
{
String fuhao=b.getOperator();
String number1=(String)linklist.getFirst();
String number2=(String)linklist.getLast();
String operator=(String)linklist.get(1);
try
{
double n1=Double.parseDouble(number1);
double n2=Double.parseDouble(number2);
double n=0;
if(operator.equals("+"))
{
n=n1+n2;
}
else if(operator.equals("-"))
{
n=n1-n2;
}
else if(operator.equals("*"))
{
n=n1*n2;
}
else if(operator.equals("/"))
{
n=n1/n2;
}
linklist.clear();
linklist.add(""+n);
linklist.add(fuhao);
result.setText(""+n);
}
catch(Exception ee)
{
}
}
}
else if(e.getSource()==equal) //等號按鈕
{
pressequal=true;
if(linklist.size()==1||linklist.size()==2)
{
String num=(String)linklist.getFirst();
result.setText(""+num);
}
else if(linklist.size()==3)
{
String number1=(String)linklist.getFirst();
String number2=(String)linklist.getLast();
String operator=(String)linklist.get(1);
try
{
double n1=Double.parseDouble(number1);
double n2=Double.parseDouble(number2);
double n=0;
if(operator.equals("+"))
{
n=n1+n2;
}
else if(operator.equals("-"))
{
n=n1-n2;
}
else if(operator.equals("*"))
{
n=n1*n2;
}
else if(operator.equals("/"))
{
n=n1/n2;
}
result.setText(""+n);
linklist.set(0,""+n);
linklist.removeLast();
linklist.removeLast();
}
catch(Exception ee)
{
}
}
}
else if(e.getSource()==radixpoint) //小數點按鈕
{
if(linklist.size()==0)
{
pressequal=false;
}
else if(linklist.size()==1)
{
String dot=radixpoint.getLabel();
String num=(String)linklist.getFirst();
String s=null;
if(num.indexOf(dot)==-1)
{
s=num.concat(dot);
linklist.set(0,s);
}
else
{
s=num;
}
linklist.set(0,s);
result.setText(s);
}
else if(linklist.size()==3)
{
String dot=radixpoint.getLabel();
String num=(String)linklist.getLast();
String s=null;
if(num.indexOf(dot)==-1)
{
s=num.concat(dot);
linklist.set(2,s);
}
else
{
s=num;
}
result.setText(s);
}
}
else if(e.getSource()==backspace) //退格按鈕
{
if(linklist.size()==1)
{
String num=(String)linklist.getFirst();
if(num.length()>=1)
{
num=num.substring(0,num.length()-1);
linklist.set(0,num);
result.setText(num);
}
else
{
linklist.removeLast();
result.setText("0");
}
}
else if(linklist.size()==3)
{
String num=(String)linklist.getLast();
if(num.length()>=1)
{
num=num.substring(0,num.length()-1);
linklist.set(2,num);
result.setText(num);
}
else
{
linklist.removeLast();
result.setText("0");
}
}
}
else if(e.getSource()==positiveminus) //正負號按鈕
{
if(linklist.size()==1)
{
String number1=(String)linklist.getFirst();
try
{
double d=Double.parseDouble(number1);
d=-1*d;
String str=String.valueOf(d);
linklist.set(0,str);
result.setText(str);
}
catch(Exception ee)
{
}
}
else if(linklist.size()==3)
{
String number2=(String)linklist.getLast();
try
{
double d=Double.parseDouble(number2);
d=-1*d;
String str=String.valueOf(d);
linklist.set(2,str);
result.setText(str);
}
catch(Exception ee)
{
}
}
}
else if(e.getSource()==reciprocal) //求倒數按鈕
{
if(linklist.size()==1||linklist.size()==2)
{
String number1=(String)linklist.getFirst();
try
{
double d=Double.parseDouble(number1);
d=1.0/d;
String str=String.valueOf(d);
linklist.set(0,str);
result.setText(str);
}
catch(Exception ee)
{
}
}
else if(linklist.size()==3)
{
String number2=(String)linklist.getLast();
try
{
double d=Double.parseDouble(number2);
d=1.0/d;
String str=String.valueOf(d);
linklist.set(0,str);
result.setText(str);
}
catch(Exception ee)
{
}
}
}
else if(e.getSource()==clear) //清零按鈕
{
pressequal=false;
result.setText("0");
linklist.clear();
}
}
public static void main(String args[])
{
new Calculator();
}
}
class NumberButton extends Button //數字按鈕類
{
int number;
public NumberButton(int number) //構造方法
{
super(""+number);
this.number=number;
setForeground(Color.blue);
}
public int getNumber()
{
return number;
}
}
class OperatorButton extends Button //運算符號按鈕類
{
String operator;
public OperatorButton(String operator) //構造方法
{
super(operator);
this.operator=operator;
setForeground(Color.red);
}
public String getOperator()
{
return operator;
}
}
『拾』 在java中用awt編寫一個計算器
我也是轉來的 共同學習
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame
{
private Container container;
private GridBagLayout layout;
private GridBagConstraints constraints;
private JTextField displayField;//計算結果顯示區
private String lastCommand;//保存+,-,*,/,=命令
private double result;//保存計算結果
private boolean start;//判斷是否為數字的開始
public Calculator()
{
super("Calculator");
container=getContentPane();
layout=new GridBagLayout();
container.setLayout(layout);
constraints=new GridBagConstraints();
start=true;
result=0;
lastCommand = "=";
displayField=new JTextField(20);
displayField.setHorizontalAlignment(JTextField.RIGHT);
constraints.gridx=0;
constraints.gridy=0;
constraints.gridwidth=4;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.BOTH;
constraints.weightx=100;
constraints.weighty=100;
layout.setConstraints(displayField,constraints);
container.add(displayField);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
addButton("Backspace",0,1,2,1,insert);
addButton("CE",2,1,1,1,insert);
addButton("C",3,1,1,1,insert);
addButton("7",0,2,1,1,insert);
addButton("8",1,2,1,1,insert);
addButton("9",2,2,1,1,insert);
addButton("/",3,2,1,1,command);
addButton("4",0,3,1,1,insert);
addButton("5",1,3,1,1,insert);
addButton("6",2,3,1,1,insert);
addButton("*",3,3,1,1,command);
addButton("1",0,4,1,1,insert);
addButton("2",1,4,1,1,insert);
addButton("3",2,4,1,1,insert);
addButton("-",3,4,1,1,command);
addButton("0",0,5,1,1,insert);
addButton("+/-",1,5,1,1,insert);//只顯示"-"號,"+"沒有實用價值
addButton(".",2,5,1,1,insert);
addButton("+",3,5,1,1,command);
addButton("=",0,6,4,1,command);
setSize(300,300);
setVisible(true);
}
private void addButton(String label,int row,int column,int with,int height,ActionListener listener)
{
JButton button=new JButton(label);
constraints.gridx=row;
constraints.gridy=column;
constraints.gridwidth=with;
constraints.gridheight=height;
constraints.fill=GridBagConstraints.BOTH;
button.addActionListener(listener);
layout.setConstraints(button,constraints);
container.add(button);
}
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input=event.getActionCommand();
if (start)
{
displayField.setText("");
start=false;
if(input.equals("+/-"))
displayField.setText(displayField.getText()+"-");
}
if(!input.equals("+/-"))
{
if(input.equals("Backspace"))
{
String str=displayField.getText();
if(str.length()>0)
displayField.setText(str.substring(0,str.length()-1));
}
else if(input.equals("CE")||input.equals("C"))
{
displayField.setText("0");
start=true;
}
else
displayField.setText(displayField.getText()+input);
}
}
}
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
String command=evt.getActionCommand();
if(start)
{
lastCommand=command;
}
else
{
calculate(Double.parseDouble(displayField.getText()));
lastCommand=command;
start=true;
}
}
}
public void calculate(double x)
{
if (lastCommand.equals("+")) result+= x;
else if (lastCommand.equals("-")) result-=x;
else if (lastCommand.equals("*")) result*=x;
else if (lastCommand.equals("/")) result/=x;
else if (lastCommand.equals("=")) result=x;
displayField.setText(""+ result);
}
public static void main(String []args)
{
Calculator calculator=new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}