若干个经典Java小程序源代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
一个Java小程序源代码(反转字符串)//BorderLayoutTest.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class test1
{
public static void main(String[] args)
{
cloneFrame frame = new cloneFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class cloneFrame extends JFrame
{
public cloneFrame()
{
setTitle("机试程序");
setSize(600, 400);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(new Color(56,43,85));
Button1 = new JButton("点击复制反转字符串");
Button1.addActionListener(new turnListener());
buttonPanel.add(Button1);
JPanel textPanel = new JPanel();
textPanel.setBackground(new Color(100,100,100));
field1 = new JTextField("姓名:老孙;学号:2004132028", 20);
field2 = new JTextField("反转", 20);
field2.setEditable(false);
textPanel.add(field1);
textPanel.add(field2);
JPanel tuPanel = new JPanel();
JLabel label = new JLabel(new ImageIcon("006.gif"));
tuPanel.add(label);
tuPanel.setBackground(new Color(100,100,100));
Container contentPane = getContentPane();
contentPane.add(buttonPanel, BorderLayout.SOUTH);
contentPane.add(textPanel, BorderLayout.NORTH);
contentPane.add(tuPanel, BorderLayout.CENTER);
contentPane.setBackground(new Color(100,100,100));
}
private class turnListener
implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String gets = field1.getText();
int i = gets.length();
StringBuffer buffer = new StringBuffer(i);
for(int j=i-1;j>=0;j--)
{
buffer.append(gets.charAt(j));
}
String gets2 = buffer.toString();
field2.setText(gets2);
}
}
Container contentPane = getContentPane();
contentPane.add(buttonPanel, BorderLayout.SOUTH);
contentPane.add(textPanel, BorderLayout.NORTH);
contentPane.add(tuPanel, BorderLayout.CENTER);
contentPane.setBackground(new Color(100,100,100)); }
private class turnListener
implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String gets = field1.getText();
int i = gets.length();
StringBuffer buffer = new StringBuffer(i);
for(int j=i-1;j>=0;j--)
{
buffer.append(gets.charAt(j));
}
String gets2 = buffer.toString();
field2.setText(gets2);
}
}
private JButton Button1;
private JTextField field1;
private JTextField field2;
}
Java1
package com.kenki.emp;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.SQLException;
import java.sql.*;
public class emp extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
String code = request.getParameter("code");
String name = request.getParameter("name");
String pay = request.getParameter("pay");
System.out.println("empcode:" + code);
System.out.println("name:" + name);
System.out.println("pay:" + pay);
//创建驱动
new com.microsoft.jdbc.sqlserver.SQLServerDriver();
String strd =
"jdbc:microsoft:sqlserver://localhost:1433;databasename=emp_dates"; String username = "sa";
String pws = "";
try {
java.sql.Connection conn = java.sql.DriverManager.getConnection( strd, username, pws);
String strs = "insert into emp values(?,?,?)";
java.sql.PreparedStatement pre = conn.prepareStatement(strs);
pre.setString(1, code);
pre.setString(2, name);
pre.setString(3, pay);
pre.execute();
pre.close();
conn.close();
//重定向至查询页面
out.println("成功保存!!");
response.sendRedirect("emp.html");
} catch (SQLException ss) {
ss.printStackTrace();
response.sendRedirect("/WebModule1/error.html");
}
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
Java2-聊天程序
//这是个聊天程序,在ECLIPSE 运行 Client.java 就可以了。
连接是:localhost
//Server 代码,
package message;
import java.io.*;
import .*;
import java.util.*;
public class Server {
public static void main(String[] args) throws Exception{ System.out.print("Server");
ServerSocket socket=new ServerSocket(8888);
Vector v=new Vector();
while(true){
Socket sk=socket.accept();
DataInputStream in=new DataInputStream(sk.getInputStream()); DataOutputStream out=new DataOutputStream(sk.getOutputStream()); v.add(sk);
new ServerThread(in,v).start();
}
}
}
//ServerThread.java 代码
package message;
import .*;
import java.io.*;
import java.util.*;
public class ServerThread extends Thread{
DataInputStream in;
Vector all;
public ServerThread(DataInputStream in,Vector v){
this.in=in;
this.all=v;
}
public void run()
{
while(true)
{
try{
String s1=in.readUTF();
for(int i=0;i<all.size();i++)
{
Object obj=all.get(i);
Socket socket=(Socket)obj;
DataOutputStream out=new DataOutputStream(socket.getOutputStream()); out.writeUTF(s1);
System.out.print(i);
out.flush();
}
System.out.print("Message send over!");
}catch(Exception e){e.printStackTrace();};
}
}
}
//ClientFrame.java 代码
package message;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import .*;
import java.io.*;
public class ClientFrame extends JFrame implements ActionListener{
JButton b1=new JButton ("SendMessage");
JButton b2=new JButton("Link Server");
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JLabel l=new JLabel("输入服务器名字:");
JTextArea area=new JTextArea(10,20);
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel p4=new JPanel();
Socket socket;
public ClientFrame()
{
this.getContentPane().add(p1);
p2.add(new JScrollPane(area));
p3.add(t1);
p3.add(b1);
p4.add(l);
p4.add(t2);
p4.add(b2);
p2.setLayout(new FlowLayout());
p3.setLayout(new FlowLayout());
p4.setLayout(new FlowLayout());
p1.setLayout(new BorderLayout());
p1.add("North",p2);
p1.add("Center",p3);
p1.add("South",p4);
b1.addActionListener(this);
b2.addActionListener(this);
this.pack();
show();
}
Java3-猜数字游戏
/*1、编写一个猜数字的游戏,由电脑随机产生一个100以内的整数,让用户去猜,如果用户猜的比电脑大,则输出“大了,再小点!”,反之则输出“小了,再大点!”,用户总共只能猜十次,并根据用户正确猜出答案所用的次数输出相
应的信息,如:只用一次就猜对,输出“你是个天才!”,八次才猜对,输出“笨
死了!”,如果十次还没有猜对,则游戏结束!*/
import java.util.*;
import java.io.*;
public class CaiShu{
public static void main(String[] args) throws IOException{
Random a=new Random();
int num=a.nextInt(100);
System.out.println("请输入一个100以内的整数:");
for (int i=0;i<=9;i++){
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String str=bf.readLine();
int shu=Integer.parseInt(str);
if (shu>num)
System.out.println("输入的数大了,输小点的!");
else if (shu<num)
System.out.println("输入的数小了,输大点的!");
else {
System.out.println("恭喜你,猜对了!");
if (i<=2)
System.out.println("你真是个天才!");
else if (i<=6)
System.out.println("还将就,你过关了!");
else if (i<=8)
System.out.println("但是你还……真笨!");
else
System.out.println("你和猪没有两样了!");
break;}
}
}
}
package GuessNumber;
import java.io.*;
import java.io.BufferedWriter;
public class GuessNumber {
public void show() {
DataInputStream stdin = new DataInputStream(System.in); BufferedInputStream buffin = new BufferedInputStream(stdin);
number = (int) (Math.random() * 10000);
try {
while (flag) {
System.out.println("产生的随机数是:"+number);
System.out.println("这是一个猜数字的小游戏,请您输入一个从0到10000
的数字!");
input = stdin.readLine();
// guessnumber=Integer.parseInt(input);
/*
* if(Character.isLetter(guessnumber)){
* System.out.println("你输入的不是数字,请输入一个数字!"); flag=true; } */
/*
* if(!Character.isDigit(input)){
* System.out.println("你输入的不是数字,请输入一个数字!"); flag=true; } */
guessnumber = Integer.parseInt(input);
// guessnumber=Integer.valueOf(stdin.readLine()).intValue(); System.out.println("你输入的数是:" + guessnumber);
{
if (number < guessnumber)
System.out.println("你输入的数大了请重新输入!");
if (number > guessnumber)
System.out.println("你输入的数小了请重新输入!");
count++;
flag = true;
}
if (number == guessnumber) {
System.out.println("你真历害这么快你就猜对了!");
System.out.println("你一共猜了" + count + "次");
flag = false;
System.out.println("请输入你的名字:");
String name = stdin.readLine();
byte names[] = name.getBytes("ISO-8859-1");
userName = new String(names);
System.out.println("姓名:" + userName);
System.out.println("记录是:" + count + "次");
SaveFile save = new SaveFile();
save.output(userName, 0, userName.length());
}
// guessnumber=Integer.parseInt(stdin.readLine());
}
stdin.close();
buffin.close();
} catch (IOException e) {
e.getMessage();
// e.toString();
System.out.println("产生了异常!");
}
}
public static void main(String[] args) {
GuessNumber gus = new GuessNumber();
gus.show();
/*
* try{ System.out.println("按回车结束....."); System.in.read(); } * catch(IOException e){}
*/
}
private static String input; // 用户开始输入数字或字母
private static int number; // 产生的随机数
private static int guessnumber;// 用户输入的的数字
private static int count = 0; // 用统计用户猜的次数
private boolean flag = true; // 标记继续输入数字进行猜
private String userName; // 用来记录猜对的用户名字
}
class SaveFile {
// 这个方法是将传过来的名字写入文件里
public void output(String name, int a, int length) {
try {
FileWriter sout = new FileWriter("Gamererecord.txt"); BufferedWriter out = new BufferedWriter(sout);
sout.write(name, 0, length);
sout.close();
out.close();
} catch (IOException e) {
System.out.println("IO Error" + e);
}
}
}
可以直接出结果的,不过你得先建立一个名为GuessNumber的包,在此包下建立一个名为GuessNumber的类,然后将些段代码粘贴进来根据提示就可以出结果的
JAVA小游戏代码
int player1win,player2win;
protected synchronized void keyPressed(int keyCode){
...
else if(action == Canvas.FIRE){
if(chesses[selectedY][selectedX]==null){
chesses[selectedY][selectedX]=new Chesses(this.isPlayer1);
if(checkWin()){
String winner;
if(isPlayer1){
winner="白方胜利";
player1win++;
}
else{
winner="红方胜利";
player2win++;
}
Thread.sleep(3000);
}catch(Exception e){
}
Alert winAlert=new Alert("",
winner+"\n白方 "+player1win+":"+player2win+"红方", null,);
winAlert.setTimeout(Alert.FOREVER);
Display.getDisplay(gobang).setCurrent(winAlert,this); init();
repaint();
}
this.isPlayer=!this.isPlayer1;//切换下棋方
}
}
repaint();
}
private boolean checkWin(){
int num=1;
if(num<5){
num=1;
for(int i=1;i<4;i++){
if(isPlayer1(selectedX-i,selectedY)){
num++;
}
ease break;
}
for(int i=1;i<4;i++){
if(isPlayer1(selectedX+1,selectedY)){
num++;
}
else break;
}
}
if(num<5){
num=1;
for(int i=1;i<4;i++){
if(isPlayer1(selectedX-i,selectedY)){
num++;
}
ease break;
}
for(int i=1;i<4;i++){
if(isPlayer1(selectedX+1,selectedY)){
}
else break;
}
}
if(num<5{
num=1;
for(int i=1;i<=4;i++){
if(isPlayer1(sesectedX,selectedY-i)){
num++;
}
ease break;
}
for(int i=1;i<=4;i++){
if(isPlayer1(selectedX.,selectedY+i))
num++;
else break;
}
}
if(num<5){
num=1;
for(int i=1;i<=4;i++){
if(isPlayer1(selectedX+i,selectedY-i))
num++;
else break;
}
for(int i=1;i<=4;i++){
if(isPlayer1(selectedX-i,selectedY+i))
num++;
else break;
}
}
if(num>=5)
return true;
else
return false;
}
private boolean isPlayer1(int y,int x){
if(x<=15 && x>=0 && y<=15 && y>=0 && chesses[x][y]!=null){ if(chesses[x][y].isPlayer1==this.isPlayer1)
return true;
else
return false;
}
else return fale;
}
JAVA计算器源代码
import java.awt.*;
import java.awt.event.*;
import ng.*;
import javax.swing.*;
public class Counter extends Frame
{
//声明三个面板的布局
GridLayout gl1,gl2,gl3;
Panel p0,p1,p2,p3;
JTextField tf1;
TextField tf2;
Button
b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19 ,b20,b21,b22,b23,b24,b25,b26;
StringBuffer str;//显示屏所显示的字符串
double x,y;//x和y都是运算数
int z;//Z表示单击了那一个运算符.0表示"+",1表示"-",2表示"*",3表示"/" static double m;//记忆的数字
public Counter()
{
gl1=new GridLayout(1,4,10,0);//实例化三个面板的布局
gl2=new GridLayout(4,1,0,15);
gl3=new GridLayout(4,5,10,15);
tf1=new JTextField(27);//显示屏
tf1.setHorizontalAlignment(JTextField.RIGHT); tf1.setEnabled(false);
tf1.setText("0");
tf2=new TextField(10);//显示记忆的索引值
tf2.setEditable(false);
//实例化所有按钮、设置其前景色并注册监听器
b0=new Button("Backspace");
b0.setForeground(Color.red);
b0.addActionListener(new Bt());
b1=new Button("CE");
b1.setForeground(Color.red);
b1.addActionListener(new Bt());
b2=new Button("C");
b2.setForeground(Color.red);
b2.addActionListener(new Bt());
b3=new Button("MC");
b3.setForeground(Color.red);
b3.addActionListener(new Bt());
b4=new Button("MR");
b4.setForeground(Color.red);
b4.addActionListener(new Bt());
b5=new Button("MS");
b5.setForeground(Color.red);
b5.addActionListener(new Bt());
b6=new Button("M+");
b6.setForeground(Color.red);
b7=new Button("7");
b7.setForeground(Color.blue);
b7.addActionListener(new Bt()); b8=new Button("8");
b8.setForeground(Color.blue);
b8.addActionListener(new Bt()); b9=new Button("9");
b9.setForeground(Color.blue);
b9.addActionListener(new Bt()); b10=new Button("/");
b10.setForeground(Color.red);
b10.addActionListener(new Bt()); b11=new Button("sqrt");
b11.setForeground(Color.blue); b11.addActionListener(new Bt()); b12=new Button("4");
b12.setForeground(Color.blue); b12.addActionListener(new Bt()); b13=new Button("5");
b13.setForeground(Color.blue); b13.addActionListener(new Bt()); b14=new Button("6");
b14.setForeground(Color.blue); b14.addActionListener(new Bt()); b15=new Button("*");
b15.setForeground(Color.red);
b16=new Button("%");
b16.setForeground(Color.blue); b16.addActionListener(new Bt()); b17=new Button("1");
b17.setForeground(Color.blue); b17.addActionListener(new Bt()); b18=new Button("2");
b18.setForeground(Color.blue); b18.addActionListener(new Bt()); b19=new Button("3");
b19.setForeground(Color.blue); b19.addActionListener(new Bt()); b20=new Button("-");
b20.setForeground(Color.red);
b20.addActionListener(new Bt()); b21=new Button("1/X");
b21.setForeground(Color.blue); b21.addActionListener(new Bt()); b22=new Button("0");
b22.setForeground(Color.blue); b22.addActionListener(new Bt()); b23=new Button("+/-");
b23.setForeground(Color.blue); b23.addActionListener(new Bt()); b24=new Button(".");
b24.setForeground(Color.blue);
b25=new Button("+");
b25.setForeground(Color.red);
b25.addActionListener(new Bt());
b26=new Button("=");
b26.setForeground(Color.red);
b26.addActionListener(new Bt());
//实例化四个面板
p0=new Panel();
p1=new Panel();
p2=new Panel();
p3=new Panel();
//创建一个空字符串缓冲区
str=new StringBuffer();
//添加面板p0中的组件和设置其在框架中的位置和大小p0.add(tf1);
p0.setBounds(10,25,300,40);
//添加面板p1中的组件和设置其在框架中的位置和大小p1.setLayout(gl1);
p1.add(tf2);
p1.add(b0);
p1.add(b1);
p1.add(b2);
p1.setBounds(10,65,300,25);
//添加面板p2中的组件并设置其的框架中的位置和大小p2.setLayout(gl2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.setBounds(10,110,40,150);
//添加面板p3中的组件并设置其在框架中的位置和大小p3.setLayout(gl3);//设置p3的布局
p3.add(b7);
p3.add(b8);
p3.add(b9);
p3.add(b10);
p3.add(b11);
p3.add(b12);
p3.add(b13);
p3.add(b14);
p3.add(b15);
p3.add(b16);
p3.add(b17);
p3.add(b18);
p3.add(b19);
p3.add(b20);
p3.add(b21);
p3.add(b22);
p3.add(b23);
p3.add(b24);
p3.add(b25);
p3.add(b26);
p3.setBounds(60,110,250,150);
//设置框架中的布局为空布局并添加4个面板setLayout(null);
add(p0);
add(p1);
add(p2);
add(p3);
setResizable(false);//禁止调整框架的大小
//匿名类关闭窗口
addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e1) {
System.exit(0);
}
});
setBackground(Color.lightGray);
setBounds(100,100,320,280);
setVisible(true);
}
//构造监听器
class Bt implements ActionListener
{
public void actionPerformed(ActionEvent e2) {
try{
if(e2.getSource()==b1)//选择"CE"清零
{
tf1.setText("0");//把显示屏清零
str.setLength(0);//清空字符串缓冲区以准备接收新的输入运算数
}
else if(e2.getSource()==b2)//选择"C"清零
{
tf1.setText("0");//把显示屏清零
str.setLength(0);
}
else if(e2.getSource()==b23)//单击"+/-"选择输入的运算数是正数还是负数{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(-x));
}
else if(e2.getSource()==b25)//单击加号按钮获得x的值和z的值并清空y 的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);//清空缓冲区以便接收新的另一个运算数
y=0d;
z=0;
}
else if(e2.getSource()==b20)//单击减号按钮获得x的值和z的值并清空y 的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=1;
}
else if(e2.getSource()==b15)//单击乘号按钮获得x的值和z的值并清空y 的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=2;
}
else if(e2.getSource()==b10)//单击除号按钮获得x的值和z的值并空y的值{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=3;
}
else if(e2.getSource()==b26)//单击等号按钮输出计算结果
{
str.setLength(0);
switch(z)
{
case 0 : tf1.setText(""+(x+y));break;
case 1 : tf1.setText(""+(x-y));break;
case 2 : tf1.setText(""+(x*y));break;
case 3 : tf1.setText(""+(x/y));break;
}
}
else if(e2.getSource()==b24)//单击"."按钮输入小数
{
if(tf1.getText().trim().indexOf(′.′)!=-1)//判断字符串中是否已经包含了小数点
{
}
else//如果没数点有小
{
if(tf1.getText().trim().equals("0"))//如果初时显示为0
{
str.setLength(0);
tf1.setText((str.append("0"+e2.getActionCommand())).toString());
}
else if(tf1.getText().trim().equals(""))//如果初时显示为空则不做任何操作
{
}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
}
}
y=0d;
}
else if(e2.getSource()==b11)//求平方根
{
x=Double.parseDouble(tf1.getText().trim()); tf1.setText("数字格式异常");
if(x<0)
tf1.setText("负数没有平方根");
else
tf1.setText(""+Math.sqrt(x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b16)//单击了"%"按钮{
x=Double.parseDouble(tf1.getText().trim()); tf1.setText(""+(0.01*x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b21)//单击了"1/X"按钮{
x=Double.parseDouble(tf1.getText().trim());
if(x==0)
{
tf1.setText("除数不能为零");
}
else
{
tf1.setText(""+(1/x));
}
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b3)//MC为清除内存
{
m=0d;
tf2.setText("");
str.setLength(0);
}
else if(e2.getSource()==b4)//MR为重新调用存储的数据{
if(tf2.getText().trim()!="")//有记忆数字
{
tf1.setText(""+m);
}
}
else if(e2.getSource()==b5)//MS为存储显示的数据{
m=Double.parseDouble(tf1.getText().trim());
tf2.setText("M");
tf1.setText("0");
str.setLength(0);
}
else if(e2.getSource()==b6)//M+为将显示的数字与已经存储的数据相加要查看新的数字单击MR
{
m=m+Double.parseDouble(tf1.getText().trim());
}
else//选择的是其他的按钮
{
if(e2.getSource()==b22)//如果选择的是"0"这个数字键
{
if(tf1.getText().trim().equals("0"))//如果显示屏显示的为零不做操作{
}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
else if(e2.getSource()==b0)//选择的是“BackSpace”按钮
if(!tf1.getText().trim().equals("0"))//如果显示屏显示的不是零
{
if(str.length()!=1)
{
tf1.setText(str.delete(str.length()-1,str.length()).toString());//可能抛出字符串越界异常
}
else
{
tf1.setText("0");
str.setLength(0);
}
}
y=Double.parseDouble(tf1.getText().trim());
}
else//其他的数字键
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
}
catch(NumberFormatException e){
tf1.setText("数字格式异常");
}
catch(StringIndexOutOfBoundsException e){
tf1.setText("字符串索引越界");
}
}
}
public static void main(String args[])
{
new Counter();
}
}
简洁java计算器代码
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; //引入所需要的包
class MyFrame extends JFrame implements ActionListener{
private JButton b1,b2,b3,b4,b5,b6;
private TextField t1,t2,t3; //定义六个按钮和三个文本域
public MyFrame(String s){
super(s);
b1=new JButton("加");
b2=new JButton("减");
b3=new JButton("乘");
b4=new JButton("除");
//对按钮加文字标签
Panel p=new Panel(); //生成一个面板
p.setLayout(new FlowLayout()); //以FlowLayout来规划面板中的组件
t1=new TextField ("",4);
t2=new TextField("",4);
t3=new TextField("",4); //生成文本域并设置长度
p.add(new JLabel("Num1"));p.add(t1);
p.add(new JLabel("Num2"));p.add(t2);
p.add(new JLabel("Res"));p.add(t3);//顺次在面板中加入按钮和文本域
t3.setEditable(false); //设置t3不可编辑
Panel button=new Panel();
button.setLayout(new GridLayout(2,2));//以两行2列来布局button面板中
的各组件
button.add(b1);button.add(b2);button.add(b3);
button.add(b4);
getContentPane().add(button,BorderLayout.SOUTH);
getContentPane().add(p,BorderLayout.NORTH);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
//注册事件监听器
}
public void actionPerformed(ActionEvent e){ //实现接口方法
double number1=Double.parseDouble(t1.getText());
double number2=Double.parseDouble(t2.getText());//得到文本域中的数字字符串调用parseDouble()函数转化为数值型数字
if(e.getSource()==b1)
{
double result=number1+number2;
t3.setText(String.valueOf(result));//实现+
}
if(e.getSource()==b2)
{
double result=number1-number2;
t3.setText(String.valueOf(result));//实现-
}
if(e.getSource()==b3)
{
double result=number1*number2; //实现*
t3.setText(String.valueOf(result));
}
if(e.getSource()==b4) //实现/
{
double result=number1/number2;
t3.setText(String.valueOf(result));
}
}
}
public class Calculator{
public static void main(String[] args){
MyFrame frm=new MyFrame("Welcome to my calculator"); //设置标题frm.setSize(320,240); //设置大小
frm. setVisible(true);//可见
} }。