百度
360搜索
搜狗搜索

java基础代码实例,用java写一个登陆界面代码。详细介绍

本文目录一览: 求一段JAVA代码(实例代码)

....分太少了。。。哎。。灌水
import java.awt.event.*;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
new F().setVisible(true);
}
}
class F extends JFrame implements ActionListener{
JCheckBox a,b,c;
JRadioButton d,e,f;
ButtonGroup g;
F(){
this.setSize(400,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new java.awt.GridLayout(2,3));
a = new JCheckBox("JCheckBox A",true);//默认为选中
b = new JCheckBox("JCheckBox B");
c = new JCheckBox("JCheckBox C");
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
add(a);
add(b);
add(c);

d = new JRadioButton("JRadioButton 1");
e = new JRadioButton("JRadioButton 2");
f = new JRadioButton("JRadioButton 3");
d.addActionListener(this);
e.addActionListener(this);
f.addActionListener(this);
add(d);
add(e);
add(f);

g = new ButtonGroup();
g.add(d);
g.add(e);
g.add(f);
}
public void actionPerformed(ActionEvent e) {
this.setTitle("最后动作: "+e.getActionCommand());
}
}

用java写一个登陆界面代码。

概述具体框架使用jframe,文本框组件:JTextField;密码框组件:JPasswordField;标签组件:JLabel;复选框组件:JCheckBox;单选框组件:JRadioButton;按钮组件JButton。
登录界面:
代码实例import javax.swing.*;
import java.awt.*; //导入必要的包
public class denglu extends JFrame{
JTextField jTextField ;  //定义文本框组件
JPasswordField jPasswordField;    //定义密码框组件
JLabel jLabel1,jLabel2;
JPanel jp1,jp2,jp3;
JButton jb1,jb2;     //创建按钮
public denglu(){
jTextField = new JTextField(12);
jPasswordField = new JPasswordField(13);
jLabel1 = new JLabel("用户名");
jLabel2 = new JLabel("密码");
jb1 = new JButton("确认");
jb2 = new JButton("取消");
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
//设置布局
this.setLayout(new GridLayout(3,1));
jp1.add(jLabel1);
jp1.add(jTextField);//第一块面板添加用户名和文本框
jp2.add(jLabel2);
jp2.add(jPasswordField);//第二块面板添加密码和密码输入框
jp3.add(jb1);
jp3.add(jb2); //第三块面板添加确认和取消
// jp3.setLayout(new FlowLayout());   //因为JPanel默认布局方式为FlowLayout,所以可以注销这段代码.
this.add(jp1);
this.add(jp2);
this.add(jp3); //将三块面板添加到登陆框上面
//设置显示
this.setSize(300, 200);
//this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setTitle("登陆");
}
public static void main(String[] args){
new denglu();
}
}
拓展内容java swing包
Swing 是一个为Java设计的GUI工具包。
Swing是JAVA基础类的一部分。
Swing包括了图形用户界面(GUI)器件如:文本框,按钮,分隔窗格和表。
Swing提供许多比AWT更好的屏幕显示元素。它们用纯Java写成,所以同Java本身一样可以跨平台运行,这一点不像AWT。它们是JFC的一部分。它们支持可更换的面板和主题(各种操作系统默认的特有主题),然而不是真的使用原生平台提供的设备,而是仅仅在表面上模仿它们。这意味着你可以在任意平台上使用JAVA支持的任意面板。轻量级组件的缺点则是执行速度较慢,优点就是可以在所有平台上采用统一的行为。
概念解析:
JFrame _ java的GUI程序的基本思路是以JFrame为基础,它是屏幕上window的对象,能够最大化、最小化、关闭。JPanel _ Java图形用户界面(GUI)工具包swing中的面板容器类,包含在javax.swing 包中,可以进行嵌套,功能是对窗体中具有相同逻辑功能的组件进行组合,是一种轻量级容器,可以加入到JFrame窗体中。。
JLabel _ JLabel 对象可以显示文本、图像或同时显示二者。可以通过设置垂直和水平对齐方式,指定标签显示区中标签内容在何处对齐。默认情况下,标签在其显示区内垂直居中对齐。默认情况下,只显示文本的标签是开始边对齐;而只显示图像的标签则水平居中对齐。
JTextField _一个轻量级组件,它允许编辑单行文本。
JPasswordField _ 允许我们输入了一行字像输入框,但隐藏星号(*) 或点创建密码(密码)
JButton _ JButton 类的实例。用于创建按钮类似实例中的 "Login"。

java程序

这个不难的,主要是锻炼你将来做javabean的能力的,呵呵,我给你敲段代码,希望你能够笑纳:
文件名:UseValue.java
程序源码:
class MyValue
{
//声明一个变量名value,int型的
int value;
//通过setValue()的方法,设置这个value的值
public void setValue(int value)
{
//this.value指的是当前对象的value,即全局变量
this.value = value ;
}
//通过getValue()的方法,来获得这个值
public int getValue()
{
return value ;
}
}
//通过这个类,来实例化MyValue的对象,并且实现各个方法
public class UseValue
{
public static void main(String args[])
{
//实例化MyValue的对象
MyValue mv = new MyValue() ;
mv.setValue(10) ;
//输出结果
System.out.println(mv.getValue()) ;
}
}
在main类中写。
MyValue myValue = new MyValue();
myValue.setValue(10); //Value是整型的,如果是String 就改成"10"
System.out.println(myValue.getMyValue());
class MyValue{
Myvalue(){}
int value;
void setValue(int value){
this. value=value;
}
int getValue(){
return this.value;
}
}
class UseValue{
public static void main(String[] args){
MyValue mv=new MyValue();
mv.setValue(10);
System.out.println(mv.getValue());
}
}
//定义一个类MyValue
class MyValue {
// 用Value来保存一属性值
private int value;
// 方法setValue设置Value
public void setValue(int value) {
this.value = value;
}
// 方法getValue获取Value
public int getValue() {
return this.value;
}
}
// 定义一个类UseValue
public class UseValue {
public static void main(String[] args) {
// 创建一个MyValue类的对象MyValue
MyValue myValue = new MyValue();
// 为MyValue对象中的Value赋值10
myValue.setValue(10);
// 使用getValue方法获得MyValue对象中的数据
int value = myValue.getValue();
// 在屏幕上输出
System.out.println(value);
}
}

求Java高手给一简单的源代码(200行以下),最好有注解和一段简单的介绍

