首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

只用AWT制作计算器,不许使用swing?该怎么处理

2012-02-03 
只用AWT制作计算器,不许使用swing?我们老师布置了一个小项目——不许使用swing,只能用AWT制作计算器。对于jav

只用AWT制作计算器,不许使用swing?
我们老师布置了一个小项目——不许使用swing,只能用AWT制作计算器。对于java菜鸟的我,这样做起来还真有点困难,那个+、-、*、/ 事件源我不会……请大家帮忙讨论一下!!

[解决办法]
怎么找不到?四个按钮对象的值属性分别是加减乘除,都加到同一个事件监听里,然后捕获到事件后判断事件源的值属性是什么,最后再来做计算器
[解决办法]
事件都在awt包里
Swing和AWT没有什么区别

不过话说回来,你们老师还是真的牛啊
非要你们用一个已经过时的,被官方抛弃掉的awt去做东西
[解决办法]

[解决办法]
这是我大一时做的,基本上都是用awt做的,楼主觉得哪有不好,自己在修饰一下就好

Java code
import java.awt.BorderLayout;import java.awt.Color;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.Insets;import java.awt.Menu;import java.awt.MenuBar;import java.awt.MenuItem;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;public class Mycalculator extends JFrame{    private String[] names = { "退格", "CE", "C", "/", "7", "8", "9", "*", "4",            "5", "6", "-", "1", "2", "3", "+", "0", "+/-", ".", "=" };    private JButton[] jb = new JButton[names.length];    private double x = 0d;    private double y = 0d;    private int z;// 作为运算符的选择    StringBuffer str;    JPanel p;    JPanel p1;    JTextField jt;    MenuItem mi;    public Mycalculator()    {        super("Followme_1987");        MenuBar mb = new MenuBar();// 设置菜单栏        setMenuBar(mb);        Menu me = new Menu("编辑");        Menu me1 = new Menu("关于");        Menu me2 = new Menu("帮助");        mi = new MenuItem("请点我");        mi.addActionListener(new Mc());        me1.add(mi);        mb.add(me);        mb.add(me1);        mb.add(me2);        jt = new JTextField(19);// 创建文本框 用于显示        jt.setHorizontalAlignment(JTextField.RIGHT);        jt.setText("0.");        jt.setEditable(false);        p = new JPanel(); // 创建一块板儿 并将文本框加入        p.setBounds(8, 2, 220, 30);        p.setLayout(new FlowLayout(FlowLayout.LEFT));        p.add(jt);        p1 = new JPanel(); // 创建另一块儿板儿        p1.setLayout(new GridLayout(5, 4, 5, 5));        p1.setBounds(13, 35, 210, 140);        jt.setBackground(Color.getHSBColor(23, 25, 125));        for (int i = 0; i < jb.length; i++)        { // 加入按钮            jb[i] = new JButton(names[i]);            jb[i].setMargin(new Insets(4, 1, 4, 1));            p1.add(jb[i]);            if (i == 1 || i == 2 || i == 0)            {                jb[i].setForeground(Color.BLUE);            }            else if (i == 3 || i == 7 || i == 11 || i == 15)            {                jb[i].setForeground(Color.RED);            }            else if (i == 19)            {                jb[i].setForeground(Color.YELLOW);                jb[i].setBackground(Color.RED);            }            else            {                jb[i].setBackground(Color.DARK_GRAY);                jb[i].setForeground(Color.YELLOW);            }            jb[i].addActionListener(new Mc());        }// 以上颜色带给人 轻松的感觉 避免视觉疲劳        setLayout(null);        add(p1);        add(p);        str = new StringBuffer();    }    /**     * @param args     */    public static void main(String[] args)    {        // TODO Auto-generated method stub        Mycalculator frame = new Mycalculator();        frame.setBounds(400, 200, 240, 230);        // frame.setLocationRelativeTo(null);        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);        frame.setVisible(true);        frame.setResizable(false);    }    public class Mc implements ActionListener    {        public void actionPerformed(ActionEvent e)        {            if (e.getSource() == mi)            {                JOptionPane.showMessageDialog(null, "楼主要记得结贴......");            }            if (e.getSource() == jb[0])            { // 按下退格键                if (!jt.getText().trim().equals("0."))                {                    if (str.length() != 1)                    {                        jt.setText(str.delete(str.length() - 1, str.length())                                .toString());                    }                    else                    {                        jt.setText("0.");                        str.setLength(0);                    }                    y = Double.parseDouble(jt.getText().trim());                }            }            else if (e.getSource() == jb[1] || e.getSource() == jb[2])            { // 按下CE键或者C键                jt.setText("0.");                str.setLength(0);                x = 0d;                y = 0d;                z = 0;            }            else if (e.getSource() == jb[3])            { // 按下除号键 并且设置z=1                x = Double.parseDouble(jt.getText().trim());                str.setLength(0);                y = 0d;                z = 1;            }            else if (e.getSource() == jb[7])            { // 按下乘号键并且设置z=2                x = Double.parseDouble(jt.getText().trim());                str.setLength(0);                y = 0d;                z = 2;            }            else if (e.getSource() == jb[11])            { // 按下减号键并且设置z=3                x = Double.parseDouble(jt.getText().trim());                str.setLength(0);                y = 0d;                z = 3;            }            else if (e.getSource() == jb[15])            { // 按下加号键并且设置z=4                x = Double.parseDouble(jt.getText().trim());                str.setLength(0);                y = 0d;                z = 4;            }            else if (e.getSource() == jb[19])            { // 按下=号键                str.setLength(0);                switch (z)                {                case 1:                    jt.setText("" + (x / y));                    break;                case 2:                    jt.setText("" + (x * y));                    break;                case 3:                    jt.setText("" + (x - y));                    break;                case 4:                    jt.setText("" + (x + y));                    break;                }            }            else if (e.getSource() == jb[17])            { // 按下+/-                if (jt.getText().trim().equals("0."))                {                }                else                {                    // x = Double.parseDouble(jt.getText().trim());                    // jt.setText("" + (-x));                    if (jt.getText().trim().startsWith("-"))                    {                        jt.setText(jt.getText().trim().substring(1));                    }                    else                    {                        jt.setText("-" + jt.getText().trim());                    }                }            }            else if (e.getSource() == jb[18])            { // 按下小数点                if (jt.getText().trim().indexOf(".") != -1)                {// 字符串中有小数点                    if (jt.getText().trim().equals("0."))                    { // 为初始状态                        str.setLength(0);                        jt.setText(str.append("0.").toString());                    }                    else                    {                    }                }                else                {                    jt.setText(str.append(e.getActionCommand()).toString());                }                y = 0d;            }            else if (e.getSource() == jb[16])            {// 按下0键                if (!jt.getText().trim().equals("0."))                {                    jt.setText(str.append(e.getActionCommand()).toString());                    y = Double.parseDouble(e.getActionCommand().trim());                }                else                {                }            }            else            {// 按下其他数字键                jt.setText(str.append(e.getActionCommand()).toString());                y = Double.parseDouble(jt.getText().trim());            }        }    }} 


[解决办法]
发个CoreJava里面用Swing写的给你参考一下。个人感觉很经典
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * @version 1.33 2007-06-12
 * @author Cay Horstmann
 */
public class Calculator
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
CalculatorFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

/**
 * A frame with a calculator panel.
 */
class CalculatorFrame extends JFrame
{
public CalculatorFrame()
{
setTitle("Calculator");
CalculatorPanel panel = new CalculatorPanel();
add(panel);
pack();
}
}

/**
 * A panel with calculator buttons and a result display.
 */
class CalculatorPanel extends JPanel
{
public CalculatorPanel()
{
setLayout(new BorderLayout());

result = 0;
lastCommand = "=";
start = true;

// add the display

display = new JButton("0");
display.setEnabled(false);
add(display, BorderLayout.NORTH);

ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();

// add the buttons in a 4 x 4 grid

panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));

addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);

addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);

addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);

addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);

add(panel, BorderLayout.CENTER);
}

/**
* Adds a button to the center panel.
* @param label the button label
* @param listener the button listener
*/
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}

/**
* This action inserts the button action string to the end of the display text.
*/
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
if (start)
{
display.setText("");
start = false;
}
display.setText(display.getText() + input);
}
}

/**
* This action executes the command that the button action string denotes.
*/
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();

System.out.println(command);
if (start)
{
if (command.equals("-"))
{
System.out.println(command);
display.setText(command);
start = false;


}
else lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}
}
}

/**
* Carries out the pending calculation.
* @param x the value to be accumulated with the prior result.
*/
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;
display.setText("" + result);
}

private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}

[解决办法]
学习了
[解决办法]

Java code
 

//发个纯正awt的


import java.lang.Math.*;
import java.awt.Button;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class jisuqi extends Frame implements ActionListener, WindowListener, ItemListener {

  int i;
  double c;
  String s[] = {"Backspace", "CE", "C", "7", "8", "9", "/", "sqrt", "4", "5", "6", "*", "%", "1", "2", "3", "-", "1/x", "0", " +/-", ".", "+", "="};
  Button but[] = new Button[s.length];
  TextField t1 = new TextField("0");

  jisuqi() {
    super("计算器");
    setSize(250, 250);
    Font f;
    f = new Font("黑体", Font.BOLD, 45);
    for (int i = 0; i < s.length; i++) {
      but[i] = new Button(s[i]);
      but[i].addActionListener(this);
    }
    setLayout(new GridLayout(4, 1));
    Panel p1 = new Panel();
    p1.setLayout(new GridLayout(1, 1, 1, 1));
    p1.add(t1);
    add(p1);
    Panel p2 = new Panel();
    p2.setLayout(new GridLayout(1, 3));
    for (int i = 0; i < 3; i++) {
      p2.add(but[i]);
    }
    add(p2);
    Panel p3 = new Panel();
    p3.setLayout(new GridLayout(2, 5));
    for (int i = 3; i < 13; i++) {
      p3.add(but[i]);
    }
    add(p3);
    Panel p4 = new Panel();
    p4.setLayout(new GridLayout(2, 5));
    for (int i = 13; i < 23; i++) {
      p4.add(but[i]);
    }
    add(p4);
    addWindowListener(this);
    setVisible(true);
  }

  public void actionPerformed(ActionEvent a) {
    String s = a.getActionCommand();


    String b;
    if (s.equals("Backspace")) {
      b = t1.getText().substring(0, t1.getText().length() - 1);
      if (b.length() == 0) {
        t1.setText("0");
      }
      if (t1.getText().equals("0") || t1.getText().equals("")) {
        t1.setText("0");
      } else {
        t1.setText(b);
      }
    }
    if (s.equals("C") || s.equals("CE")) {
      t1.setText("0");
    }
    if (s.equals("0")) {
      if (t1.getText().equals("0")) {
        t1.setText("0");
      } else {
        t1.setText(t1.getText() + "0");
      }
    }
    if (s.equals("1")) {
      if (t1.getText().equals("0")) {
        t1.setText("1");
      } else {
        t1.setText(t1.getText() + "1");
      }
    }
    if (s.equals("2")) {
      if (t1.getText().equals("0")) {
        t1.setText("2");
      } else {
        t1.setText(t1.getText() + "2");
      }
    }
    if (s.equals("3")) {
      if (t1.getText().equals("0")) {
        t1.setText("3");
      } else {
        t1.setText(t1.getText() + "3");
      }
    }
    if (s.equals("4")) {
      if (t1.getText().equals("0")) {
        t1.setText("4");
      } else {
        t1.setText(t1.getText() + "4");
      }
    }
    if (s.equals("5")) {
      if (t1.getText().equals("0")) {
        t1.setText("5");
      } else {
        t1.setText(t1.getText() + "5");
      }
    }
    if (s.equals("6")) {
      if (t1.getText().equals("0")) {
        t1.setText("6");
      } else {
        t1.setText(t1.getText() + "6");
      }
    }
    if (s.equals("7")) {
      if (t1.getText().equals("0")) {
        t1.setText("7");
      } else {
        t1.setText(t1.getText() + "7");
      }
    }
    if (s.equals("8")) {
      if (t1.getText().equals("0")) {
        t1.setText("8");
      } else {
        t1.setText(t1.getText() + "8");
      }
    }
    if (s.equals("9")) {
      if (t1.getText().equals("0")) {
        t1.setText("9");


      } else {
        t1.setText(t1.getText() + "9");
      }
    }
    if (s.equals("+")) {
      b = t1.getText();
      c = Double.parseDouble(b);
      t1.setText("");
      i = 0;
    }
    if (s.equals("-")) {
      b = t1.getText();
      c = Double.parseDouble(b);
      t1.setText("");
      i = 1;
    }
    if (s.equals("*")) {
      b = t1.getText();
      c = Double.parseDouble(b);
      t1.setText("");
      i = 2;
    }
    if (s.equals("/")) {
      b = t1.getText();
      c = Double.parseDouble(b);
      t1.setText("");
      i = 3;
    }
    if (s.equals(".")) {
      if (!t1.getText().substring(t1.getText().length() - 1, t1.getText().length()).equals(".")) {
        t1.setText(t1.getText() + ".");
      }
    }
    if (s.equals("sqrt")) {
      b = t1.getText();
      double d = Double.parseDouble(b);
      double e = Math.sqrt(d);
      t1.setText(Double.toString(e));
    }
    if (s.equals("%")) {
      b = t1.getText();
      double d = Double.parseDouble(b);
      t1.setText(Double.toString(d / 100));
    }
    if (s.equals("1/x")) {
      b = t1.getText();
      double d = Double.parseDouble(b);
      double e = 1 / d;
      t1.setText(Double.toString(e));
    }
    if (s.equals("+/-")) {
      if (t1.getText().substring(0, 1).equals("-")) {
        t1.setText(t1.getText().substring(1, t1.getText().length()));
      } else {
        t1.setText("-" + t1.getText());
      }
    }
    if (s.equals("=")) {
      b = t1.getText();
      double c1 = Double.parseDouble(b);
      if (i == 0) {
        t1.setText(Double.toString(c + c1));
      }
      if (i == 1) {
        t1.setText(Double.toString(c - c1));
      }
      if (i == 2) {
        t1.setText(Double.toString(c * c1));
      }
      if (i == 3) {
        t1.setText(Double.toString(c / c1));
      }
    }
  }

  public void windowActivated(WindowEvent arg0) {
  }

  public void windowClosed(WindowEvent arg0) {
  }

  public void windowClosing(WindowEvent arg0) {
    Window f = (Window) arg0.getSource();
    f.dispose();

  }

  public void windowDeactivated(WindowEvent arg0) {
  }

  public void windowDeiconified(WindowEvent arg0) {
  }


  public void windowIconified(WindowEvent arg0) {
  }

  public void windowOpened(WindowEvent arg0) {
  }

  public void itemStateChanged(ItemEvent arg0) {
  }

  public static void main(String[] args) {
    jisuqi s = new jisuqi();
  }
}



