用户什么都不输入就直接按下按钮的情况
这时再去获得文本域的内容显然就是一个空字符串
接下来又把空字符串转化成数字程序就崩溃了开始抛异常
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);
}
}