//声明包
package cn.jbit.classandobject;
//导入包
import java.util.Scanner;
/**
* 上机阶段4:登录并购买商品
*/
// 声明类Goods
public class Goods
{
// 声明String类型的数组:goods,并初始化。
String[] goods = new String[] { "电风扇", "洗衣机", "电视机", "冰 箱", "空调机" }; // 定义数组是干什么用的
// 声明double类型的数组:price,并初始化。
double[] price = new double[] { 124.23, 4500, 8800.90, 5000.88, 4456,
12000.46 };
// 声明返回值类型为:boolean的login()方法
public boolean login()
{
// 声明变量flag,类型为boolean,初始值为:false,作为是否登录成功的标志
boolean flag = false;
// 键盘输入
Scanner input = new Scanner(System.in);
// 打印
System.out.print("请输入用户名: ");
// 声明变量name,接收输入用户名
String name = input.next();
// 打印
System.out.print("请输入密码: ");
// 声明变量pwd,接收输入密码
String pwd = input.next();
// if判断用户名和密码是否正确
if (name.equals("TOM") && pwd.equals("123"))
{
// 打印
System.out.println("登录成功! ");
// 修改是否登录成功的标志
flag = true;
}
// else情况
else
{
// 打印
System.out.println("用户名或密码不匹配,登录失败!");
}
// 返回是否登录成功的标志:成功(true),失败(false)
return flag;// 这段代码为什么要加返回值
}
// 声明返回值为StringBuffer类型的方法change(double d),参数为double类型的d
public StringBuffer change(double d)// 这是什么意思啊
{
// StringBuffer str:声明StringBuffer类型的变量str
// String.valueOf(d):获取d的字符串值
// new StringBuffer(String.valueOf(d)):实例化str,调用了StringBuffer的构造方法
StringBuffer str = new StringBuffer(String.valueOf(d));// 这一句
// str.indexOf("."):返回第一个.所在位置:如果该值返回大于等于4,则进入for循环,否则跳过
for (int i = str.indexOf(".") - 3; i > 0; i = i - 3)
{// 这一句
// 在i出添加,如8,800.9
str.insert(i, ',');// 还有这一句
}
// 返回StringBuffer类型的字符串
return str;
}
// 声明返回值为void的方法showGoods()
public void showGoods()
{
// 打印
System.out.print("*********欢迎进入商品批发城*********");
// 打印
System.out.print("\n\t编号\t商品\t价格\n");
// for循环输出商品:goods.length用到开始声明的goods来获取数组长度
for (int i = 0; i < goods.length; i++)
{
// 打印:因为数组从0开始,而商品只能从1开始,所以i+1。\t制表符
System.out.print("\t" + (i + 1));
// 打印第i个商品
System.out.print("\t" + goods[i]);
// 打印第i个商品的价格。\n回车
System.out.print("\t" + change(price[i]) + "\n");
}
// 打印
System.out.println("**********************************");
}
// 主方法
public static void main(String[] args)
{
// 键盘输入
Scanner input = new Scanner(System.in);
// 声明Goods类的对象g,并实例化
Goods g = new Goods();
// 声明int变量serial, num
int serial, num;
// 声明double变量total
double total = 0;
// 判断是否登录成功
if (g.login())
{
// 打印商品信息
g.showGoods();
// 输入商品编号
System.out.print("请输入您批发的商品编号:");
// 接收
serial = input.nextInt();
// 输入批发数量
System.out.print("请输入批发数量:");
// 接收
num = input.nextInt();
// 计算总金额:price数组是从0开始的,商品数量是从1开始,第一个商品对应第0个价格
total = g.price[serial - 1] * num;// 计算总金额 //这一句
// 打印总金额
System.out.print("您需要付款:" + g.change(total));
}
}
}
/*jadclipse*/// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
package java.io;
// Referenced classes of package java.io:
// FilterInputStream, DataInput, EOFException, IOException,
// InputStream, PushbackInputStream, UTFDataFormatException
public class DataInputStream extends FilterInputStream
implements DataInput
{
public DataInputStream(InputStream inputstream)
{
super(inputstream);
bytearr = new byte[80];
chararr = new char[80];
readBuffer = new byte[8];
}
public final int read(byte abyte0[])
throws IOException
{
return in.read(abyte0, 0, abyte0.length);
}
public final int read(byte abyte0[], int i, int j)
throws IOException
{
return in.read(abyte0, i, j);
}
public final void readFully(byte abyte0[])
throws IOException
{
readFully(abyte0, 0, abyte0.length);
}
public final void readFully(byte abyte0[], int i, int j)
throws IOException
{
if(j < 0)
throw new IndexOutOfBoundsException();
int l;
for(int k = 0; k < j; k += l)
{
l = in.read(abyte0, i + k, j - k);
if(l < 0)
throw new EOFException();
}
}
public final int skipBytes(int i)
throws IOException
{
int j = 0;
for(int k = 0; j < i && (k = (int)in.skip(i - j)) > 0; j += k);
return j;
}
public final boolean readBoolean()
throws IOException
{
int i = in.read();
if(i < 0)
throw new EOFException();
else
return i != 0;
}
public final byte readByte()
throws IOException
{
int i = in.read();
if(i < 0)
throw new EOFException();
else
return (byte)i;
}
public final int readUnsignedByte()
throws IOException
{
int i = in.read();
if(i < 0)
throw new EOFException();
else
return i;
}
public final short readShort()
throws IOException
{
int i = in.read();
int j = in.read();
if((i | j) < 0)
throw new EOFException();
else
return (short)((i << 8) + (j << 0));
}
public final int readUnsignedShort()
throws IOException
{
int i = in.read();
int j = in.read();
if((i | j) < 0)
throw new EOFException();
else
return (i << 8) + (j << 0);
}
public final char readChar()
throws IOException
{
int i = in.read();
int j = in.read();
if((i | j) < 0)
throw new EOFException();
else
return (char)((i << 8) + (j << 0));
}
public final int readInt()
throws IOException
{
int i = in.read();
int j = in.read();
int k = in.read();
int l = in.read();
if((i | j | k | l) < 0)
throw new EOFException();
else
return (i << 24) + (j << 16) + (k << 8) + (l << 0);
}
public final long readLong()
throws IOException
{
readFully(readBuffer, 0, 8);
return ((long)readBuffer[0] << 56) + ((long)(readBuffer[1] & 255) << 48) + ((long)(readBuffer[2] & 255) << 40) + ((long)(readBuffer[3] & 255) << 32) + ((long)(readBuffer[4] & 255) << 24) + (long)((readBuffer[5] & 255) << 16) + (long)((readBuffer[6] & 255) << 8) + (long)((readBuffer[7] & 255) << 0);
}
public final float readFloat()
throws IOException
{
return Float.intBitsToFloat(readInt());
}
public final double readDouble()
throws IOException
{
return Double.longBitsToDouble(readLong());
}
/**
* @deprecated Method readLine is deprecated
*/
public final String readLine()
throws IOException
{
char ac[] = lineBuffer;
if(ac == null)
ac = lineBuffer = new char[128];
int i = ac.length;
int j = 0;
int k;
label0:
do
switch(k = in.read())
{
case -1:
case 10: // '\n'
break label0;
case 13: // '\r'
int l = in.read();
if(l != 10 && l != -1)
{
if(!(in instanceof PushbackInputStream))
in = new PushbackInputStream(in);
((PushbackInputStream)in).unread(l);
}
break label0;
default:
if(--i < 0)
{
ac = new char[j + 128];
i = ac.length - j - 1;
System.arraycopy(lineBuffer, 0, ac, 0, j);
lineBuffer = ac;
}
ac[j++] = (char)k;
break;
}
while(true);
if(k == -1 && j == 0)
return null;
else
return String.copyValueOf(ac, 0, j);
}
public final String readUTF()
throws IOException
{
return readUTF(((DataInput) (this)));
}
public static final String readUTF(DataInput datainput)
throws IOException
{
int i = datainput.readUnsignedShort();
byte abyte0[] = null;
char ac[] = null;
if(datainput instanceof DataInputStream)
{
DataInputStream datainputstream = (DataInputStream)datainput;
if(datainputstream.bytearr.length < i)
{
datainputstream.bytearr = new byte[i * 2];
datainputstream.chararr = new char[i * 2];
}
ac = datainputstream.chararr;
abyte0 = datainputstream.bytearr;
} else
{
abyte0 = new byte[i];
ac = new char[i];
}
int l = 0;
int i1 = 0;
datainput.readFully(abyte0, 0, i);
do
{
if(l >= i)
break;
int j = abyte0[l] & 255;
if(j > 127)
break;
l++;
ac[i1++] = (char)j;
} while(true);
do
{
if(l >= i)
break;
int k = abyte0[l] & 255;
switch(k >> 4)
{
case 0: // '\0'
case 1: // '\001'
case 2: // '\002'
case 3: // '\003'
case 4: // '\004'
case 5: // '\005'
case 6: // '\006'
case 7: // '\007'
l++;
ac[i1++] = (char)k;
break;
case 12: // '\f'
case 13: // '\r'
if((l += 2) > i)
throw new UTFDataFormatException("malformed input: partial character at end");
byte byte0 = abyte0[l - 1];
if((byte0 & 192) != 128)
throw new UTFDataFormatException((new StringBuilder()).append("malformed input around byte ").append(l).toString());
ac[i1++] = (char)((k & 31) << 6 | byte0 & 63);
break;
case 14: // '\016'
if((l += 3) > i)
throw new UTFDataFormatException("malformed input: partial character at end");
byte byte1 = abyte0[l - 2];
byte byte2 = abyte0[l - 1];
if((byte1 & 192) != 128 || (byte2 & 192) != 128)
throw new UTFDataFormatException((new StringBuilder()).append("malformed input around byte ").append(l - 1).toString());
ac[i1++] = (char)((k & 15) << 12 | (byte1 & 63) << 6 | (byte2 & 63) << 0);
break;
case 8: // '\b'
case 9: // '\t'
case 10: // '\n'
case 11: // '\013'
default:
throw new UTFDataFormatException((new StringBuilder()).append("malformed input around byte ").append(l).toString());
}
} while(true);
return new String(ac, 0, i1);
}
private byte bytearr[];
private char chararr[];
private byte readBuffer[];
private char lineBuffer[];
}
/*
DECOMPILATION REPORT
Decompiled from: D:\Program Files (x86)\myeclipce_blue\jre\lib\rt.jar
Total time: 260 ms
Jad reported messages/errors:
Exit status: 0
Caught exceptions:
*/

