攀枝花学院Java实验六 Java Swing(上课用)
- 格式:docx
- 大小:153.35 KB
- 文档页数:9
Swing(曹雯君)Swing是一个为Java设计的图形用户界面(GUI)工具包。
Swing是Java API的一部分。
Swing包括了GUI的元器件,如:文本框,按钮,分隔窗格和表。
Swing用于提供一组“轻量级”(全部是 Java 语言)组件,它们用纯Java写成,所以同样可以跨平台使用。
轻量级元件的缺点则是执行速度较慢,优点就是可以在所有平台上采用统一的行为。
1. 30分钟快速上手1.1 Swing和AWT的关系与区别•关系Swing是一个用于开发JAVA应用程序用户界面的开发工具包。
以抽象窗口包(AWT)为基础使跨平台应用程序可以使用任何可插拔的外观风格。
Swing API的大部分是AWT的补充扩展而不是直接的替代。
Swing用来绘制轻量级组件的核心渲染功能是由Java 2D提供的,这是AWT的一部分。
然而,轻量级和重量级组件在同一个应用中使用会导致Z-order不兼容。
•区别Swing为基于窗体的GUI应用开发设计,为Java跨平台特性提供了卓越的支持,它完全没有本地代码,不受操作系统的影响,做到了真正的跨平台应用,甚至能够提供本地窗口系统不支持的其他特性。
因此比AWT具有更强的实用性,同时比AWT程序拥有更加精致的外观感受。
AWT只提供基本的组件,使很多设计变得复杂,且无法在不同的平台下保持显示风格的一致性。
例如:如果建立一个按钮(Button)对象,就会有一个按钮对象会请求底层操作系统创建一个真正的按钮。
即在WindowsNT上执行那么创建的就是WindowsNT按钮;在Linux 上执行,那么创建的就是Linux按钮。
因此AWT组件外观会受到底层操作系统的影响。
1.2 Swing操作步骤1.2.1 导入Swing包import javax.swing.*;大部分的Swing程序用到AWT的基础底层结构和事件模型,因此需要导入两个包:import java.awt.*;import java.awt.event.*;如果图形界面中包括了事件处理,那么还需要导入事件处理包:import.javax.swing.event.*;1.2.2 选择界面风格Swing允许选择程序的图形界面风格常用的有Java风格,Windows风格等。
Java桌面应用程序的开发:Swing、SWT和JavaFX一、引言在计算机科学领域,Java 是一门非常流行的编程语言,被广泛应用于各个领域。
除了用于开发Web 应用程序和移动应用程序之外,Java 还被用于开发桌面应用程序。
本文将介绍Java 桌面应用程序开发的三种主要技术:Swing、SWT 和JavaFX。
二、SwingSwing 是Java 提供的一套UI 组件,用于开发桌面应用程序。
它是Java Foundation Classes(JFC)的一部分,提供了丰富的图形用户界面组件,如按钮、文本框、标签等。
Swing 的特点是跨平台,可以在不同的操作系统上运行,并且具有良好的可定制性。
Swing 的开发相对简单,只需要导入相应的包,创建组件并将其添加到容器中即可。
例如,可以使用JFrame 类创建一个窗口,并在窗口中添加按钮和标签。
同时,Swing 还提供了丰富的布局管理器,如BorderLayout、FlowLayout 和GridBagLayout,用于管理组件的排布和布局。
三、SWTSWT(Standard Widget Toolkit)是IBM 开发的一套用于创建桌面应用程序的Java 组件库。
与Swing 不同,SWT 是基于本地操作系统的本机窗口小部件(native widget)实现的,这意味着SWT 应用程序使用操作系统提供的原生控件,具有更好的性能和更好的外观。
要使用SWT 开发桌面应用程序,需要导入相应的SWT 包,并创建Display 和Shell 对象。
Display 对象表示应用程序的显示器,而Shell 对象则表示应用程序的窗口。
通过在Shell 对象中添加按钮、文本框和标签等控件,即可创建一个简单的SWT 程序。
与Swing 类似,SWT 也提供了布局管理器,如GridLayout 和FillLayout,用于管理控件的排布。
四、JavaFXJavaFX 是Oracle 开发的一套用于创建富客户端应用程序的框架。
T u t o r i a l5TopicsInterfaceso What is an interfaceo ActionListenerIntroduction to Java Swingo What is Swingo SwingApplicationo Step-by-Step guideDesign ProblemsI n t e r f a c eWhat is an InterfaceAn interface is a collection of method declarations which can be implemented by classesAn interface describes what classes should do, without specifying how they should do itThe how will be defined in the classes that implement the interfaceEach class defines the implementation differentlyA class can implement one or more interfacesAn interface can contain both methods and constantsTo use an interface, a class mustImplement that interfaceDefine ALL methods in that interfaceA c t i o n L i s t e n e rActionListener is a Java interface implemented by many GUI components, such as buttons. It has only one method – actionPerformed. Here is its definition:public Interface ActionListener {public void actionPerformed(ActionEvent e)}The following example is a Java GUI application called SwingApplication which has a “button-click” counter – every time user clicks the button, the counter increases by 1. We will explain how to create the GUI in the next section. Here, we just want to demonstrate how one should implement ActionListener.class SwingApplication implements ActionListener{………………….……………………int numClicks = 0; //”click-counter”JLabel label = new JLabel(“Number of button clicks: ” + numClicks);JButton button = new JButton("I'm a Swing button!");button.addActionListener(this); //Add an actionListener to the button……………………public void actionPerformed(ActionEvent e){numClicks++;label.setText(“Number of button clicks: “ + numClicks);}}Here, the class SwingApplication implements the ActionListener interface. Inside the class definition, it re-defined the actionPerformed method: every time user clicks the button, the counter in the message increases by 1.Introducing the Java SwingWhat is SwingThe Swing package is part of the JavaTM Foundation Classes (JFC) in the Java platform. The JFC encompasses a group of features to help people build GUIs. Here are some commonly-used Swing components:ButtonsCombo boxListDialogScroll paneMenuTable Frame S w i n g A p p l i c a t i o nThe SwingApplication is an example we pulled from the Java Tutorial. As mentioned earlier, it is a “button-click” counter - every time the user clicks the button, the label is updated showing the counter increasing by 1.SwingApplication has four Swing components:A frame (JFrame). The frame is a top-level container. It provides a place forother Swing components to paint themselves. The other commonly used top-level containers are dialogs (JDialog) and applets (JApplet).A panel (JPanel). The panel is an intermediate container. Its only purpose is tosimplify the positioning of the button and label. Other intermediate Swingcontainers include JScrollPane (scroll panes) and JTabbedPane (tabbed panes)A button (JButton) and a label (JLabel). The button and label are atomiccomponents -- components that exist not to hold other Swing components, butto interface with the user. The Swing API provides many atomic components,including combo boxes (JComboBox), text fields (JTextField), and tables(JTable).Here is a diagram of the containment hierarchy for the window shown by SwingApplicationHere is the code that adds the button and label to the panel, and the panel to the content pane:frame = new JFrame(...);pane = new JPanel();button = new JButton(...);label = new JLabel(...);pane.add(button);pane.add(label);frame.getContentPane().add(pane, BorderLayout.CENTER);Step-by-step guideHere is a step-by-step guide of how to create this SwingApplication: Setting up the top-level containerSetting up buttons and labelsAdding components to containersHandling eventsNext we will discuss each step in length.Setting up the top-level container//Create the top-level container titled “SwingApplicatoin”JFrame frame = new JFrame("SwingApplication");..................frame.pack();frame.setVisible(true);Setting up buttons and labels//Create a buttonJButton button = new JButton("I'm a Swing button!");//Create a labelJLabel label = new JLabel(“Number of button clicks: “ + "0 ");//Set the label textint numClicks = 0;label.setText(“Number of button clicks: “ + numClicks);Adding components to containersJPanel pane = new JPanel();pane.setLayout(new GridLayout(0, 1));pane.add(button);pane.add(label);frame.getContentPane().add(pane, BorderLayout.CENTER);Handling eventsWe will discuss this feature in the next tutorial.D e s i g n P r o b l e mInterfaceYou are hired to develop an accounting program that calculates the weekly salary of three types of employees: management, union workers, and contractors.Each management employee has a social security number (SSN), name, title, and salary. There is no overtime pay for management employeesEach union worker has a SSN, name, hourly rate, and hours worked. Union rules require that we pay union workers overtime, which is 1.5 times the hourly rate for the hours they put in beyond 40Each contractor has a SSN, name, agency, hours worked, and hourly rate. We don’t have to pay contractors at a higher rate for overtime. However, there is a cap on how much each contractor can make each week. Currently, the cap is 60 * hourly rate.Please define a set of classes that model this situation. Here are some requirements: Create an abstract class called Employee which has a method called printCreate an interface Compensation which has one method called calculatePayCreate three subclasses: Management, UnionWorker, Contractor which inherit from EmployeeEach subclass will implement the Compensation interfaceEach subclass must print all its information. For example, here is the printout for a manager:SSN: 1111 Name: Wen XiaoSalary: $9500Basic Swing componentDownload the code of SwingApplication.java and add a menu bar to the frame. The menu bar has two menus: File and Edit. Within File, there are 3 menu items: Open, Save, and Exit. Within Edit, there are 2 menu items: Copy and Paste. You don’t need to implement any event-handling functions, just the GUI. (There is a short course on how to use menus at/docs/books/tutorial/uiswing/components/menu.html. Make sure the program compiles and runs.。
第Ⅰ部分:实验指导实验1:Java开发环境J2SE一、实验目的(1)学习从网络上下载并安装J2SE开发工具。
(2)学习编写简单的Java Application程序.(3)了解Java源代码、字节码文件,掌握Java程序的编辑、编译和运行过程。
二、实验任务从网络上下载或从CD-ROM直接安装J2SE开发工具,编写简单的Java Application程序,编译并运行这个程序。
三、实验内容1.安装J2SE开发工具Sun公司为所有的java程序员提供了一套免费的java开发和运行环境,取名为Java 2 SDK,可以从上进行下载。
安装的时候可以选择安装到任意的硬盘驱动器上,例如安装到C:\j2sdk1.4.1_03目录下。
教师通过大屏幕演示J2SE的安装过程,以及在Windows98/2000/2003下环境变量的设置方法。
2.安装J2SE源代码编辑工具Edit Plus教师通过大屏幕演示Edit Plus的安装过程,以及在Windows98/2000/2003操作系统环境下编辑Java 原程序的常用命令的用法。
3.编写并编译、运行一个Java Application程序。
创建一个名为HelloWorldApp的java Application程序,在屏幕上简单的显示一句话"老师,你好!"。
public class HelloWorldApp{public static void main(String[] args){System.out.println("老师,你好!");}}4.编译并运行下面的Java Application程序,写出运行结果。
1:public class MyClass {2:private int day;3:private int month;4:private int year;5:public MyClass() {6:day = 1;7:month = 1;8:year = 1900;9:}10:public MyClass(int d,int m,int y) {11:day = d;12:month = m;13:year = y;14:}15:public void display(){16:System.out.println(day + "-" + month + "-" + year);17:}18:public static void main(String args[ ]) {19:MyClass m1 = new MyClass();20:MyClass m2 = new MyClass(25,12,2001);21:m1.display();22:m2.display();23:}24:}运行结果:1-1-190025-12-2001实验2:Java基本数据类型一、实验目的(1)掌握javadoc文档化工具的使用方法。
第6章习题解答1.简述Java中设计图形用户界面程序的主要步骤。
对于设计图形用户界面程序而言,一般分为两个步骤:第一步,设计相应的用户界面,并根据需要对相关的组件进行布局;第二步,添加相关的事件处理,如鼠标、菜单、按钮和键盘等事件。
2.试说明容器与组件之间的关系。
组件(component)是图形用户界面中的各种部件(如标签、按钮、文本框等等),所有的组件类都继承自JComponent类。
容器(container)是用来放置其他组件的一种特殊部件,在java中容器用Container类描述。
3.阅读下面程序,说明其运行结果和功能。
//filename:MyFrame.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class MyFrame{public static void main(String agrs[]){JFrame f=new JFrame("简单窗体示例");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JLabel l=new JLabel("习题1");f.getContentPane().add(l,BorderLayout.CENTER);f.pack();f.setVisible(true);}}程序的运行结果如下:4.阅读下面程序,说明其运行结果和功能。
//filename:TestButton.javaimport java.awt.*;import javax.swing.*;public class TestButton extends JFrame{JButton b1,b2;TestButton(String s){super(s);b1=new JButton("按钮1");b2=new JButton("按钮2");setLayout(new FlowLayout());add(b1);add(b2);setSize(300,100);setVisible(true);}public static void main(String args[]){ TestButton test;test=new TestButton("测试按钮"); }}程序的运行结果如下:5.阅读下面程序,说明其运行结果和功能。
实验报告附页String s7 = new String("123.678");int n1=Integer.parseInt(s6);//将s6转化成int型数据。
double n2=Double.parseDouble(s7); //将s7转化成double型数据。
double m=n1+n2;System.out.println(m);String s8=String.valueOf(m); //String调用valuOf(int n)方法将m转化为字符串对象position=s8.indexOf(".");String temp=s8.substring(position+1);System.out.println("数字"+m+"有"+temp.length()+"位小数") ;@SuppressWarnings("unused")String s9=new String("ABCDEF");char a[]=s8.toCharArray(); //将s8存放到数组a中。
for(int i=a.length-1;i>=0;i--){System.out.print(" "+a[i]);}}}运行结果:将上面程序按如下要求修改,并运行:(1)程序中的s6改写成String s6=new String(“1a12b”);运行时提示怎样的错误?Exception in thread "main" ng.NumberFormatException: For input string: "1a12b"at ng.NumberFormatException.forInputString(Unknown Source)at ng.Integer.parseInt(Unknown Source)at ng.Integer.parseInt(Unknown Source)at xiti2.xiugai.main(xiugai.java:39)(2)请用数组a的前3个单元创建一个字符串并输出该串。
《Java语言程序设计基础教程》上机实验指导手册实验一基本数据类型与控制语句【目的】①掌握开发Java应用程序的3个步骤:编写源文件、编译源文件和运行应用程序;②学习同时编译多个Java源文件;③掌握char型数据和int型数据之间的相互转换,同时了解unicode字符表;④掌握使用if…else if多分支语句;⑤使用if…else分支和while循环语句解决问题。
【内容】1.一个简单的应用程序✧实验要求:编写一个简单的Java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习Java”和“We are students”。
✧程序运行效果示例:程序运行效果如下图所示:✧程序模板:Hello.javapublic class Hello{public static void main (String args[ ]){【代码1】//命令行窗口输出"你好,很高兴学习Java"A a=new A();a.fA();}}class A{void fA(){【代码2】//命令行窗口输出"We are students"}}✧实验后的练习:1.编译器怎样提示丢失大括号的错误?2.编译器怎样提示语句丢失分号的错误?3.编译器怎样提示将System写成system这一错误?编译器怎样提示将String写成string这一错误?2.联合编译✧实验要求:编写4个源文件:Hello.java、A.java、B.java和C.java,每个源文件只有一个类,Hello.java是一个应用程序(含有main方法),使用了A、B和C类。
将4个源文件保存到同一目录中,例如:C:\100,然后编译Hello.java。
✧程序运行效果示例:程序运行效果如下图所示:✧程序模板:模板1:Hello.javapublic class MainClass{public static void main (String args[ ]){【代码1】 //命令行窗口输出"你好,只需编译我"A a=new A();a.fA();B b=new B();b.fB();}}模板2 :A.javapublic class A{void fA(){【代码2】 //命令行窗口输出"I am A"}}模板3 :B.javapublic class B{void fB(){【代码3】 //命令行窗口输出"I am B"}}模板4 :C.javapublic class C{void fC(){【代码4】 //命令行窗口输出"I am C"}}✧实验后的练习:4.将Hello.java编译通过后,不断修改A.java源文件中的代码,比如,在命令行窗口输出“我是A类”或“我被修改了”。
Java实验报告专业班级学号姓名指导教师实验一、安装JDK并熟悉java的运行环境一、实验目的熟悉JA V A的运行环境及学习简单的编程。
二、预习内容安装工具软件的基本方法。
三、实验设备与环境装有JA V A语言工具软件(JCreator )的微机若干四、实验内容安装JCreator及JA V A的核心编译程序J2SDK。
1、打开JCreator的安装盘安装JCreator。
2、在相同目录下安装J2SDK。
3、打开JCreator软件对J2SDK文件进行配置。
4、编写一应用程序,在屏幕上显示“HELLO WORLD”。
public class Hello{public static void main(String args[]){System.out.println( "HELLO WORLD");}}5、编写一小程序实现上述功能:在屏幕上显示“HELLO WORLD”。
实验结果:五、注意事项⒈认真填写实验报告⒉遵守实验室各项制度,服从实验指导教师的安排⒊按规定的时间完成实验六、实验总结与体会1.通过这个实验我了解到java的运行环境。
2.通过这个简单的程序使我认识到做实验是要认真对待,不可马虎大意,区分字母的大小写和符号的正确使用。
实验二、基本语法练习一、实验目的⒈熟悉Java的基本语法⒉编写应用程序接收命令行参数⒊编写应用程序接收用户从键盘的输入⒋掌握字符串与数组的基本方法二、预习内容java编程的基本结构三、实验设备与环境装有JA V A语言工具软件(JCreator )的微机若干四、实验内容⒈编写一个应用程序求若干个数的平均数,原始数字要求从命令行输入。
应用程序中main方法的参数String类型的数组args能接受用户从命令行键入的参数。
(1)编辑A verage.java,设保存在D:\myjava目录下。
public class Average{public static void main(String args[ ]){double n,sum=0;for (int l=0;l<args.length;l++){sum=sum+Double.valueOf(args[l]).doubleValue();}n=sum/args.length;System.out.println("average="+n);}}(2)编译。
实验报告附页 实验内容与步骤 1.Jbutton,GridLayout,BorderLayout,Jpanel的用法 实验要求: 编写一个Java应用程序,采用GridLayout实现如下计算机器的布局
代码如下: import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class MyCalculater extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L; JPanel mainpanel = new JPanel(); //主面板 JPanel centerpanel = new JPanel(); //中心面板 JTextField txt = new JTextField(""); //主显示区 StringBuffer sb1 = new StringBuffer(); //参数一 StringBuffer sb2 = new StringBuffer(); //参数二 char sign; boolean flag = false; JButton[] buttons = new JButton[16]; { buttons[0] = new JButton("1"); buttons[1] = new JButton("2"); buttons[2] = new JButton("3"); buttons[3] = new JButton("+"); buttons[4] = new JButton("4"); buttons[5] = new JButton("5"); buttons[6] = new JButton("6"); buttons[7] = new JButton("-"); buttons[8] = new JButton("7"); buttons[9] = new JButton("8"); buttons[10] = new JButton("9"); buttons[11] = new JButton("*"); buttons[12] = new JButton("0"); buttons[13] = new JButton("c"); buttons[14] = new JButton("="); buttons[15] = new JButton("/"); } { centerpanel.setLayout(new GridLayout(4,4,8,8)); for (int i = 0; i < buttons.length; i++) { centerpanel.add(buttons[i]); buttons[i].addActionListener(this); } }
public MyCalculater(int x,int y) { this.setTitle("我的计算器"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setContentPane(mainpanel); this.setResizable(false); BorderLayout bl = new BorderLayout(); mainpanel.setLayout(bl); mainpanel.add(txt,BorderLayout.NORTH); mainpanel.add(centerpanel,BorderLayout.CENTER); this.setBounds(x,y, 300, 240); this.setVisible(true); } public static void main(String[] args) { new MyCalculater(750, 200);
} @Override public void actionPerformed(ActionEvent e) { JButton jb = (JButton)e.getSource(); char c = jb.getText().charAt(0); switch(c){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':{ addNum(c); break; } case '+': case '-': case '*': case '/':{ signEvent(c); break; } case 'c':{ MyCalculater.this.dispose(); new MyCalculater(MyCalculater.this.getLocation().x,MyCalculater.this.getLocation().y); break; } case '=':{ if(!flag)this.txt.setText(sb1.toString());; sb1 = new StringBuffer(getAnswer()); sb2 = new StringBuffer(); this.txt.setText(sb1.toString()); sign = '='; flag = false; break; } default: break; }
} private void signEvent(char c) { if(flag&&sb2.length()!=0){ sb1 = new StringBuffer(""+getAnswer()); this.txt.setText(sb1.toString()); } else { flag = !flag; this.txt.setText(""); } this.sign = c; } private String getAnswer() { double a = 0; if(sb1.length()!=0) a = Double.parseDouble(sb1.toString()); double b = 0; if(sb2.length()!=0) b = Double.parseDouble(sb2.toString()); double answer = 0; switch(sign){ case '+': answer = a+b; this.txt.setText(""); break; case '-': answer = a-b; this.txt.setText(""); break; case '*': answer = a*b; this.txt.setText(""); break; case '/': answer = a/b; this.txt.setText(""); break; default : return null; } this.sb1 = new StringBuffer(""); this.sb2 = new StringBuffer(""); return ""+answer; } private void addNum(char c) {
if(!flag){ sb1.append(c); this.txt.setText(sb1.toString()); } else { sb2.append(c); this.txt.setText(sb2.toString()); } } } 运行结果如下::
2.Jbutton,CardLayout,BorderLayout,Jpanel,JLabel的用法 实验要求: 编写一个Java应用程序,实现如下图布局
代码如下: package A; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import javax.swing.*; @SuppressWarnings("serial") public class TextWindow extends JFrame{
JPanel p,p1,p2,p3,butPanel; JButton nextBut,preBut,button[]=new JButton[3]; JLabel label1,label2,label3; CardLayout card; public void init(){ p=new JPanel(); p1=new JPanel(); label1=new JLabel("第一个面板"); p1.setBackground(Color.YELLOW); p1.add(label1);
p2=new JPanel(); label2=new JLabel("第二个面板"); p2.setBackground(Color.GREEN); p2.add(label2);