[解决办法]
Java code
 
/*
这是我两年前写的,此计算机的功能不甚强大。
它可以实现加、减、乘、除,当然,可以输入[color=#FF0000][b]一串算式[/b][/color],[b][color=#FF0000]可以加括号[/color][/b],运算时是会判

断优先级的。不过,输入算式时,一定要输入标准的,否则会没有反应。
标准的如:12*(34/(45-32))+98
不标准的:12(34+98)  (这里,乘号不能少)
    +12    (这也不行,呵呵)

功能键:
AC:清屏(遇到问题时,按这个键即可)
C:退格键(即删除一个字符)
RE: 重新显示(在按下“=”以后,算式没了,显示的是结果,如果你还想看算式,

可以按下此键


最后说明一下:如果你运行它的时候,发现只看到一个界面,没有按钮等情况,请不

要怀疑我的程序,可能是系统的问题。当然,遇到这种情况,你关闭窗口。再次运行

,就不会有这种问题了。如果还有什么问题的话,可以用QQ留言给我:815611030
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Stack
{
  String s[]=new String[100];
  int n=0;
  public void InQuece(String str)
  {
    s[n]=str;
    n++;
  }
  public String DeQuece()
  {
    return s[--n];
  }
  public String Front()
  {
    return s[n-1];
  }
  public void Sprint()
  {
    for(int i=n-1;i>=0;i--)
      System.out.print(s[i]+" ");
    System.out.println();
  }
}
public class Calculator
{
  static Frame frm=new Frame("Calculator");
  //static TextField tff=new TextField(20);
  static Label lab=new Label("0.");
  static Panel pan=new Panel();
  static String labelstr="";
  static String ltemp="";
  static int flag=1;
  static Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19;
  public void setFrame()
  {
    frm.setBounds(300,150,400,350);
    frm.setLayout(null);
    frm.addWindowListener(new window());
    frm.setVisible(true);
    b0=new Button("0");b1=new Button("1");b2=new Button("2");b3=new Button("3");b4=new Button("4");b5=new Button("5");b6=new Button("6");
    b7=new Button("7");b8=new Button("8");b9=new Button("9");
    b10=new Button("+");b11=new Button("-");b12=new Button("*");b13=new Button("/");b14=new Button("AC");b15=new Button("C");b16=new Button("=");
    b17=new Button("(");b18=new Button(")");b19=new Button("RE");
    lab.setBounds(0, 30, 400, 40);
    lab.setFont(new Font("宋体",Font.PLAIN,30));
    lab.setAlignment(Label.RIGHT);
    pan.setBounds(0,60, 400, 300);
    pan.setLayout(new GridLayout(5,4));
    b0.addActionListener(new action());b1.addActionListener(new action());b2.addActionListener(new action());b3.addActionListener(new action());b4.addActionListener(new action());
    b5.addActionListener(new action());b6.addActionListener(new action());b7.addActionListener(new action());b8.addActionListener(new action());b9.addActionListener(new action());
    b10.addActionListener(new action());b11.addActionListener(new action());b12.addActionListener(new action());b13.addActionListener(new action());b14.addActionListener(new action());


    b15.addActionListener(new action());b16.addActionListener(new action());b17.addActionListener(new action());b18.addActionListener(new action());b19.addActionListener(new action());
    pan.add(b1);pan.add(b2);pan.add(b3);pan.add(b10);pan.add(b4);pan.add(b5);pan.add(b6);pan.add(b11);pan.add(b7);pan.add(b8);pan.add(b9);pan.add(b12);
    pan.add(b0);pan.add(b14);pan.add(b15);pan.add(b13);pan.add(b16);pan.add(b17);pan.add(b18);pan.add(b19);
    frm.add(lab);
    frm.add(pan);
    frm.setVisible(true);
  }
 


[解决办法]
Java code
public double cal(String str)    {        str=str.trim();        StringTokenizer st=new StringTokenizer(str,"+-*/ ",true);        Stack sta=new Stack();        String s,s1,s2;        while(st.hasMoreTokens())        {            s=st.dar.getTi 

热点排行