阅读更多 >>>  无代码开发平台免费,zion无代码开发平台开发微信小程序怎么样?

怎么用java for循环打印万年历基础源代码

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class CalenderTrain extends JFrame implements ActionListener {
JComboBox Month = new JComboBox(); //月份下拉列表框
JComboBox Year = new JComboBox(); //年份下拉列表框
JLabel Year_l = new JLabel("Year::"); //定义标签
JLabel Month_l = new JLabel("Month::"); //定义标签
Date now_date = new Date(); //获取今天的日期
JButton[] button_day = new JButton[49]; //定义一个数组用来存放日期
JButton button_ok = new JButton("Enter"); //现实选择日期
JButton button_today = new JButton("Today"); //显示今天按钮
int now_year = now_date.getYear() + 1900; //获取年份值
int now_month = now_date.getMonth(); //获取月份值(当前月份-1)
String year_int = null; //存放年份
int month_int; //存放月份
JPanel pane_ym = new JPanel(); //放置下拉列表框和控制按钮面板
JPanel pane_day = new JPanel(); //放置日期面板
JPanel pane_parent = new JPanel(); //放置以上两个面板
//定义方法绘制面板
public CalenderTrain() {
super("Calender!"); //设定面板得title
//---以下几行使得关闭面板时退出程序
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClose(WindowEvent e) {
System.exit(0);
}
});
//---
setResizable(false); //面板的大小不能变化
//设定年月
/*年份的区间是当前年份的过去10年到当前年份的未来20年
* 月份正常1??12月
*/
for (int i = now_year - 10; i <= now_year + 20; i++) {
Year.addItem(i + "");
}
for (int i = 1; i < 13; i++) {
Month.addItem(i + "");
}
Year.setSelectedIndex(10);//设定年份下拉列表为当前年份
pane_ym.add(Year_l);//添加年份标签
pane_ym.add(Year);//添加年份下拉列表框
Month.setSelectedIndex(now_month);//设定月份下拉列表为当前月份
pane_ym.add(Month_l);//添加月份标签
pane_ym.add(Month);//添加月份下拉列表框
pane_ym.add(button_ok);//添加确定按钮
pane_ym.add(button_today);//添加“今天”按钮
button_ok.addActionListener(this);//确定按钮添加监听事件
button_today.addActionListener(this);//“今天”按钮添加监听事件
//年月设定结束
//初始化日期按钮并绘制
pane_day.setLayout(new GridLayout(7, 7, 10, 10));
for (int i = 0; i < 49; i++) {
button_day[i] = new JButton(" ");
pane_day.add(button_day[i]);
}
this.setDay();//调用setDay()方法
pane_parent.setLayout(new BorderLayout());//设定布局管理器
setContentPane(pane_day);
setContentPane(pane_ym);
pane_parent.add(pane_day, BorderLayout.SOUTH);
pane_parent.add(pane_ym, BorderLayout.NORTH);
setContentPane(pane_parent);
pack();
show();
}
void setDay() {
year_int = Year.getSelectedItem().toString();
month_int = Month.getSelectedIndex();
int year_sel = Integer.parseInt(year_int) - 1900;//获得年份值
Date dt = new Date(year_sel, month_int, 1);//构造一个日期
GregorianCalendar cal = new GregorianCalendar();//创建一个Calendar实例
cal.setTime(dt);
String week[] = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
int day = 0;//day中存放某个月份的天数
int day_week = 0;//用来存放某个月的第一天是星期几的数值
//--将星期添加到前7个按钮中
for (int i = 0; i < 7; i++) {
button_day[i].setText(week[i]);
}
//--
/*判断是几月份,根据它来设定day的值
* 其中二月份要判断是否是闰年
*/
if (month_int == 0
|| month_int == 2
|| month_int == 4
|| month_int == 6
|| month_int == 7
|| month_int == 9
|| month_int == 11) {
day = 31;
} else if (
month_int == 3
|| month_int == 5
|| month_int == 8
|| month_int == 10) {
day = 30;
} else {
if (cal.isLeapYear(year_sel)) {
day = 29;
} else {
day = 28;
}
}
day_week = 7 + dt.getDay();
int count = 1;
/*绘制按钮
* 在这里我们首先要根据选定的月份的第一天是星期几来确定我们绘制按钮的起始位置
* 其中day_week就是我们要绘制的起始位置
* 对于那些没有数值可以显示的按钮要置空
*/
for (int i = day_week; i < day_week + day; count++, i++) {
if (i % 7 == 0
|| i == 13
|| i == 20
|| i == 27
|| i == 48
|| i == 34
|| i == 41) {
button_day[i].setForeground(Color.RED);
button_day[i].setText(count + "");
} else {
button_day[i].setText(count + "");
}

}
//--对于没有日期数值显示的按钮进行置空处理
if (day_week == 0) {
for (int i = day; i < 49; i++) {
button_day[i].setText(" ");
}
} else {
//第一天前面的按钮置空
for (int i = 7; i < day_week; i++) {
button_day[i].setText(" ");
}//最后一天后面的按钮置空
for (int i = day_week + day; i < 49; i++) {
button_day[i].setText(" ");
}
}

}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button_ok) {
this.setDay();//如果点击确定按钮就调用setDay()重新方法绘制按钮
} else if (e.getSource() == button_today) {
new CalenderTrain();//如果点击今天按钮,得到今天的日期
}
}
public static void main(String[] args) {
CalenderTrain ct = new CalenderTrain();
}
}

如何编写一个简单的java web前后端实例

