编写一个图形界面的应用程序,Frame中包括一个菜单和一个Label。程序监听ActionEvent事件,每当用户选择一个菜单项时,Label中将显示这个菜单项

信管1132陈玉君 2015-06-18 04:34:48
编写一个图形界面的应用程序,Frame中包括一个菜单和一个Label。程序监听ActionEvent事件,每当用户选择一个菜单项时,Label中将显示这个菜单项的名称;菜单项设置一个“退出”项,当用户选择“退出”时,退出整个程序的执行行
新学java的菜鸟,各位高手帮帮忙~~~
...全文
170 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
第9章 AWT事件模型 本模块讨论了事件驱动的图形用户界面(GUI)的用户输入机制。 第一节 相关问题 讨论 - 以下为与本模块内容有关的问题: - 哪些部分对于一个图形用户界面来说是必需的? - 一个图形化程序如何处理鼠标点击或者其他类型的用户交互? 第二节 目 标 完成本模块之后,你应当能够: - 编写代码来处理在图形用户界面发生的事件 - 描述Adapter类的概念,包括如何和何使用它们 - 根据事件对象的细节来确定产生事件用户动作 - 为各种类型的事件创建合适的接口和事件处理器。 第三节 什么是事件? 如果用户用户界面层执行了一个动作(鼠标点击和按键),这将导致一个事件的发生。事件是描述发生了什么的对象。存在各种不同类型的事件类用来描述各种类型的用户交互。 9.3.1 事件事件源是一个事件的产生者。例如,在Button组件上点击鼠标会产生以这个Button 为源的一个ActionEvent. 这个ActionEvent实例是一个对象,它包含关于刚才所发生的那个事件的信息的对象。这些信息包括: - getActionCommand-返回与动作相关联的命令名称。 - GetModifiers-返回在执行动作持有的修饰符。 9.3.2 事件处理器 事件处理器就是一个接收事件、解释事件并处理用户交互的方法。 第四节 JDK1.0的事件模型与JDK1.2的事件模型比较 在JDK1.1事件接收和处理的方法发生了重要的改变。本节将比较以前的事件模型(JDK1.0)和当前的事件模型(JDK1.1和JDK1.2)。 JDK1.0采用的是层次事件模型,而JDK1.1以及更高的版本采用的是委托事件模型。 9.4.1 层次模型(JDK1.0) 层次模型是基于容器的。 事件先发送到组件,然后沿容器层次向上传播。没有被组件处理的事件会自动地继续传播到组件的容器。 JDK1.0的事件模型与JDK1.2的事件模型比较 例如,在下图,Button对象(包含在一个Frame上的Panel)上的鼠标点击首先向Button发送一个动作事件。如果它没有被Button处理,这个事件会被送往Panel,如果它在那儿仍然没有被处理,这个事件会被送往Frame。 层次模型(JDK1.0)(续) 这种模型有一个显著的优点: - 它简单,而且非常适合面向对象的编程环境;说到底,所有的组件都继承了java.awt.Component类,而handleEvent()就在java.awt.Component类。 然而,这种模型也存在缺点: - 事件只能由产生这个事件的组件或包含这个组件的容器处理。这个限制违反了面向对象编程的一个基本原则:功能应该包含在最合适的类。而最适合处理事件的类往往并不是源组件的容器层次的成员。 - 大量的CPU周期浪费在处理不相关的事件上。任何对于程序来说不相关或者并不重要的事件会沿容器层次一路传播,直到最后被抛弃。不存在一种简单的方法来过滤事件。 - 为了处理事件,你必须定义接收这个事件的组件的子类,或者在基容器创建一个庞大的handleEvent()方法。 委托事件模型是在JDK1.1引入的。在这个模型事件被送往产生这个事件的组件,然而,注册一个或多个称为监听者的类取决于每一个组件,这些类包含事件处理器,用来接收和处理这个事件。采用这种方法,事件处理器可以安排在与源组件分离的对象监听者就是实现了Listener接口的类。 事件是只向注册的监听者报告的对象。每个事件都有一个对应的监听者接口,规定哪些方法必须在适合接收那种类型的事件的类定义。实现了定义那些方法的接口的类可以注册为一个监听者。 9.4.2 委托模型 从没有注册的监听者的组件发出的事件不会被传播。 例如,这是一个只含有单个Button的简单Frame。 1.import java.awt.*; 2. 3.public class TestButton { 4.public static void main(String args[]) { 5.Frame f = new Frame("Test"); 6.Button b = new Button("Press Me!"); 7.b.addActionListener(new ButtonHandler()); 8.f.add(b,"Center"); 9.f.pack(); 10.f.setVisible(true); 11.} 12.} ButtonHandler类是一个处理器类,事件将被委托给这个类。 1.import java.awt.event.*; 2. 3.public class ButtonHandler implements ActionListener { 4.public void actionPerformed(ActionEvent e) { 5.System.out.println("Action occurred"); 6.System.out.println("Button's label is : ' 7.+ e.getActionCommand()); 8.} 9.} 这两个范例的特征如下: - Button类有一个addActionListner(ActionListener)方法。 - AddActionListner接口定义了一个方法actionPerformed,用来接收一个ActionEvent。 - 创建一个Button对象,这个对象可以通过使用addActionListener方法注册为ActionEvents的监听者。调用这个方法带有一个实现了ActionListener接口的类的参数。 委托模型(JDK1.1或更高版本)(续) - 在Button对象上用鼠标进行点击,将发送一个ActionEvent事件。这个ActionEvent事件会被使用addActionListener()方法进行注册的所有ActionListener的actionPerformed()方法接收。 - ActionEvent类的getActionCommand()方法返回与动作相关联的命令名称。以按钮的点击动作为例,将返回Button的标签。 这种方法有若干优点: - 事件不会被意外地处理。在层次模型一个事件可能传播到容器,并在非预期的层次被处理。 - 有可能创建并使用适配器(adapter)类对事件动作进行分类。 - 委托模型有利于把工作分布到各个类。 - 新的事件模型提供对JavaBeans的支持。 这种方法也有一个缺点: - 尽管当前的JDK支持委托模型和JDK1.0事件模型,但不能混合使用JDK1.0和JDK1.1。 第五节 图形用户界面的行为 9.5.1 事件类型 我们已经介绍了在单一类型事件上下文从组件接收事件的通用机制。事件类的层次结构图如下所示。许多事件类在java.awt.event,也有一些事件类在API的其他地方。 对于每类事件,都有一个接口,这个接口必须由想接收这个事件的类的对象实现。这个接口还要求定义一个或多个方法。当发生特定的事件,就会调用这些方法。表9-1列出了这些(事件)类型,并给出了每个类型对应的接口名称,以及所要求定义的方法。这些方法的名称是易于记忆的,名称表示了会引起这个方法被调用的源或条件。 表9-1方法类型和接口 Category Interface Name Methods Action ActionListener actionPerformed(ActionEvent) Item ItemListener itemStateChanged(ItemEvent) Mouse motion MouseMotionListener mouseDragged(MouseEvent) mouseMoved(MouseEvent) Mouse button MouseListener mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mouseClicked(MouseEvent) Key KeyListener keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent) Focus FocusListener focusGained(FocusEvent) focusLost(FocusEvent) Adjustment AdjustmentListener adjustmentValueChanged (AdjustmentEvent) Component ComponentListener componentMoved(ComponentEvent) componentHidden(ComponentEvent) componentResized(ComponentEvent) componentShown(ComponentEvent) 表9-1方法类型和接口(续) 9.5.2 复杂的范例 本节将考察一个更复杂的Java软件范例。它将跟踪鼠标被按下,鼠标的移动情况(鼠标拖动)。这个范例还将监测当鼠标没有按下,鼠标的移动情况(鼠标移动)。 当鼠标按下或没有按下,移动鼠标产生的事件会被实现了MouseMotionListener接口的类的对象检取。这个接口要求定义两个方法,mouseDragged()和mouseMoved()。即使你只对鼠标拖动感兴趣,也必须提供这两个方法。然而,mouseMoved()的体可以是空的。 要检取其他鼠标事件包括鼠标点击,必须定义MouseListener接口。这个接口包括若干个事件,即:mouseEntered, mouseExited, mousePressed, mouseReleased和 mouseClicked。 发生鼠标或键盘事件,有关鼠标的位置和所按下的键的信息可以从事件得到。代码如下: 1.import java.awt.*; 2.import java.awt.event.*; 3. 4.public class TwoListen implements 5.MouseMotionListener, MouseListener { 6.private Frame f; 7.private TextField tf; 8. 9.public static void main(String args[]) { 10.TwoListen two = new TwoListen(); 11.two.go(); 12.} 13. 复杂的范例(续) 1.public void go() { 2.f = new Frame("Two listeners example"); 3.f.add (new Label ("Click and drag the mouse"), 4."BorderLayout.NORTH"); 5.tf = new TextField (30); 6.f.add (tf, "BorderLayout.SOUTH"); 7. 8.f.addMouseMotionListener(this); 9.f.addMouseListener (this); 10.f.setSize(300, 200); 11.f.setVisible(true); 12.} 13. 14.// These are MouseMotionListener events 15.public void mouseDragged (MouseEvent e) { 16.String s = 17."Mouse dragging: X = " + e.getX() + 18." Y = " + e.getY(); 19.tf.setText (s); 20.} 21. 22.public void mouseMoved (MouseEvent e) { 23.} 24. 25.// These are MouseListener events 26.public void mouseClicked (MouseEvent e) { 27.} 28. 29.public void mouseEntered (MouseEvent e) { 30.String s = "The mouse entered"; 31.tf.setText (s); 32.} 复杂的范例(续) 1.public void mouseExited (MouseEvent e) { 2.String s = "The mouse has left the building"; 3.tf.setText (s); 4.} 5. 6.public void mousePressed (MouseEvent e) { 7.} 8. 9.public void mouseReleased (MouseEvent e) { 10.} 11.} 这个范例的一些地方值得注意。它们将在以下的几节讨论。 定义多重接口 这个类由第4行的如下代码声明: implements MouseMotionListener, MouseListener 声明多个接口,可以用逗号隔开。 监听多个源 如果你在第11行和第12行,调用如下方法: 两种类型的事件都会引起TwoListen类的方法被调用。一个对象可以“监听”任意数量的事件源;它的类只需要实现所要求的接口。 f.addMouseListener(this); f.addMouseMotionListener(this); 复杂的范例(续) 获取关于事件的细节 调用处理器方法(如mouseDragged())所带的事件参数可能会包含关于源事件的重要信息。为了确定可以获取关于某类事件的哪些细节,你应当查看java.awt.event合适的类文档。 9.5.3 多监听者 AWT事件监听框架事实上允许同一个组件带有多个监听者。一般地,如果你想写一个程序,它基于一个事件而执行多个动作,把那些行为编写到处理器的方法里即可。然而,有一个程序的设计要求同一程序的多个不相关的部分对于同一事件作出反应。这种情况是有可能的,例如,将一个上下文敏感的帮助系统加到一个已存在的程序监听者机制允许你调用addXXXlistener方法任意多次,而且,你可以根据你的设计需要指定任意多个不同的监听者。事件发生,所有被注册的监听者的处理器都会被调用。 注-没有定义调用事件处理器方法的顺序。通常,如果调用的顺序起作用,那么处理器就不是不相关的。在这种情况下,只注册第一个监听者,并由它直接调用其它的监听者。 9.5.4 事件Adapters(适配器) 你定义的Listener可以继承Adapter类,而且只需重写你所需要的方法。例如: 实现每个Listener接口的所有方法的工作量是非常大的,尤其是MouseListener接口和ComponentListener接口。 以MouseListener接口为例,它定义了如下方法: - mouseClicked(MouseEvent) - mouseEntered(MouseEvent) - mouseExited(MouseEvent) - mousePressed(MouseEvent) - mouseReleased(MouseEvent) 为了方便起见,Java语言提供了Adapters类,用来实现含有多个方法的类。这些Adapters类的方法是空的。 你可以继承Adapters类,而且只需重写你所需要的方法。例如: 1.import java.awt.*; 2.import java.awt.event.*; 3. 4.public class MouseClickHandler extends MouseAdapter { 5. 6.// We just need the mouseClick handler, so we use 7.// the Adapter to avoid having to write all the 8.// event handler methods 9.public void mouseClicked (MouseEvent e) { 10.// Do something with the mouse click... 11.} 12.} 9.5.5 匿名类 可以在一个表达式的域,包含整个类的定义。这种方法定义了一个所谓的匿名类并且立即创建了实例。匿名类通常和AWT事件处理一起使用。例如: 1.import java.awt.*; 2.import java.awt.event.*; 3.public class AnonTest { 4.private Frame f; 5.private TextField tf; 6. 7.public static void main(String args[]) 8.{ 9.AnonTest obj = new AnonTest(); 10.obj.go(); 11.} 12. 匿名类(续) 1.public void go() { 2.f = new Frame("Anonymous classes example"); 3.f.add(new Label("Click and drag the " + 4." mouse",BorderLayout.NORTH); 5.tf = new TextField (30); 6.f.add(tf,BorderLayout.SOUTH); 7. 8.f.addMouseMotionListener ( new 9.MouseMotionAdapter() { 10.public void mouseDragged (MouseEvent e) { 11.String s = 12."Mouse dragging: X = " + e.getX() + 13." Y = " + e.getY(); 14.tf.setText (s); 15.} 16.} ); // <- note the closing parenthesis 17. 18.f.addMouseListener (new MouseClickHandler()); 19.f.setSize(300, 200); 20.f.setVisible(true); 21.} 22.} 练习:事件 练习目标-你将编写、编译和运行包含事件处理器的Calculator 图形用户界面 和Account 图形用户界面的修改版本。 一、准备 为了很好地完成这个练习,你必须对事件模型是如何工作的有一个清晰的了解。 二、任务 水平1:创建一个Calculator 图形用户界面,第二部分 1. 使用你在模块8创建的图形用户界面代码,编写一段事件代码,用来连接计算器的用户界面和处理计算器上的函数的事件处理器。 水平3:创建一个Account 图形用户界面,第二部分 1. 创建一个AccountEvent类,类的对象在帐目发生改变被激活。然后激活送往Bankmanager类的事件。根据你在模块8创建的Teller.java GUI代码为起点进行练习。 三、练习小结 讨论 - 花几分钟间讨论一下,在本实验练习过程你都经历、提出和发现了什么。 经验 解释 总结 应用 四、检查一下你的进度 在进入下一个模块的学习之前,请确认你能够: - 编写代码来处理在图形用户界面发生的事件 - 描述Adapter类的概念,包括如何和何使用它们 - 根据事件对象的细节来确定产生事件用户动作 - 为各种类型的事件创建合适的接口和事件处理器。 五、思考 你现在已经知道如何为图形化输出和交互式用户输入来创建Java图形用户界面。然而,我们只介绍了能创建图形用户界面的一些组件。其他的组件在图形用户界面有什么用处呢?
java 编写计算器的简单程序//一个较为简洁的巧妙的计算器程序, import java.io.*; import java.awt.event.*; import java.awt.*; //需要解决的问题,数学的运算都有正负号的出现,在点击等号的候就会有冲突,应该怎样解决,经验:双精度浮点型数据类型是会像后减一位。0.7会显示成0.69999999 public class app74 { static int i=0; static int j=0; static int k=-1; static int l=-1; //static int Data1[]={1}; static String str9=""; static Frame frm1=new Frame("计算器"); static Button btn1=new Button("1"); static Button btn2=new Button("2"); static Button btn3=new Button("3"); static Button btn5=new Button("4"); static Button btn6=new Button("5"); static Button btn7=new Button("6"); static Button btn9=new Button("7"); static Button btn14=new Button("8"); static Button btn16=new Button("9"); static Button btn11=new Button("0");//数字0 static Button btn4=new Button("."); static Button btn8=new Button("+"); static Button btn10=new Button("-"); static Button btn15=new Button("*"); static Button btn13=new Button("/"); static Button btn20=new Button("="); static Button btn18=new Button("清零"); static Button btn19=new Button("后退"); static Button btn12=new Button("π"); static Button btn17=new Button("颜色"); static TextField TF1=new TextField(); static Label Lb1=new Label(".0",Label.RIGHT); //标签 static Label Lb2=new Label(".0",Label.RIGHT); //BS字符长度 static Label Lb3=new Label(".0",Label.RIGHT); //对象str22字符长度 static Label Lb4=new Label(".0",Label.RIGHT); //BS剩余字符长度字符长度 static Label Lb5=new Label("无",Label.LEFT); //执行错误抛出 static Label Lb6=new Label("对象BS字符长度 : ",Label.LEFT); static Label Lb7=new Label("对象str22字符长度 :",Label.LEFT); static Label Lb8=new Label("对象BS剩余字符长度:",Label.LEFT); static Label Lb9=new Label("错误:",Label.LEFT); static Label Lb10=new Label(".0",Label.RIGHT); //计算器下面的标签 static Label Lb11=new Label("余数:",Label.RIGHT); //余数标签 static Label Lb12=new Label(".0",Label.RIGHT); static TextArea TA=new TextArea("说明:由于软件不够完善,请规范运算的输入:1.可在里面按键输入",1000,TextArea.SCROLLBARS_VERTICAL_ONLY); static TextField TF=new TextField(); static GridLayout GL1=new GridLayout(5,4); //流动布局 static Panel Pl=new Panel(); //面板 static BorderLayout BL=new BorderLayout(); static shijian app1=new shijian(); //实现监听器的类对象 static char Data2[]=new char[5]; static Font fnt=new Font("Serief",Font.ITALIC+Font.BOLD,18); static Font fnt2=new Font("Serief",Font.BOLD,15); static String str22; static StringBuffer BS=new StringBuffer(""); //可创建空的字符串对象,这个很重要 static String str23=str22; public static void main(String args[]) throws IOException { frm1.setLayout(null); Pl.setLayout(GL1);//面板加入布局 frm1.setSize(253,450);//没有设置窗口大小 frm1.setLocation(250,450); Lb1.setBounds(0,55,250,25);//计算器数字输入显示框之一上边框 Pl.setBounds(0,80,250,290); Lb2.setBounds(370,60,50,25); Lb3.setBounds(370,90,50,25); Lb4.setBounds(370,120,50,25); Lb5.setBounds(300,150,320,25); Lb6.setBounds(250,60,120,25); Lb7.setBounds(250,90,120,25); Lb8.setBounds(250,120,120,25); Lb9.setBounds(250,150,30,25); Lb10.setBounds(0,365,250,30);//计算器数字输入显示框之一下边框 Lb11.setBounds(250,30,120,25); Lb12.setBounds(370,30,50,25); TF.setBounds(0,30,250,25); TA.setBounds(0,395,250,75); TA.setEditable(false); Pl.add(btn1);//面板 Pl.add(btn2); Pl.add(btn3); Pl.add(btn4); Pl.add(btn5); Pl.add(btn6); Pl.add(btn7); Pl.add(btn8); Pl.add(btn9);//加入按钮 Pl.add(btn14); Pl.add(btn16); Pl.add(btn17); Pl.add(btn10);//加 Pl.add(btn11);//减 Pl.add(btn12);//乘 Pl.add(btn13);//除 Pl.add(btn15);//这里是等号注意事件监听器在不同的类上 Pl.add(btn17); Pl.add(btn18); Pl.add(btn19); Pl.add(btn20); frm1.add(Pl);//加入面板 frm1.addWindowListener(new shijian2()); frm1.add(Lb1); frm1.add(Lb2); frm1.add(Lb3); frm1.add(Lb4); frm1.add(Lb5); frm1.add(Lb6); frm1.add(Lb7); frm1.add(Lb8); frm1.add(Lb9); frm1.add(Lb10); frm1.add(Lb11); frm1.add(Lb12); frm1.add(TA); frm1.add(TF); //Lb2.setBackground(Color.pink); //Lb3.setBackground(Color.pink); //Lb4.setBackground(Color.pink); //Lb5.setBackground(Color.white); Lb6.setBackground(Color.white); Lb7.setBackground(Color.white); Lb8.setBackground(Color.white); Lb9.setBackground(Color.white); Lb10.setBackground(Color.gray); Lb11.setBackground(Color.white); TF.setBackground(Color.pink); //TA.setBackground(Color.pink); //Lb12.setBackground(Color.gray); Lb1.setFont(fnt); Lb2.setFont(fnt); Lb3.setFont(fnt); Lb4.setFont(fnt); Lb10.setFont(fnt); Lb11.setFont(fnt2); Lb12.setFont(fnt); Lb1.setBackground(Color.gray); btn1.addActionListener(app1); btn2.addActionListener(app1); btn3.addActionListener(app1); btn4.addActionListener(app1); btn5.addActionListener(app1); btn6.addActionListener(app1); btn7.addActionListener(app1); btn8.addActionListener(app1); btn9.addActionListener(app1); btn10.addActionListener(app1); btn11.addActionListener(app1); btn12.addActionListener(app1); //btn12.addActionListener(app1);//写两个这个则会被触发两次事件 btn13.addActionListener(app1); btn14.addActionListener(app1); btn15.addActionListener(app1); btn16.addActionListener(app1); btn17.addActionListener(app1); btn18.addActionListener(app1); btn19.addActionListener(app1); btn20.addActionListener(app1); TF.addTextListener(new shijian3()); frm1.setBackground(Color.white); frm1.setResizable(false); frm1.setVisible(true);//可见 } static class shijian implements ActionListener//接口的实现 { public void actionPerformed(ActionEvent e) { Button BT=(Button)e.getSource(); //取得事件的对象,用于判断事件所属 String str1=BT.getLabel(); //取得按钮的名字,也就是相应的数字 if(str1=="0"||str1=="1"||str1=="2"||str1=="3"||str1=="4"||str1=="5"||str1=="6"||str1=="7"||str1=="8"||str1=="9"||str1=="+"||str1=="-"||str1=="*"||str1=="/"||str1=="."||str1=="π") { if(str1=="π"){str1=Double.toString(Math.PI);} BS.append(str1);//将得到的字符串加入到原有字符串 String str22=BS.toString();//转换成字符串 String str56=Integer.toString(str22.length());//将整形转换成字符串 Lb10.setText(str22); Lb2.setText(str56); Lb3.setText(str56); Lb4.setText(str56); Lb5.setText("无"); Lb12.setText(".0"); Lb1.setText(str22); try{ FileWriter FQ=new FileWriter("D:\\java\\10.txt");FQ.write(str22);FQ.flush();} catch(Exception u) {System.out.println("出错了");}} if(str1=="=")//如果等于等号if里面包含多个if或者while { // System.out.println("str22="+str22); char Data[]=new char[BS.length()]; try{ FileReader FV=new FileReader("D:\\java\\10.txt");//写入所需数据 FV.read(Data);} //这是我们写入的数据, catch(Exception y){System.out.println("出错了");} while(k程序的关键,包括识别使用者使用的计算符号, //还有就是为解决符号多个共存,又没有冲突,不能访问数组的第一位,如果第一位就有符号,那就会跳出,出现错误,只要不访问数组的第一位就好啦, //到了非一号的运算符,会直接跳出,执行相应的动作 break;}; char ch2=Data[k+1]; if(ch2=='*') {Lb1.setText(""); //清空标签内的内容 String str90=BS.toString(); //转换并取得字符串的内容.字符串内容已经确定,只是调用 Lb10.setText(str90); // Lb10标签的显示 if(str90.indexOf(".")!=-1) //不等于1那么就是有点号,使用浮点数,利用的是系统抛出异常赋的默认值 { int num1=str90.indexOf('*'); //取得*号的位置 String str2=str90.substring(0,num1); //取得数字字符窜 String str3=str90.substring(num1+1,BS.length()); //取得数字字符窜 // System.out.println("str2="+str2); // System.out.println("str3="+str3); float num2=Float.parseFloat(str2); //数据类型转换,使用长整形 float num3=Float.parseFloat(str3); //数据类型转换 float sum=(float)num2*num3; String str6=Float.toString(sum); //转换回字符串 Lb1.setText(str6); k=-1; BS=new StringBuffer(""); BS.append(str6);} if(str90.indexOf(".")==-1) //等于1那么就是没有有点号,使用非浮点数 { Lb1.setText(""); //清空标签内的内容 String str91=BS.toString(); //转换并取得字符串的内容.字符串内容已经确定,只是调用 Lb10.setText(str90); // Lb10标签的显示 int num1=str91.indexOf('*'); //取得*号的位置 String str2=str91.substring(0,num1); //取得数字字符窜 String str3=str91.substring(num1+1,BS.length()); //取得数字字符窜 // System.out.println("str2="+str2); //System.out.println("str3="+str3); long num2=Long.parseLong(str2); //数据类型转换,使用长整形 long num3=Long.parseLong(str3); //数据类型转换 long sum=num2*num3; String str6=Long.toString(sum); //转换回字符串 Lb1.setText(str6); k=-1; BS=new StringBuffer(""); BS.append(str6); } } if(ch2=='/') { Lb1.setText(""); //清空标签内的内容 String str91=BS.toString(); //转换并取得字符串的内容 Lb10.setText(str91); // Lb10标签的显示 //System.out.println("BS长度="+BS.length()); String str1000=BS.toString(); // System.out.println("str1000="+str1000); if(str91.indexOf(".")==-1){ int num1000=str1000.indexOf('/'); //取得*号的位置 // System.out.println("num1000="+num1000); String str2000=str1000.substring(0,num1000); String str3000=str1000.substring(num1000+1,BS.length()); int num2000=Integer.parseInt(str2000); int num3000=Integer.parseInt(str3000); int sum20=num2000/num3000; //整除数 int sum21=num2000%num3000; //余数 String str56=Integer.toString(sum20); String str57=Integer.toString(sum21); //System.out.println("sum="+sum20); Lb1.setText(str56); Lb12.setText(str57); BS=new StringBuffer("");k=-1; BS.append(Float.toString((float)num2000/(float)num3000));}//因为整形运算会有余数的求法,所以得转换成单精度型的数据类型进行计算,以免丢失数据 if(str91.indexOf(".")!=-1){ int num1000=str1000.indexOf('/'); //取得*号的位置 // System.out.println("num1000="+num1000); String str2000=str1000.substring(0,num1000); String str3000=str1000.substring(num1000+1,BS.length()); float num2000=Float.parseFloat(str2000); float num3000=Float.parseFloat(str3000); float sum20=(float)num2000/num3000; String str56=Float.toString(sum20); // System.out.println("sum="+sum20); Lb1.setText(str56); BS=new StringBuffer("");k=-1; BS.append(str56);} } if(ch2=='+'){ Lb1.setText(""); //清空标签内的内容 String str97=BS.toString(); //转换并取得字符串的内容 Lb10.setText(str97); // Lb10标签的显示 // System.out.println("BS长度="+BS.length()); String str1001=BS.toString(); // System.out.println("str1001="+str1001); if(str97.indexOf(".")==-1){ int num1001=str1001.indexOf('+');//取得*号的位置 // System.out.println("num1001="+num1001); if(num1001>0){ String str2001=str1001.substring(0,num1001); String str3002=str1001.substring(num1001+1,BS.length()); int num2001=Integer.parseInt(str2001); //如果是由小数点的结果则要将数据类型转换成float int num3001=Integer.parseInt(str3002); int sum21=num2001+num3001; String str51=Integer.toString(sum21); // System.out.println("sum="+sum21); Lb1.setText(str51); BS=new StringBuffer("");k=-1; BS.append(str51);} if(num1001==0) { BS.deleteCharAt(0);//删除第一个减号 (BS.toString()).indexOf("+");//取得第二个减号的位置 //StringBuffer str69=new StringBuffer(BS.toString()); //这里必须引入其他的字符串变量来储存,关键在于获得不是第一个减号的位置 //str69.insert(0,'+'); String str2001=(BS.toString()).substring(0,((BS.toString()).indexOf("+"))); String str3002=(BS.toString()).substring(((BS.toString()).indexOf("+")+1),(BS.length())); int num2001=Integer.parseInt(str2001); //如果是由小数点的结果则要将数据类型转换成float int num3001=Integer.parseInt(str3002); int sum21=num2001+num3001; String str51=Integer.toString(sum21); // System.out.println("sum="+sum21); Lb1.setText(str51); BS=new StringBuffer("");k=-1; BS.append(str51); } } if(str97.indexOf(".")!=-1) { //利用抛出异常的数字是-1的规律,设定if语句 int num1001=str1001.indexOf('+');//取得*号的位置 // System.out.println("num1001="+num1001); if(num1001>0){ String str2001=str1001.substring(0,num1001); String str3002=str1001.substring(num1001+1,BS.length()); float num2001=Float.parseFloat(str2001); //如果是由小数点的结果则要将数据类型转换成float float num3001=Float.parseFloat(str3002); float sum21=(float)num2001+num3001; String str51=Float.toString(sum21); //System.out.println("sum="+sum21); Lb1.setText(str51); BS=new StringBuffer("");k=-1; BS.append(str51);} if(num1001==0) { BS.deleteCharAt(0);//删除第一个减号 (BS.toString()).indexOf("+");//取得第二个减号的位置 String str2001=(BS.toString()).substring(0,((BS.toString()).indexOf("+"))); String str3002=(BS.toString()).substring(((BS.toString()).indexOf("+")+1),(BS.length())); float num2001=Float.parseFloat(str2001); //如果是由小数点的结果则要将数据类型转换成float float num3001=Float.parseFloat(str3002); float sum21=(float)num2001+num3001; String str51=Float.toString(sum21); //System.out.println("sum="+sum21); Lb1.setText(str51); BS=new StringBuffer("");k=-1; BS.append(str51); } } } //k值已经变化,为使上面的语句的循环有用,的赋回原值 if(ch2=='-') { Lb1.setText(""); //清空标签内的内容 String str102=BS.toString(); //转换并取得字符串的内容 Lb10.setText(str102); // Lb10标签的显示 // System.out.println("BS长度="+BS.length()); String str1002=BS.toString(); // System.out.println("str1002="+str1002); if(str1002.indexOf(".")==-1) //利用抛出异常的数字是-1的规律,设定if语句 {int num1002=str1002.indexOf('-');//取得*号的位置 // System.out.println("num1002="+num1002); if(num1002>0){ String str2002=str1002.substring(0,num1002); String str3003=str1002.substring(num1002+1,BS.length()); int num2002=Integer.parseInt(str2002); int num3002=Integer.parseInt(str3003); int sum22=num2002-num3002; String str53=Integer.toString(sum22); // System.out.println("sum="+sum22); Lb1.setText(str53); BS=new StringBuffer("");k=-1; BS.append(str53);} if(num1002==0){//由于会有两个减号存在的情况,应该要分情况,比如负数加负数的候 BS.deleteCharAt(0);//删除第一个减号 (BS.toString()).indexOf("-");//取得第二个减号的位置 StringBuffer str67=new StringBuffer(BS.toString()); //这里必须引入其他的字符串变量来储存,关键在于获得不是第一个减号的位置 str67.insert(0,'-'); String str2002=(str67.toString()).substring(0,((BS.toString()).indexOf("-")+1)); String str3003=(str67.toString()).substring(((BS.toString()).indexOf("-")+2),(BS.length()+1)); int num2002=Integer.parseInt(str2002); int num3002=Integer.parseInt(str3003); int sum22=num2002-num3002; String str53=Integer.toString(sum22); // System.out.println("sum="+sum22); Lb1.setText(str53); BS=new StringBuffer("");k=-1; BS.append(str53); }} if(str1002.indexOf(".")!=-1) { int num1002=str1002.indexOf('-');//取得*号的位置 StringBuffer str66=new StringBuffer(str1002); // System.out.println("num1002="+num1002); if(num1002>0){ String str2002=str1002.substring(0,num1002); String str3003=str1002.substring(num1002+1,BS.length()); float num2002=Float.parseFloat(str2002); float num3002=Float.parseFloat(str3003); float sum22=(float)(num2002-num3002); String str53=Float.toString(sum22); // System.out.println("sum="+sum22); Lb1.setText(str53); BS=new StringBuffer("");k=-1; BS.append(str53);} if(num1002==0) { BS.deleteCharAt(0);//删除第一个减号 (BS.toString()).indexOf("-");//取得第二个减号的位置 StringBuffer str68=new StringBuffer(BS.toString()); //这里必须引入其他的字符串变量来储存,关键在于获得不是第一个减号的位置 str68.insert(0,'-'); String str2002=(str68.toString()).substring(0,((BS.toString()).indexOf("-")+1)); String str3003=(str68.toString()).substring(((BS.toString()).indexOf("-")+2),(BS.length()+1)); float num2002=Float.parseFloat(str2002); float num3002=Float.parseFloat(str3003); float sum22=(float)(num2002-num3002); String str53=Float.toString(sum22); // System.out.println("sum="+sum22); Lb1.setText(str53); BS=new StringBuffer("");k=-1; BS.append(str53); } } }} if(str1=="清零")//删除键 { TF.setText(""); Lb12.setText(".0"); Lb2.setText(".0"); Lb3.setText(".0"); Lb4.setText(".0"); Lb1.setText(".0"); Lb5.setText("无"); Lb10.setText(".0"); BS=new StringBuffer(""); //System.out.println("str22="+str22);//测试 //归无,即使是把对想的内容给删除了,也就是数组的大小事零,但是调用的那个文本并没有归零, //System.out.println("str22="+str22); Lb2.setText(".0"); Lb3.setText(".0");//在清除BS的同Lb3也会跟着归零 try{FileWriter FP=new FileWriter("D:\\java\\10.txt"); FP.write(str9);//不能写整形数组,只能写字符类型的数组 FP.flush(); FP.close(); k=-1; } //在这里给k赋值,若果计算执行,那么k没有办法在=号哪里进行设置,这里可以设置一下原值的赋值,错误那么可以通过归原值进行调节} //所以每个语句执行完之后都得注意把值给赋回去 catch(Exception o) {Lb5.setText("已经没有数据可删除!");} } try{ if(str1=="后退") //在这里拦住的思路,没按一下“后退”按钮就删最后一个,从BS.length(); //得到的长度是不能直接用来做字符串索引值的,因为达到的长度是整数,要应用于删除字符上,应该减一,不然会出现超出异常 { i++; Lb12.setText(".0");//余数清零上面的标签 if(i显示剩下的字符串下方标签 Lb3.setText(str67); } if(BS.length()==0) { Lb1.setText(".0");} i=-1; //要加上这个,因为没按一次后退都会加上一,总有一次会超过字符长度,执行完相应的 语句之后将它赋回原值 }} catch(Exception p) { Lb5.setText("已经没有数据可删除!"); } if(str1=="颜色") { l++; if(l==0) {frm1.setBackground(Color.yellow); Lb2.setBackground(Color.yellow); Lb3.setBackground(Color.yellow); Lb4.setBackground(Color.yellow); Lb5.setBackground(Color.yellow); Lb6.setBackground(Color.yellow); Lb7.setBackground(Color.yellow); Lb8.setBackground(Color.yellow); Lb9.setBackground(Color.yellow); Lb11.setBackground(Color.yellow); Lb12.setBackground(Color.yellow); } if(l==1) {frm1.setBackground(Color.pink); Lb2.setBackground(Color.pink); Lb3.setBackground(Color.pink); Lb4.setBackground(Color.pink); Lb5.setBackground(Color.pink); Lb6.setBackground(Color.pink); Lb7.setBackground(Color.pink); Lb8.setBackground(Color.pink); Lb9.setBackground(Color.pink); Lb11.setBackground(Color.pink); Lb12.setBackground(Color.pink); } if(l==2) {frm1.setBackground(Color.red);Lb2.setBackground(Color.red); Lb3.setBackground(Color.red); Lb4.setBackground(Color.red); Lb5.setBackground(Color.red); Lb6.setBackground(Color.red); Lb7.setBackground(Color.red); Lb8.setBackground(Color.red); Lb9.setBackground(Color.red); Lb11.setBackground(Color.red); Lb12.setBackground(Color.red); } if(l==3) {frm1.setBackground(Color.gray);Lb2.setBackground(Color.gray); Lb3.setBackground(Color.gray); Lb4.setBackground(Color.gray); Lb5.setBackground(Color.gray); Lb6.setBackground(Color.gray); Lb7.setBackground(Color.gray); Lb8.setBackground(Color.gray); Lb9.setBackground(Color.gray); Lb11.setBackground(Color.gray); Lb12.setBackground(Color.gray); } if(l==4) {frm1.setBackground(Color.orange);Lb2.setBackground(Color.pink); Lb3.setBackground(Color.orange); Lb4.setBackground(Color.orange); Lb5.setBackground(Color.orange); Lb6.setBackground(Color.orange); Lb7.setBackground(Color.orange); Lb8.setBackground(Color.orange); Lb9.setBackground(Color.orange); Lb11.setBackground(Color.orange); Lb12.setBackground(Color.orange); } if(l==5) {frm1.setBackground(Color.white);Lb2.setBackground(Color.white); Lb3.setBackground(Color.white); Lb4.setBackground(Color.white); Lb5.setBackground(Color.white); Lb6.setBackground(Color.white); Lb7.setBackground(Color.white); Lb8.setBackground(Color.white); Lb9.setBackground(Color.white); Lb11.setBackground(Color.white); Lb12.setBackground(Color.white); } if(l==6) {frm1.setBackground(Color.blue);l=-1;Lb2.setBackground(Color.blue); Lb3.setBackground(Color.blue); Lb4.setBackground(Color.blue); Lb5.setBackground(Color.blue); Lb6.setBackground(Color.blue); Lb7.setBackground(Color.blue); Lb8.setBackground(Color.blue); Lb9.setBackground(Color.blue); Lb11.setBackground(Color.blue); Lb12.setBackground(Color.blue); } } }//内部类的函数 }//内部类 public static class shijian2 extends WindowAdapter { public void windowClosing(WindowEvent o) { System.exit(0); } } static class shijian3 implements TextListener { public void textValueChanged(TextEvent q) { Lb12.setText(".0"); try{BS=new StringBuffer(TF.getText());//写入BS,改变BS的值 FileWriter FY=new FileWriter("D:\\java\\10.txt");FY.write(TF.getText());FY.flush();}//同写入同一个文本内相当于拥有两份运算的数据,当按面板是也会将文本覆盖,不清空 catch(Exception u) {System.out.println("出错了");} Lb2.setText(Integer.toString(BS.length())); Lb3.setText(Integer.toString(BS.length())); Lb4.setText(Integer.toString(BS.length())); Lb5.setText(Integer.toString(BS.length())); Lb1.setText(BS.toString()); //让数字输入的同取得BS字符串BS也是整个程序的关键,整个程序围绕BS进行,包括加入修改,新添 Lb10.setText(BS.toString()); } } }//主类 Ps:QQ:550119320
import java.awt.*;//导入AWT包
import java.awt.event.*;//导入事件处理包
import javax.swing.*;
//继承一个
public class Untitled1
extends Frame {
//构造各种组件
TextField t = new TextField(" ");
TextField tt = new TextField(" ");
Label l = new Label(" 我的计算器");
Panel p = new Panel();
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
Panel p4 = new Panel();
Panel p5 = new Panel();
Panel p6 = new Panel();
Button bbb = new Button("EXIT");
Button b0 = new Button("0");
Button b1 = new Button("1");
Button b2 = new Button("2");
Button b3 = new Button("3");
Button b4 = new Button("4");
Button b5 = new Button("5");
Button b6 = new Button("6");
Button b7 = new Button("7");
Button b8 = new Button("8");
Button b9 = new Button("9");
Button ba = new Button("+");
Button bb = new Button("-");
Button bc = new Button("*");
Button bd = new Button("/");
Button be = new Button(".");
Button bg = new Button("sin");
Button bh = new Button("cos");
Button bi = new Button("tan");
Button bj = new Button("sqrt");
Button bk = new Button("CLEAR");
Button bl = new Button("exp");
Button bm = new Button("log");
Button bn = new Button("abs");
Button bf = new Button("=");
//声明几个变量
String s1, s2, s3;
double u1, u2, u3;
char op;
//设置各种方法参数
public Untitled1() {
this.setTitle("我的计算器");
this.setLayout(new GridLayout(7, 1, 5, 5));
this.setBackground(Color.blue);
t.setFont(new java.awt.Font("Dialog", 0, 30));
l.setFont(new java.awt.Font("Dialog", 0, 30));
tt.setFont(new java.awt.Font("Dialog", 0, 30));
//为按钮和面板添加底色
//添加面板
this.add(p);
this.add(p1);
this.add(p2);
this.add(p3);
this.add(p4);
this.add(p5);
this.add(p6);
//设置面板
p.setLayout(new BorderLayout());
p.add(l);
p1.setLayout(new BorderLayout());
p1.add(t);
p2.setLayout(new GridLayout(1, 6, 5, 5));
p3.setLayout(new GridLayout(1, 6, 5, 5));
p4.setLayout(new GridLayout(1, 6, 5, 5));
p5.setLayout(new GridLayout(1, 6, 5, 5));
p6.setLayout(new GridLayout(1, 7, 5, 5));
//添加按钮
p2.add(b0);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(bg);
p2.add(bk);
p3.add(b4);
p3.add(b5);
p3.add(b6);
p3.add(b7);
p3.add(bh);
p3.add(bl);
p4.add(b8);
p4.add(b9);
p4.add(ba);
p4.add(bb);
p4.add(bm);
p4.add(bi);
p5.add(bc);
p5.add(bd);
p5.add(be);
p5.add(bf);
p5.add(bj);
p5.add(bn);
p6.add(bbb);
//添加各种监听
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "0";
t.setText(s);
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "1";
t.setText(s);
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "2";
t.setText(s);
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "3";
t.setText(s);
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "4";
t.setText(s);
}
});
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "5";
t.setText(s);
}
});
b6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "6";
t.setText(s);
}
});
b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "7";
t.setText(s);
}
});
b8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "8";
t.setText(s);
}
});
b9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += "9";
t.setText(s);
}
});
bg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
double b = Double.parseDouble(s);
b *= Math.PI / 180;
b = Math.sin(b);
b = b * 10000;
b = Math.rint(b);
b = b / 10000;
t.setText("" + b);
}
});
bh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
double b = Double.parseDouble(s);
b *= Math.PI / 180;
b = Math.cos(b);
b = b * 10000;
b = Math.rint(b);
b = b / 10000;
t.setText("" + b);
}
});
bi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
double b = Double.parseDouble(s);
b *= Math.PI / 180;
b = Math.tan(b);
b = b * 10000;
b = Math.rint(b);
b = b / 10000;
t.setText("" + b);
}
});
bl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
double b = Double.parseDouble(s);
b = Math.exp(b);
b = b * 10000;
b = Math.rint(b);
b = b / 10000;
t.setText("" + b);
}
});
bj.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
double b = Double.parseDouble(s);
b = Math.sqrt(b);
b = b * 10000;
b = Math.rint(b);
b = b / 10000;
t.setText("" + b);
}
});
//开始设置功能键
bm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
double b = Double.parseDouble(s);
b = Math.log(b);
b = b * 10000;
b = Math.rint(b);
b = b / 10000;
t.setText("" + b);
}
});
bn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
double b = Double.parseDouble(s);
b = Math.abs(b);
b = b * 10000;
b = Math.rint(b);
b = b / 10000;
t.setText("" + b);
}
});
bk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
t.setText("");
}
});
ba.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
s1 = t.getText();
op = '+';
t.setText("");
}
});
bb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
s1 = t.getText();
op = '-';
t.setText("");
}
});
bc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
s1 = t.getText();
op = '*';
t.setText("");
}
});
bd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
s1 = t.getText();
op = '/';
t.setText("");
}
});
be.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = t.getText();
s += ".";
t.setText(s);
}
});
bf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
s2 = t.getText();
double u1 = Double.parseDouble(s1);
double u2 = Double.parseDouble(s2);
if (op == '+')
u3 = u1 + u2;
if (op == '-')
u3 = u1 - u2;
if (op == '*')
u3 = u1 * u2;
if (op == '/')
u3 = u1 / u2;
t.setText("" + u3);
}
});
//添加退出按钮
bbb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
//设置主函数
public static void main(String[] args) {
Untitled1 w = new Untitled1();
w.pack();
w.show();
}
}
chatRoom.zip 聊天室聊天室服务端 package chatroom; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * 聊天室服务器端 ChatRoomServer类 * * @version 1.01, 09/04/10 */ public class ChatRoomServer { private ServerSocket ss; /* 存放Socket的集合hs */ private HashSet hs; public ChatRoomServer() { JFrame jf = new JFrame(); do { /* * 弹出输入对话框,提示输入服务器需要绑定的端口号 */ int port = Integer.parseInt(JOptionPane.showInputDialog(jf, "bind port:")); try { ss = new ServerSocket(port); System.out.println("server start success,now listening port:" + port); } catch (Exception e) { /* 弹出确认框进行确认 */ int op = JOptionPane.showConfirmDialog(jf, // 指定是在jf弹出确认框 "bind fail,retry?", // 框体内容 "bind fail", // 对话框的标题 JOptionPane.YES_NO_OPTION); // 确认框按钮项 /* 如果选择'否',则退出程序 */ if (op == JOptionPane.NO_OPTION) { System.exit(1); } /* 打印异常栈信息 */ e.printStackTrace(); } } while (ss == null); /* 创建HashSet,用来存放Socket对象 */ hs = new HashSet(); while (true) { try { /* 获得Socket,网络阻塞,等待客户端的连接 */ Socket s = ss.accept(); /* 一旦客户端连接上,则加入HashSet,便于维护 */ hs.add(s); /* 启动一个服务线程,为客户端服务 */ new ServerThread(s).start(); } catch (IOException e) { e.printStackTrace(); } } } /** * 成员内部类,服务线程类 */ class ServerThread extends Thread { private Socket s; public ServerThread(Socket s) { this.s = s; } @Override public void run() { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(s .getInputStream())); while (true) { /* 从网络读取客户端发出的消息 */ String str = br.readLine(); /* * 客户退出的处理逻辑 规则:以"%EXIT_CHATROOM%"开头的消息为客户退出标记 */ if (str.charAt(0) == '%') { String com = str.split("%")[1]; if (com.equals("EXIT_CHATROOM")) { hs.remove(s); printMessage(str.split("%")[2] + ",leave!"); s.close(); break; } } else { /* 正常情况,直接向客户端群发消息 */ printMessage(str); } } } catch (IOException e) { e.printStackTrace(); } } /* * 负责为客户端群发消息 */ private void printMessage(String mes) { System.out.println(mes); try { /* 遍历所有Socket */ for (Socket s : hs) { PrintStream ps = new PrintStream(s.getOutputStream()); /* 产生发消息的刻 */ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); /* 向客户端发消息,消息结构为mes [yyyy-MM-dd HH:mm:ss] */ ps.println(mes + " [" + sdf.format(date) + "]"); /* 注意需要及flush,清空缓冲区 */ ps.flush(); } } catch (IOException e) { e.printStackTrace(); } } } /* * 主方法,启动聊天室服务器端 */ public static void main(String[] args) { new ChatRoomServer(); } } 客户端窗体 package chatroom; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; /** * 客户端窗口ChatRoomClientFrame类 负责客户端的视图表示、事件处理等逻辑 作为一个窗口,所以本类继承自JFrame * 为了实现事件处理,本类实现了ActionListener接口 * * @version 1.01, 09/04/10 */ public class ChatRoomClientFrame extends JFrame implements ActionListener { private static final long serialVersionUID = 3484437496861281646L; private JTextArea jta; // 多行文本域 private JLabel label; // 文本标签 private JTextField jtf; // 单行文本框 private JButton jb; // 按钮 private Socket socket; // socket 套接字 private String name; // 用户名 /* * ChatRoomClientFrame构造方法,负责初始化以及添加事件处理 */ public ChatRoomClientFrame(String name, Socket socket) { super("chatroom"); Font f = new Font("楷体", Font.BOLD, 20); /* 设置字体 */ jta = new JTextArea(10, 10); /* 创建10行10列的空多行文本域 */ jta.setEditable(false); /* 设置多行文本域为不可编辑 */ jta.setFont(f); /* 设置多行文本域字体 */ label = new JLabel(name + ":"); /* 创建带有用户名的文本标签 */ label.setFont(f); /* 设置文本标签字体 */ jtf = new JTextField(25); /* 创建单行文本框 */ jtf.setFont(f); /* 设置单行文本框字体 */ jb = new JButton("send"); /* 创建按钮 */ this.name = name; this.socket = socket; init(); /* 初始化,设置组件关系 */ addEventHandler(); /* 为组件添加事件监听 */ } /* * 初始化组件关系方法,供构造方法调用 */ private void init() { JScrollPane jsp = new JScrollPane(jta); this.add(jsp, BorderLayout.CENTER); JPanel jp = new JPanel(); jp.add(label); jp.add(jtf); jp.add(jb); this.add(jp, BorderLayout.SOUTH); } /* * 负责为各组件添加事件处理机制 */ private void addEventHandler() { jb.addActionListener(this); // 为jb添加事件监听,JButton点击触发事件 jtf.addActionListener(this); // 为jtf添加事件监听,JTextField敲回车触发事件 /* 设置JFrame默认关闭状态:DO_NOTHING_ON_CLOSE */ this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); /* 为JFrame添加窗口事件监听 */ this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { /* 弹出确认框进行交互 */ int op = JOptionPane.showConfirmDialog( ChatRoomClientFrame.this, "exit?", "exit", JOptionPane.YES_NO_OPTION); if (op == JOptionPane.YES_OPTION) { try { PrintStream ps = new PrintStream(socket .getOutputStream()); /* 向服务器发送以%EXIT_CHATROOM%name为格式的串,代表退出信号 */ ps.println("%EXIT_CHATROOM%" + name); /* 注意需要及flush */ ps.flush(); try { Thread.sleep(168); // 进行延控制,防止提前关闭socket } catch (InterruptedException e) { e.printStackTrace(); } socket.close(); // 关闭客户端socket ps.close(); // 关闭流 } catch (IOException e) { e.printStackTrace(); } System.exit(1); // 退出程序 } } }); } /* * 实现事件处理方法 */ public void actionPerformed(ActionEvent ae) { try { PrintStream ps = new PrintStream(socket.getOutputStream()); ps.println(name + ": " + jtf.getText()); ps.flush(); /* 清空jtf内容 */ jtf.setText(""); } catch (IOException e) { e.printStackTrace(); } } /* * 显示并执行窗口逻辑 */ public void showMe() { this.pack(); // 自动调整此窗口的大小 this.setVisible(true); // 设置窗口可见 /* * 启动线程,负责接收服务器端发来的消息 */ new Thread() { @Override public void run() { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(socket .getInputStream())); while (true) { /* 从网络读取服务器发出的数据 */ String str = br.readLine(); /* 对JTextArea进行追加消息 */ jta.append(str + "\n"); } } catch (IOException e) { e.printStackTrace(); } } }.start(); } } 客户端 package chatroom; import java.io.PrintStream; import java.net.Socket; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * 聊天室客户端 ChatRoomClient * * @version 1.01, 09/04/10 */ public class ChatRoomClient { private String name; // 用户名 private Socket socket; // Socket 套接字 private ChatRoomClientFrame frame; // 组合复用 ChatRoomClientFrame /* * ChatRoomClient构造方法,负责构造客户端表示逻辑 */ public ChatRoomClient() { JFrame jf = new JFrame(); /* * 弹出用户输入对话框,提示用户输入服务器的IP地址 返回相应字符串形式,存于变量serverIP,缺省值127.0.0.1 */ String serverIP = JOptionPane.showInputDialog(jf, "server IP:", "127.0.0.1"); /* * 弹出用户输入对话框,提示用户输入服务器端口号 转化为int形式返回,存于变量serverPort */ int serverPort = Integer.parseInt(JOptionPane.showInputDialog(jf, "port:")); /* * 弹出用户输入对话框,提示用户输入用户名,存于成员属性name */ name = JOptionPane.showInputDialog(jf, "your name:"); try { /* 通过IP和Port,与服务器端建立连接 */ socket = new Socket(serverIP, serverPort); /* 给服务器发消息 */ PrintStream ps = new PrintStream(socket.getOutputStream()); ps.println(name + ",login !"); } catch (Exception e) { JOptionPane.showMessageDialog(jf, "fail,check the connection!"); e.printStackTrace(); System.exit(1); } /* * 创建ChatRoomClientFrame,进行客户端主窗口的显示 */ frame = new ChatRoomClientFrame(name, socket); frame.showMe(); } /* * 主方法,启动聊天室客户端 */ public static void main(String[] args) { new ChatRoomClient(); } }
package com.Login; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.UIManager; import com.jdbc.DB; import com.window.Main; public class Login extends JFrame { private JPanel contentPane; private Point pressedPoint; /*private final class LoginActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { // 显示窗体的登录进度面板 getGlassPane().setVisible(true); } }*/ public static void main(String[] args) { try { UIManager .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Throwable e) { e.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { try { Login frame = new Login (); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public Login(){ super("登录"); addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { do_this_windowOpened(e); } }); setUndecorated(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(380,280); setIconImage(new ImageIcon("image\\tubiao.png").getImage()); Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize=this.getSize(); setLocation((displaySize.width - frameSize.width) / 2+(frameSize.width)/2,(displaySize.height - frameSize.height) / 2); contentPane=new JPanel(); contentPane.setBorder(BorderFactory.createLineBorder(Color.BLACK)); //设置边框为无 contentPane.setLayout(new BorderLayout(0,0));//设置contentPane的布局 setContentPane(contentPane);// JPanel topPanel = new JPanel(){ public void paintComponent(Graphics g) { g.drawImage(new ImageIcon("image\\logintop1.jpg").getImage(), 0, 0,500,48, null); super.paintComponent(g); } };//标题栏panel topPanel.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { do_topPanel_mouseDragged(e); } }); topPanel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { do_topPanel_mousePressed(e); } }); topPanel.setOpaque(false);//设置背景透明 topPanel.setPreferredSize(new Dimension(500,30)); topPanel.setLayout(null); JPanel panel = new JPanel(); panel.setBounds(312, 0, 66, 15); panel.setOpaque(false); topPanel.add(panel); panel.setLayout(new GridLayout(1, 0, 0, 0)); JButton button = new JButton(""); button.setRolloverIcon(new ImageIcon("image\\button4.png")); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button_itemStateChanged(e); } }); button.setFocusPainted(false);// 取消焦点绘制 button.setBorderPainted(false);// 取消边框绘制 button.setContentAreaFilled(false);// 取消内容绘制 button.setIcon(new ImageIcon("image\\button4-1.png")); panel.add(button); JButton button_2 = new JButton(""); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button_2_actionPerformed(e); } }); button_2.setRolloverIcon(new ImageIcon("image\\button3.png")); button_2.setFocusPainted(false); button_2.setContentAreaFilled(false); button_2.setBorderPainted(false); button_2.setIcon(new ImageIcon("image\\button3-1.png")); panel.add(button_2); contentPane.add(topPanel, BorderLayout.NORTH); JPanel backgroundPanel = new JPanel(){ public void paintComponent(Graphics g) { g.drawImage(new ImageIcon("image\\loginframe1.jpg").getImage(), 0, 0,500,300, null); super.paintComponent(g); } };//panel backgroundPanel.setLayout(new GridLayout(1,1)); backgroundPanel.setOpaque(false); JPanel panel1 = new JPanel() { public void paintComponent(Graphics g) { g.drawImage(new ImageIcon("image\\4.png").getImage(), 0, 0,420,200, null); super.paintComponent(g); } }; panel1.setLayout(null); panel1.setOpaque(false); JLabel label1=new JLabel("用户名:"); JLabel label2=new JLabel("密 码:"); final JTextField text1=new JTextField(15); final JPasswordField text2=new JPasswordField(15); label1.setBounds(80,60,60,30); text1.setBounds(160, 60, 150,30); label2.setBounds(80,120,60,30); text2.setBounds( 160, 120, 150, 30); panel1.add(label1); panel1.add(text1); panel1.add(label2); panel1.add(text2); backgroundPanel.add(panel1); contentPane.add(backgroundPanel, BorderLayout.CENTER); JPanel panel2 =new JPanel(); //panel2.setPreferredSize(new Dimension(380,40)); panel2.setLayout(null); panel2.setOpaque(false); JButton button1=new JButton("登录"); JButton button2=new JButton("取消"); MouseAdapter mouseAdapter = new MouseAdapter() {// 创建鼠标事件监听器 private Rectangle sourceRec;// 创建矩形对象 @Override public void mouseEntered(MouseEvent e) { JButton button = (JButton) e.getSource();// 获取事件源按钮 sourceRec = button.getBounds();// 保存按钮大小 button.setBounds(sourceRec.x-5, sourceRec.y-5, sourceRec.width + 10, sourceRec.height + 10);// 把按钮放大 super.mouseEntered(e); } @Override public void mouseExited(MouseEvent e) { JButton button = (JButton) e.getSource();// 获取事件源按钮 if (sourceRec != null) {// 如果有备份矩形则用它恢复按钮大小 button.setBounds(sourceRec);// 设置按钮大小 } super.mouseExited(e); } }; button1.addMouseListener(mouseAdapter); button2.addMouseListener(mouseAdapter); button1.setBackground(new Color(154,216,230)); button2.setBackground(new Color(154,216,230)); //button1.setBorder(BorderFactory.createLineBorder(Color.blue) ); //button1.setBorder(new EmptyBorder(10, 0, 0, 0));// 顶部留白:40pix //button2.setBorder(new EmptyBorder(10, 0, 0, 0));// 顶部留白:40pix button1.setBounds(190, 9,70, 30); button2.setBounds(280, 9,70, 30); panel2.add(button1); panel2.add(button2); panel2.setBounds(0, 200, 380, 50); panel1.add(panel2); //button1.addActionListener( new LoginActionListener()); button1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs=null; Statement stmt=null; try{ con=DB.getConnection(); pstmt = con.prepareStatement("select *from tb_manager where id=? and password=?"); pstmt.setString(1, text1.getText()); pstmt.setString(2, text2.getText()); rs=pstmt.executeQuery(); JOptionPane pane=new JOptionPane(); if(rs.next()) { // new LoginActionListener(); pane.showMessageDialog(null, "登录成功!"); // new Main(); new Main(); dispose();// 销毁窗体 con.close(); } else if(text1.getText().equals("")||text2.getText().equals("")) { pane.showMessageDialog(null, " 登录失败!用户名或密码不能为空,请重新输入!"); text1.setText(""); text2.setText(""); } else { pane.showMessageDialog(null, "登录失败,你输入的用户名或密码错误,请重新输入!"); text1.setText(""); text2.setText(""); } }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DB.close(pstmt); DB.close(pstmt); } } } ); button2.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } } ); } protected void do_button_itemStateChanged(ActionEvent e) { setExtendedState(JFrame.ICONIFIED);// 窗体最小化 } protected void do_button_2_actionPerformed(ActionEvent e) { dispose();// 销毁窗体 } protected void do_topPanel_mousePressed(MouseEvent e) { pressedPoint = e.getPoint();// 记录鼠标坐标 } protected void do_topPanel_mouseDragged(MouseEvent e) { Point point = e.getPoint();// 获取当前坐标 Point locationPoint = getLocation();// 获取窗体坐标 int x = locationPoint.x + point.x - pressedPoint.x;// 计算移动后的新坐标 int y = locationPoint.y + point.y - pressedPoint.y; setLocation(x, y);// 改变窗体位置 } protected void do_this_windowOpened(WindowEvent e) { final int height = getHeight();// 记录窗体高度 new Thread() {// 创建新线程 public void run() { Rectangle rec = getBounds(); for (int i = 0; i < 385; i += 10) {// 循环拉伸窗体 setBounds(rec.x - i / 2, rec.y, i, height);// 不断设置窗体大小与位置 try { Thread.sleep(15);// 线程休眠10毫秒 } catch (InterruptedException e1) { e1.printStackTrace(); } } } }.start();// 启动线程 } }

50,331

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