用model2这种小框架搭建一个喽
你随便网上下一个,看看就行
jsp+Servlet
Java代码编写的30条实践建议,很多人认为学习java需要较好的计算机语言基础,而事实上高中学历的学习java,月薪过万的比比皆是,Java代码编写的30条实践建议,java知识点学习贵在积累。
Java代码编写的30条实践建议:
(1) 类名首字母应该大写。字段、方法以及对象(句柄)的首字母应小写。对于所有标识符,其中包含的所有单词都应紧靠在一起,而且大写中间单词的首字母。
例如:
ThisIsAClassName
thisIsMethodOrFieldName
若在定义中出现了常数初始化字符,则大写static final基本类型标识符中的所有字母。这样便可标 志出它们属于编译期的常数。
Java包(Package)属于一种特殊情况:它们全都是小写字母,即便中间的单词亦是如此。对于域名扩展名称,如com,org,net或者edu等,全部都应小写(这也是Java 1.1和Java 1.2的区别之一)。
(2) 为了常规用途而创建一个类时,请采取"经典形式",并包含对下述元素的定义:
equals()
hashCode()
toString()
clone()(implement Cloneable)
implement Serializable
(3) 对于自己创建的每一个类,都考虑置入一个main(),其中包含了用于测试那个类的代码。为使用一个项目中的类,我们没必要删除测试代码。若进行了任何形式的改动,可方便地返回测试。这些代码也可作为如何使用类的一个示例使用。
(4) 应将方法设计成简要的、功能性单元,用它描述和实现一个不连续的类接口部分。理想情况下,方法应简明扼要。若长度很大,可考虑通过某种方式将其分割成较短的几个方法。这样做也便于类内代码的重复使用(有些时候,方法必须非常大,但它们仍应只做同样的一件事情)。
(5) 设计一个类时,请设身处地为客户程序员考虑一下(类的使用方法应该是非常明确的)。然后,再设身处地为管理代码的人考虑一下(预计有可能进行哪些形式的修改,想想用什么方法可把它们变得更简单)。
(6) 使类尽可能短小精悍,而且只解决一个特定的问题。下面是对类设计的一些建议:
■一个复杂的开关语句:考虑采用"多形"机制
■数量众多的方法涉及到类型差别极大的操作:考虑用几个类来分别实现
■许多成员变量在特征上有很大的差别:考虑使用几个类
(7) 让一切东西都尽可能地"私有"--private。可使库的某一部分"公共化"(一个方法、类或者一个字段等等),就永远不能把它拿出。若强行拿出,就可能破坏其他人现有的代码,使他们不得不重新编写和设计。若只公布自己必须公布的,就可放心大胆地改变其他任何东西。
在多线程环境中,隐私是特别重要的一个因素--只有private字段才能在非同步使用的情况下受到保护。
(8) 谨惕"巨大对象综合症"。对一些习惯于顺序编程思维、且初涉OOP领域的新手,往往喜欢先写一个顺序执行的程序,再把它嵌入一个或两个巨大的对象里。根据编程原理,对象表达的应该是应用程序的概念,而非应用程序本身。
(9) 若不得已进行一些不太雅观的编程,至少应该把那些代码置于一个类的内部。
(10) 任何时候只要发现类与类之间结合得非常紧密,就需要考虑是否采用内部类,从而改善编码及维护工作(参见第14章14.1.2小节的"用内部类改进代码")。
(11) 尽可能细致地加上注释,并用javadoc注释文档语法生成自己的程序文档。
(12) 避免使用"魔术数字",这些数字很难与代码很好地配合。如以后需要修改它,无疑会成为一场噩梦,因为根本不知道"100"到底是指"数组大小"还是"其他全然不同的东西"。所以,我们应创建一个常数,并为其使用具有说服力的描述性名称,并在整个程序中都采用常数标识符。这样可使程序更易理解以及更易维护。
(13) 涉及构建器和异常的时候,通常希望重新丢弃在构建器中捕获的任何异常--如果它造成了那个对象的创建失败。这样一来,调用者就不会以为那个对象已正确地创建,从而盲目地继续。
(14) 当客户程序员用完对象以后,若你的类要求进行任何清除工作,可考虑将清除代码置于一个良好定义的方法里,采用类似于cleanup()这样的名字,明确表明自己的用途。除此以外,可在类内放置一个boolean(布尔)标记,指出对象是否已被清除。在类的finalize()方法里,请确定对象已被清除,并已丢弃了从RuntimeException继承的一个类(如果还没有的话),从而指出一个编程错误。在采取象这样的方案之前,请确定finalize()能够在自己的系统中工作(可能需要调用System.runFinalizersOnExit(true),从而确保这一行为)。
(15) 在一个特定的作用域内,若一个对象必须清除(非由垃圾收集机制处理),请采用下述方法:初始化对象;若成功,则立即进入一个含有finally从句的try块,开始清除工作。
(16) 若在初始化过程中需要覆盖(取消)finalize(),请记住调用super.finalize()(若Object属于我们的直接超类,则无此必要)。在对finalize()进行覆盖的过程中,对super.finalize()的调用应属于最后一个行动,而不应是第一个行动,这样可确保在需要基础类组件的时候它们依然有效。
(17) 创建大小固定的对象集合时,请将它们传输至一个数组(若准备从一个方法里返回这个集合,更应如此操作)。这样一来,我们就可享受到数组在编译期进行类型检查的好处。此外,为使用它们,数组的接收者也许并不需要将对象"造型"到数组里。
(18) 尽量使用interfaces,不要使用abstract类。若已知某样东西准备成为一个基础类,那么第一个选择应是将其变成一个interface(接口)。只有在不得不使用方法定义或者成员变量的时候,才需要将其变成一个abstract(抽象)类。接口主要描述了客户希望做什么事情,而一个类则致力于(或允许)具体的实施细节。
(19) 在构建器内部,只进行那些将对象设为正确状态所需的工作。尽可能地避免调用其他方法,因为那些方法可能被其他人覆盖或取消,从而在构建过程中产生不可预知的结果(参见第7章的详细说明)。
(20) 对象不应只是简单地容纳一些数据;它们的行为也应得到良好的定义。
(21) 在现成类的基础上创建新类时,请首先选择"新建"或"创作"。只有自己的设计要求必须继承时,才应考虑这方面的问题。若在本来允许新建的场合使用了继承,则整个设计会变得没有必要地复杂。
(22) 用继承及方法覆盖来表示行为间的差异,而用字段表示状态间的区别。一个非常极端的例子是通过对不同类的继承来表示颜色,这是绝对应该避免的:应直接使用一个"颜色"字段。
(23) 为避免编程时遇到麻烦,请保证在自己类路径指到的任何地方,每个名字都仅对应一个类。否则,编译器可能先找到同名的另一个类,并报告出错消息。若怀疑自己碰到了类路径问题,请试试在类路径的每一个起点,搜索一下同名的.class文件。
(24) 在Java 1.1 AWT中使用事件"适配器"时,特别容易碰到一个陷阱。若覆盖了某个适配器方法,同时拼写方法没有特别讲究,最后的结果就是新添加一个方法,而不是覆盖现成方法。然而,由于这样做是完全合法的,所以不会从编译器或运行期系统获得任何出错提示--只不过代码的工作就变得不正常了。
(25) 用合理的设计方案消除"伪功能"。也就是说,假若只需要创建类的一个对象,就不要提前限制自己使用应用程序,并加上一条"只生成其中一个"注释。请考虑将其封装成一个"独生子"的形式。若在主程序里有大量散乱的代码,用于创建自己的对象,请考虑采纳一种创造性的方案,将些代码封装起来。
(26) 警惕"分析瘫痪"。请记住,无论如何都要提前了解整个项目的状况,再去考察其中的细节。由于把握了全局,可快速认识自己未知的一些因素,防止在考察细节的时候陷入"死逻辑"中。
(27) 警惕"过早优化"。首先让它运行起来,再考虑变得更快--但只有在自己必须这样做、而且经证实在某部分代码中的确存在一个性能瓶颈的时候,才应进行优化。除非用专门的工具分析瓶颈,否则很有可能是在浪费自己的时间。
性能提升的隐含代价是自己的代码变得难于理解,而且难于维护。
(28) 请记住,阅读代码的时间比写代码的时间多得多。思路清晰的设计可获得易于理解的程序,但注释、细致的解释以及一些示例往往具有不可估量的价值。无论对你自己,还是对后来的人,它们都是相当重要的。如对此仍有怀疑,那么请试想自己试图从联机Java文档里找出有用信息时碰到的挫折,这样或许能将你说服。
(29) 如认为自己已进行了良好的分析、设计或者实施,那么请稍微更换一下思维角度。试试邀请一些外来人士--并不一定是专家,但可以是来自本公司其他部门的人。请他们用完全新鲜的眼光考察你的工作,看看是否能找出你一度熟视无睹的问题。采取这种方式,往往能在最适合修改的阶段找出一些关键性的问题,避免产品发行后再解决问题而造成的金钱及精力方面的损失。
(30) 良好的设计能带来最大的回报。简言之,对于一个特定的问题,通常会花较长的时间才能找到一种最恰当的解决方案。但一旦找到了正确的方法,以后的工作就轻松多了,再也不用经历数小时、数天或者数月的痛苦挣扎。我们的努力工作会带来最大的回报(甚至无可估量)。而且由于自己倾注了大量心血,最终获得一个出色的设计方案,成功的快感也是令人心动的。坚持抵制草草完工的诱惑--那样做往往得不偿失。

java 源代码 基础点的 谢谢

//给你贴个扫雷吧,请勿商用!
/*
This class defines a class that contains some useful
attributions and some methods to set or get these attributions
*/
import javax.swing.JButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
import java.util.Timer;
class ExButton extends JButton
{
//if the button is a mine,the isMine will be true
private boolean isMine;
//to check if a button has been visited is useful
//when using the recursion in the Game class
private boolean isVisited;
//the row number of the button
int btnRowNumber;
//the column number of the button
int btnColumnNumber;
//the mines around a button
int minesAround=0;
public void setIndex(int btnRowNumber,int btnColumnNumber)
{
this.btnRowNumber=btnRowNumber;
this.btnColumnNumber=btnColumnNumber;
}
public int getRowNumber()
{
return this.btnRowNumber;
}
public int getColumnNumber()
{
return this.btnColumnNumber;
}
public void setVisited(boolean isVisited)
{
this.isVisited=isVisited;
}
public boolean getVisited()
{
return this.isVisited;
}
public void setMine(boolean isMine)
{
this.isMine=isMine;
}
public boolean getMine()
{
return this.isMine;
}
//the attribute of minesAround add one each
//time a mine is put down around the button
public void addMinesAround()
{
this.minesAround++;
}
public int getMinesAround()
{
return this.minesAround;
}
}
//-------------------------------------------------
/*
File Name: Game.java
Author: Tian Wei Student Number: Email: xiangchensuiyue@163.com
Assignment number: #4
Description: In this program ,a frame will be created which contains
ten "mines".When you click a button ,it will present the
number of mines around or a message of losing the game
(if the button is a mine).You can make a right click to
sign a dengerous button as well.When all the mines have
been signed ,a message box of winning the game will jump
to the screen.And the the message of the time you used in
the game.More over,you can click the button on the bottom
to restart the game.
*/
public class Game extends JFrame{
//define some menber variables
private long minute=0,second=0;//take down time used int the game
private ExButton[][] btn;//two-dimension array present the buttons
private JLabel label;
private JButton restart;//restart button
private int minesRemained;//remained mines that you have not signed
private boolean thisTry=true;
private JLabel timeUsed=new JLabel ();
private Random rand=new Random();
private final int ROWS,COLUMNS;
private final int MINES;
// the constuctor
public Game(int rows,int columns,int mines)
{
super("Find mines");
this.ROWS=rows;
this.COLUMNS=columns;
this.MINES=mines;
minesRemained=MINES;
Timer timer=new Timer();//Timer's object to timer the game
timer.schedule(new MyTimer(), 0, 1000);//do the function every second
Container container=getContentPane();
container.setLayout(new BorderLayout());
//Jpanel in the Container
JPanel jpanel=new JPanel();
jpanel.setLayout(new GridLayout(ROWS,COLUMNS));
restart=new JButton("click me to restart the game");
JPanel jpanel2=new JPanel();
//Another JPanel in the Container
jpanel2.setLayout(new FlowLayout());
jpanel2.add(timeUsed);
jpanel2.add(restart);
ButtonListener restartHandler=new ButtonListener();
restart.addActionListener(restartHandler);
container.add(jpanel2,BorderLayout.SOUTH);
btn=new ExButton[ROWS+2][COLUMNS+2];
//initialize the buttons
for(int i=0;i<=ROWS+1;i++)
{
for(int j=0;j<=COLUMNS+1;j++)
{
btn[i][j]=new ExButton();
btn[i][j].addMouseListener(new MouseClickHandler());
btn[i][j].setIndex(i,j);
btn[i][j].setVisited(false);
}
}
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
jpanel.add(btn[i][j]);
container.add(jpanel,BorderLayout.CENTER);
JPanel jpanel3=new JPanel ();
label=new JLabel();
label.setText("Mines remaining "+MINES);
jpanel3.add(label);
container.add(jpanel3,BorderLayout.NORTH );
this.addMines();
this.addMinesAround();
}
//randomly put ten mines
private void addMines()
{
for(int i=1;i<=MINES;i++)
{
int raInt1=rand.nextInt(ROWS);
int raInt2=rand.nextInt(COLUMNS);
if((raInt1==0)||(raInt2==0)||btn[raInt1][raInt2].getMine())
i--;
else
btn[raInt1][raInt2].setMine(true);
}
}
//take down the mines around a button
private void addMinesAround()
{
for(int i=1;i<=ROWS;i++)
{
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine())
{
btn[i][j-1].addMinesAround();
btn[i][j+1].addMinesAround();
btn[i-1][j-1].addMinesAround();
btn[i-1][j].addMinesAround();
btn[i-1][j+1].addMinesAround();
btn[i+1][j-1].addMinesAround();
btn[i+1][j].addMinesAround();
btn[i+1][j+1].addMinesAround();
}
}
}
}
//if a button clicked is a empty one,then use a recursion
//to find all the empty buttons around
private void checkEmpty(ExButton button)
{
button.setVisited(true);
int x=button.getRowNumber();
int y=button.getColumnNumber();
button.setBackground(Color.white);
if((button.getMinesAround()==0)&&(x>=1)&&(x<=ROWS)
&&(y>=1)&&(y<=COLUMNS))
{
if(!btn[x][y-1].getVisited())
checkEmpty(btn[x][y-1]);
if(!btn[x][y+1].getVisited())
checkEmpty(btn[x][y+1]);
if(!btn[x-1][y].getVisited())
checkEmpty(btn[x-1][y]);
if(!btn[x+1][y].getVisited())
checkEmpty(btn[x+1][y]);
if(!btn[x-1][y-1].getVisited())
checkEmpty(btn[x-1][y-1]);
if(!btn[x-1][y+1].getVisited())
checkEmpty(btn[x-1][y+1]);
if(!btn[x+1][y-1].getVisited())
checkEmpty(btn[x+1][y-1]);
if(!btn[x+1][y+1].getVisited())
checkEmpty(btn[x+1][y+1]);
}
else if(button.getMinesAround()>0)
button.setText(""+button.getMinesAround());
}
//the main function
public static void main(String args[])
{
String rows,columns,mines;
int rowNumber,columnNumber,mineNumber;
rows=JOptionPane.showInputDialog("Enter the rows of the game");
columns=JOptionPane.showInputDialog("Enter the columns of the game");
mines=JOptionPane.showInputDialog("Enter the mines of the game");
rowNumber=Integer.parseInt(rows);
columnNumber=Integer.parseInt(columns);
mineNumber=Integer.parseInt(mines);
Game frame=new Game(rowNumber,columnNumber,mineNumber);
frame.setTitle("Find Mines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(220, 80);
frame.setSize(600, 600 );
frame.setVisible(true);
}
//there are three inner class below
//The first inner class is used to do the mouse listener's
//function.When you click a button ,it will present the
//number of mines around or a message of losing the game
//(if the button is a mine).You can make a right click to
//sign a dengerous button as well.When ten mines have been
//signed,it will check whether all the signed ones are mines
private class MouseClickHandler extends MouseAdapter
{
public void mouseClicked(MouseEvent event)
{
//get the button that been clicked
ExButton eventButton=new ExButton();
eventButton=(ExButton)event.getSource();
eventButton.setVisited(true);
//when it is a right click
if(event.isMetaDown())
{
if(eventButton.getText()=="#")
{
minesRemained++;
eventButton.setText("");
}
else
{
if((eventButton.getBackground()==Color.white)||
(eventButton.getText()!=""))
{
//do nothing
}
else
{
minesRemained--;
eventButton.setText("#");
}
}
label.setText("Mines remaining "+minesRemained);
//check if all the signed buttons are mines
if(minesRemained==0)
{
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine()&&btn[i][j].getText()!="#")
thisTry=false;
if(!btn[i][j].getMine()&&btn[i][j].getText()=="#")
thisTry=false;
}
if(thisTry)
{
//win the game
JOptionPane.showMessageDialog(null, "You succeed" +
" in this experience!");
JOptionPane.showMessageDialog(null, "Time used:"+
timeUsed.getText());
}
else//you have wrongly signed one or more mines
JOptionPane.showMessageDialog(null, "You have wrongly " +
"signed one or more mines,please check it and go on!");
}
}
else if(event.isAltDown())
{
//do nothing
}
else
{//normally click(left click)
if(eventButton.getText()=="#")
{
//do nothing
}
else if(eventButton.getMine())
{
//lose the game
JOptionPane.showMessageDialog(null, "What a pity!" +
"You failed!" );
//show all the mines to the loser
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine())
btn[i][j].setBackground(Color.BLACK);
}
JOptionPane.showMessageDialog(null, "Time used: 0"+
minute+":"+second);
}
else
{
if(eventButton.getMinesAround()==0)
{
//call the function to find all the empty buttons around
checkEmpty(eventButton);
}
else
eventButton.setText(""+eventButton.getMinesAround());
}
}
}
}
//The second class is to listen to the button which used to
//restart the game.In this class,it will dispose the old frame
//and create a new one(Of course,the mines's position have
//been changed).
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//what to dispose is the object of Game class
Game.this.dispose();
//the same code as in the main function
Game frame=new Game(ROWS,COLUMNS,MINES);
frame.setTitle("Find Mines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600 );
//make sure the frame is at the center of the screen
frame.setLocation(220, 80);
frame.setVisible(true);
}
}
//The last class is the class that will be used in the
//Timer's object timer.It should inherit the class TimerTask
//It is the task that the Timer will do every second
private class MyTimer extends TimerTask
{
public void run()
{
second+=1;
minute+=second/60;
second=second%60;
//change the text of the time used in the game
timeUsed.setText("Time used 0"+minute+":"+second);
}
}
}
//end of the class Game
package com.xuzs.test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField txtResult;
private JButton btnZero, btnOne, btnTwo, btnThree, btnFour, btnFive,
btnSix, btnSeven, btnEight, btnNine, btnPlus, btnMinus, btnTimes,
btnDivided, btnEqual, btnPoint, btnC, btnCE, btnSqrt, btnPlusMinus;
int z;
double x, y;
StringBuffer str;
public Calculator() {
super("计算器");
this.setSize(311, 231);
this.setLocation(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(1, 1));// 网格布局
JPanel panel = new JPanel(new GridLayout(6, 1));// 面板 网格布局6行1列
this.add(panel);
txtResult = new JTextField("0");
Color BackColor = new Color(255, 255, 255);
Color ForeColor = new Color(0, 0, 0);
txtResult.setBackground(BackColor);
txtResult.setForeground(ForeColor);
panel.add(txtResult);
txtResult.setHorizontalAlignment(JTextField.RIGHT);
txtResult.setEnabled(false);
// text.setEnabled(true);
JPanel panel_1 = new JPanel(new GridLayout(1, 4));
panel.add(panel_1);
btnSqrt = new JButton("sqrt");
panel_1.add(btnSqrt);
btnSqrt.addActionListener(this);
btnPlusMinus = new JButton("+/-");
panel_1.add(btnPlusMinus);
btnPlusMinus.addActionListener(this);
btnCE = new JButton("CE");
panel_1.add(btnCE);
btnCE.addActionListener(this);
btnC = new JButton("C");
panel_1.add(btnC);
btnC.addActionListener(this);
JPanel panel_2 = new JPanel(new GridLayout(1, 4));
panel.add(panel_2);
btnSeven = new JButton("7");
panel_2.add(btnSeven);
btnSeven.addActionListener(this);
btnEight = new JButton("8");
panel_2.add(btnEight);
btnEight.addActionListener(this);
btnNine = new JButton("9");
panel_2.add(btnNine);
btnNine.addActionListener(this);
btnDivided = new JButton("/");
panel_2.add(btnDivided);
btnDivided.addActionListener(this);
JPanel panel_3 = new JPanel(new GridLayout(1, 4));
panel.add(panel_3);
btnFour = new JButton("4");
panel_3.add(btnFour);
btnFour.addActionListener(this);
btnFive = new JButton("5");
panel_3.add(btnFive);
btnFive.addActionListener(this);
btnSix = new JButton("6");
panel_3.add(btnSix);
btnSix.addActionListener(this);
btnTimes = new JButton("*");
panel_3.add(btnTimes);
btnTimes.addActionListener(this);
JPanel panel_4 = new JPanel(new GridLayout(1, 4));
panel.add(panel_4);
btnOne = new JButton("1");
panel_4.add(btnOne);
btnOne.addActionListener(this);
btnTwo = new JButton("2");
panel_4.add(btnTwo);
btnTwo.addActionListener(this);
btnThree = new JButton("3");
panel_4.add(btnThree);
btnThree.addActionListener(this);
btnMinus = new JButton("-");
panel_4.add(btnMinus);
btnMinus.addActionListener(this);
JPanel panel_5 = new JPanel(new GridLayout(1, 4));
panel.add(panel_5);
btnZero = new JButton("0");
panel_5.add(btnZero);
btnZero.addActionListener(this);
btnPoint = new JButton(".");
panel_5.add(btnPoint);
btnPoint.addActionListener(this);
btnEqual = new JButton("=");
panel_5.add(btnEqual);
btnEqual.addActionListener(this);
btnPlus = new JButton("+");
panel_5.add(btnPlus);
btnPlus.addActionListener(this);
str = new StringBuffer();
this.setVisible(true);
}
public void windowClosing(WindowEvent a) {
System.exit(0);
}
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == btnC) {
txtResult.setText("0");
str.setLength(0);
} else if (e.getSource() == btnCE) {
txtResult.setText("0.");
str.setLength(0);
} else if (e.getSource() == btnPlusMinus) {
x = Double.parseDouble(txtResult.getText().trim());
txtResult.setText("" + (-x));
} else if (e.getSource() == btnPlus) {
x = Double.parseDouble(txtResult.getText().trim());
str.setLength(0);
y = 0d;
z = 1;
} else if (e.getSource() == btnMinus) {
x = Double.parseDouble(txtResult.getText().trim());
str.setLength(0);
y = 0d;
z = 2;
} else if (e.getSource() == btnTimes) {
x = Double.parseDouble(txtResult.getText().trim());
str.setLength(0);
y = 0d;
z = 3;
} else if (e.getSource() == btnDivided) {
x = Double.parseDouble(txtResult.getText().trim());
str.setLength(0);
y = 0d;
z = 4;
} else if (e.getSource() == btnEqual) {
str.setLength(0);
switch (z) {
case 1:
txtResult.setText("" + (x + y));
break;
case 2:
txtResult.setText("" + (x - y));
break;
case 3:
txtResult.setText("" + (x * y));
break;
case 4:
txtResult.setText("" + (x / y));
break;
}
}
else if (e.getSource() == btnPoint) {
if (txtResult.getText().trim().indexOf('.') != -1)// 判断字符串中是否已经包含了小数点
{
} else// 如果没数点有小
{
if (txtResult.getText().trim().equals("0"))// 如果初时显示为0
{
str.setLength(0);
txtResult.setText((str.append("0"
+ e.getActionCommand())).toString());
} else if (txtResult.getText().trim().equals(""))// 如果初时显示为空则不做任何操作
{
} else {
txtResult.setText(str.append(e.getActionCommand())
.toString());
}
}
y = 0d;
}
else if (e.getSource() == btnSqrt)// 求平方根
{
x = Double.parseDouble(txtResult.getText().trim());
txtResult.setText("数字格式异常");
if (x < 0)
txtResult.setText("负数没有平方根");
else
txtResult.setText("" + Math.sqrt(x));
str.setLength(0);
y = 0d;
}
else if (e.getSource() == btnZero)// 如果选择的是"0"这个数字键
{
if (txtResult.getText().trim().equals("0"))// 如果显示屏显示的为零不做操作
{
} else {
txtResult.setText(str.append(e.getActionCommand())
.toString());
y = Double.parseDouble(txtResult.getText().trim());
}
}
else// 其他的数字键
{
txtResult.setText(str.append(e.getActionCommand()).toString());
y = Double.parseDouble(txtResult.getText().trim());
}
} catch (NumberFormatException ae) {
txtResult.setText("数字格式异常");
} catch (StringIndexOutOfBoundsException ae) {
txtResult.setText("字符串索引越界");
}
}
public static void main(String arg[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
new Calculator();
}
}
我也贴一个:
用Java写的记事本,同样的,仅供交流,请勿商用!
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Remember extends JFrame implements TreeSelectionListener,ActionListener
{
JTree tree=null;
JTextArea text=new JTextArea(20,20);
int i=0;
DefaultMutableTreeNode root;
JButton b_save=new JButton("保存日记");
JButton b_del=new JButton("删除日记");
DefaultMutableTreeNode month[]=new DefaultMutableTreeNode[13];
Remember()
{
Container con=getContentPane();
DefaultMutableTreeNode root=new DefaultMutableTreeNode("日历记事本");
for(i=1;i<=12;i++)
{
month=new DefaultMutableTreeNode(""+i+"月");
root.add(month);
}
for(i=1;i<=12;i++)
{
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12)
{
for(int j=1;j<=31;j++)
month.add(new DefaultMutableTreeNode(j+"日"));
}
else if(i==4||i==6||i==9||i==11)
{
for(int j=1;j<=30;j++)
month.add(new DefaultMutableTreeNode(j+"日"));
}
else
{
for (int j=1;j<=28;j++)
month.add(new DefaultMutableTreeNode(j+"日"));
}
}
b_save.addActionListener(this);
b_del.addActionListener(this);
tree=new JTree(root);
JPanel p=new JPanel();
p.setLayout(new BorderLayout());
JScrollPane scrollpane_1=new JScrollPane(text);
p.add(scrollpane_1,BorderLayout.CENTER);
JPanel p_1=new JPanel();
p_1.add(b_save);
p_1.add(b_del);
p.add(p_1,BorderLayout.NORTH);
JScrollPane scrollpane_2=new JScrollPane(tree);
JSplitPane splitpane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,scrollpane_2,p);
tree.addTreeSelectionListener(this);
con.add(splitpane);
setVisible(true);
setBounds(70,80,460,320);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void valueChanged(TreeSelectionEvent e)
{
text.setText(null);
if(e.getSource()==tree)
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if(node.isLeaf())
{
String str=node.toString();
for(int i=0;i<=12;i++)
{
if(node.getParent()==month)
{
try{
String temp=null;
File f=new File(node.getParent().toString()+str+".txt");
FileReader file=new FileReader(f);
BufferedReader in=new BufferedReader(file);
while((temp=in.readLine())!=null)
text.append(temp+'\n');
file.close();
in.close();
}
catch(Exception el){}
}
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b_save)
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String str=node.toString();
if(node.isLeaf())
{
try
{
File f=new File(node.getParent().toString()+str+".txt");
FileWriter tofile=new FileWriter(f);
BufferedWriter out=new BufferedWriter(tofile);
out.write(text.getText(),0,(text.getText()).length());
out.flush();
tofile.close();
out.close();
}
catch(Exception el){}
}
}
else if(e.getSource()==b_del)
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String str=node.toString();
if(node.isLeaf())
{
File f=new File(node.getParent().toString()+str+".txt");
f.delete();
}
}
}
}
public class Example17_13 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Remember win=new Remember();
win.validate();
}
}
汗~~~这叫300行。。。
package com.regex;
import java.io.*;
import java.net.URLDecoder;
import java.util.regex.*;
public class Regex {
private int REMARK=0;
private int LOGIC=0;
private int PHYSIC=0;
boolean start=false;
/**
* @param args
*/
public static void main(String[] args) { //测试方法
// TODO Auto-generated method stub
Regex re=new Regex();
re.regCount("Regex.java");
System.out.println("remark Line: "+re.REMARK);
System.out.println("logic Line: "+re.LOGIC);
System.out.println("physic Line: "+re.PHYSIC);
}/**
* @author BlueDance
* @param s
* @deprecated count
*/
public void regCount(String s){
String url=null;
try {
url=URLDecoder.decode(this.getClass().getResource(s).getPath(),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
try {
BufferedReader br=new BufferedReader(new FileReader(new File(url)));
String s1=null;
while((s1=br.readLine())!=null){
PHYSIC++;
if(CheckChar(s1)==1){
REMARK++;
System.out.println("纯注释行:"+s1);
}
if(CheckChar(s1)==2){
LOGIC++;
REMARK++;
System.out.println("非纯注释行:"+s1);
}
if(CheckChar(s1)==3)
LOGIC++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}

阅读更多 >>>  jdklinux什么意思

}
/**
*
* @param s
* @return int
* @version check s
*/
public int CheckChar(String s){
String s1=null;
if(s!=null)
s1=s.trim();

//System.out.println(regCheck(s1,re));
if(regCheck(s1,"(//.*)")) //判断//开头的为纯注释行
return 1;
if(regCheck(s1,"(.*[;{})] *//.*)")) //判断不是//开头的非纯注释行
return 2;
if(regCheck(s1,"(//*.*)")){ //判断/*开头的纯注释行
start=true;
return 1;
}
if(regCheck(s1,"(.*[;{})]//*.*)")){ //判断不是/*开头的非纯注释行
start=true;
return 2;
}
if(regCheck(s1,"(.* */*/)")){ //判断*/结尾的纯注释行
start=false;
return 1;
}
if(regCheck(s1,"(.* */*/.*)")&&!strCheck(s1)){ //判断不是*/结尾的非纯注释行
if(strCheck(s1)){
start=false;
return 2;
}
}
if(start==true) //状态代码,start即/*开始时start=true*/结束时为false
return 1;
return 3;//ssssllll
}//aeee
/**
*
* @param s
* @param re
* @return boolean
*/
public boolean regCheck(String s,String re){ //正则表达试判断方法
return Pattern.matches(re,s);
}
public boolean strCheck(String s){ //中间有*/的字符判断 此方法最关键
if(s.indexOf("*/")>0){
int count=0;
String y[]=s.split("/*/");
boolean boo[]=new boolean[y.length];
for (int i = 0; i < y.length-1; i++) {
char c[]=y[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if(c[j]=='\\'&&c[j+1]=='"'){
count++;
}
}
if(count%2==0){
if(countNumber("\"",y[i])%2!=0){
boo[i]=true;
}else{
boo[i]=false;
}
}else{
if(countNumber("\"",y[i])%2==0){
boo[i]=true;
}else{
boo[i]=false;
}
}

}
for(int i=0;i
<boo.length;i++){
if(!boo[i])

return false;

}

return true;

}

return false;

}

public int countNumber(String s,String y){ //此方法为我前面写的字符串出现次数统计方法,不懂的可以看我前面的文章

int count=0;

String [] k=y.split(s);

if(y.lastIndexOf(s)==(y.length()-s.length()))

count=k.length;

else

count=k.length-1;

if(count==0)

System.out.println ("字符串\""+s+"\"在字符串\""+y+"\"没有出现过");

else

return count;

return -1;

}

}

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class GoodLucky extends JFrame implements ActionListener{

JTextField tf = new JTextField(); //实例化一个文本域

//设置两个按钮

JButton b1 = new JButton("开始");

JButton b2 = new JButton("停止");

boolean isGo = false;

//构造函数

public GoodLucky(){

b1.setActionCommand("start");//在开始按钮上设置一个动作监听 start

JPanel p = new JPanel(); //实例化一个可视化容器

//将两个按钮添加到可视化容器上面,用add方法

p.add(b1);

p.add(b2);

//在两个按钮上增加监听的属性,自动调用下面的监听处理方法actionPerformed(ActionEvent e),如果要代码有更好的可读性,可用内部类实现动作

//监听处理。

b1.addActionListener(this);

b2.addActionListener(this);

//将停止按钮设置为不可编辑(即不可按的状态)

b2.setEnabled(false);

this.getContentPane().add(tf,"North"); //将上面的文本域放在面板的北方,也就是上面(上北下南左西右东)

this.getContentPane().add(p,"South"); //将可视化容器pannel放在南边,也就是下面

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置用户在此窗体上发起 "close" 时默认执行的操作,参数EXIT_ON_CLOSE是使用 System exit 方法退出应用程序。仅在应用程序中使用

this.setSize(300,200); //设置面板大小,宽和高

this.setLocation(300,300); //设置面板刚开始的出现的位置

Cursor cu = new Cursor(Cursor.HAND_CURSOR); //用指定名称创建一个新的定制光标对象,参数表示手状光标类型

this.setCursor(cu); //为指定的光标设置光标图像,即设置光标图像为上面所创建的手状光标类型

this.setVisible(true); //将面板可视化设置为true,即可视,如果为false,即程序运行时面板会隐藏

tf.setText("welcome you! "); //设置面板的标题为欢迎

this.go(); //调用go方法

}

public void go(){

while(true){ //这里是死循环,也就是说用户不点击停止按钮的话他一直循环出现随机数,直到用户点击停止按钮循环才能推出,具体流程在actionPerformed方法中控制。

if(isGo == true){ //上面所定义的isGo的初始值为false,所以程序第一次到此会跳过

String s = ""; //设置空字符串

for(int j = 1; j <= 7;j++){ //产生7个随机数

int i = (int)(Math.random() * 36) + 1;//每个随机数产生方式,这里定义灵活,可以自由定义随机数产生的方式

if(i < 10){

s = s + " 0" + i; //如果产生的随机数小于10的话做处理:这里就牵扯到一个重要的概念,简单叙述一下:

/*

当一个字符串与一个整型数项相加的意思是连接,上面的s = s + " 0" + i的意思是字符串s链接0再连接整型i值,而不会导致0和整型的i相加,

产生的效果为s0i,由于s为空字符串(上面定义过的),所以当i小于零时,在个位数前面加上0,比如产生的随机数i为7的话,显示效果为 07.

*/

}else{

s = s + " " + i; //如果产生的随机数比10打的话,那么加上空格显示,即数字和数字之间有个空格

}

//以上循环循环七次,以保证能出现7个随机数

}

tf.setText(s); //将产生的随机数全部显示在文本域上,用文本域对象tf调用它的设置文本的方法setText(String)实现。

}

//以下为线程延迟

try{

Thread.sleep(10); //线程类同步方法sleep,睡眠方法,括号里的单位为ms。

}catch(java.lang.InterruptedException e){

e.printStackTrace(); //异常捕获,不用多说。

}

}

}

//以下是上面设置的事件监听的具体处理办法,即监听时间处理方法,自动调用

public void actionPerformed(ActionEvent e){ //传入一个动作事件的参数e

String s = e.getActionCommand(); //设置字符串s来存储获得动作监听,上面的start

/*

以下这个条件语句块的作用为:用户点击开始后(捕获start,用方法getActionCommand()),将命令触发设置为true,从而执行上面的go方法中的循环体(因为循环体中要求isGo参数为true,而初始为false)。

执行循环快产生随机数,并将开始按钮不可编辑化,而用户只可以使用停止按钮去停止。如果用户按下停止时,也就是没有传入参数“start”的时候,

执行else语句块中的语句,isGo设置为false,将不执行上面go中的循环语句块,从而停止产生随机数,并显示,并且把开始按钮设置为可用,而把

停止按钮设置为不可用,等待用户按下开始再去开始新一轮循环产生随机数。

*/

if(s.equals("start")){ //如果捕获到start,也就是用户触发了动作监听器,那么下面处理

isGo = true; //设置isGo为true

b1.setEnabled(false); //将开始按钮设置为不可用

b2.setEnabled(true); //将停止按钮设置为可用

}else{

isGo = false; //将isGo设置为false,isGo为循环标志位

b2.setEnabled(false); //设置停止按钮为不可用(注意看是b2,b2是停止按钮)

b1.setEnabled(true); //设置开始按钮为可用

}

}

public static void main(String[] args){

new GoodLucky(); //产生类的实例,执行方法

}

}
</boo.length;i++){

阅读更多 >>>  java有什么用,学习Java的用途有哪些?

初学Java。求一些Java简单小程序的代码实例

public class HelloWorld{
public static void main(String[] args){
System.out.println("Helloworld!");
}
}
java入门的第一个小程序,你安装个JDK,运行下试试,呵呵!!
随便一本java书上都有的

求一计算器java代码,最好简单一点(图形界面)

import java.awt.*;
import java.awt.event.*;
import java.lang.*;
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);
b6.addActionListener(new Bt());
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);
b15.addActionListener(new Bt());
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);
b24.addActionListener(new Bt());
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();
}
}
这是简的不能再简了的
import java.awt.*;
import java.awt.event.*;
public class jisuanqi extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
TextField txt;
private Button[] b = new Button[17];
private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "清空", "0", "=", "/", "关闭" };
static double a;
static String s, str;//定义变量 创建对像
public static void main(String args[]) {
(new jisuanqi()).frame();
}
public void frame() {
Frame fm = new Frame("简单计算器");
for (int i = 0; i <= 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i <= 15; i++) {
p2.add(b[i]);
} //创建按钮 并添加到P2
b[16].setBackground(Color.yellow);
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i <= 16; i++) {
b[i].addActionListener(new buttonlistener());//添加监听器
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "North");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);//都是些窗中设置 添加相关组件和监听器
}
public void windowClosing(WindowEvent e) {
System.exit(0);//退出系统
}
class buttonlistener implements ActionListener {//编写监听器事件 通过按键得出给果
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
jisuan();
str = String.valueOf(a);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";
} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());
if (btn.getLabel() == "清空")
txt.setText("");
}
}
public void jisuan() {//编写具体计算方法
if (s == "+")
a += Double.parseDouble(txt.getText());
else if (s == "-")
a -= Double.parseDouble(txt.getText());
else if (s == "*")
a *= Double.parseDouble(txt.getText());
else if (s == "/")
a /= Double.parseDouble(txt.getText());
else
a = Double.parseDouble(txt.getText());
}
}
}
class close implements ActionListener {//退出
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}

网站数据信息

"java基础代码实例,用java写一个登陆界面代码。"浏览人数已经达到20次,如你需要查询该站的相关权重信息,可以点击进入"Chinaz数据" 查询。更多网站价值评估因素如:java基础代码实例,用java写一个登陆界面代码。的访问速度、搜索引擎收录以及索引量、用户体验等。 要评估一个站的价值,最主要还是需要根据您自身的需求,如网站IP、PV、跳出率等!