一、实验目的
1.掌握图形界面设计。
二、实验内容
1.编程包含一个标签和一个按钮,单击按钮时,标签的内容在"你好"和"再见"之间切换。
2.设计一个窗口,窗口中包含有一个文本框,一个标签,两个按钮,当按下“文本一”按纽时,使得“Hello java!”显示在文本框中,按下“文本二”按纽时,使得“你好 Java!” 显示在文本框中(要求两个按纽之间使用网格布局,与其他组件共使用Frame默认布局管理)。
3. 试设计一个窗口,内含一个按钮。开始运行时,按钮显示“Click Me”字样,当按钮按下时,按钮显示为“Click Me Again”字样,再按一次,则按钮显示“Click Me”字样,依此循环。(1,2,3可以选作其一)
4.编程包含一个文本框和一个文本区域,在文本框中按回车键时,把文本框的内容写入文本区域。
5.试设计一个窗口,窗口界面如下图。包含Style菜单、Color菜单和Exit菜单,Style菜单设计字体的样式(包括Plane、Bold、Italic),Color(红、绿、蓝、自定义)菜单设计字体的颜色、Exit菜单(CloseWindow)退出系统。
代码实现:
1.
方法一:
package p;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class T {
public static void main(String[] args) {
JFrame f=new JFrame();
FlowLayout flow =new FlowLayout();
f.setLayout(flow);//设置布局
JButton b=new JButton("exchange");
final JLabel j=new JLabel("hello");
b.addActionListener(new ActionListener(){//利用匿名类
public void actionPerformed(ActionEvent e) {
if(j.getText().equals("hello"))
j.setText("bye");
else j.setText("hello");
}
});
f.add(b); //先添加哪个,哪个组件就会在前面
f.add(j);
f.setBounds(20,20,200,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
方法二:
package cn.nefu.edu.cn;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyWindow extends JFrame implements ActionListener{
JButton bt;
JLabel bq1;
public MyWindow(){
FlowLayout flow =new FlowLayout();
this.setLayout(flow);
bq1=new JLabel("bye");
bt=new JButton("exchange");
bt.addActionListener(this);//监听本身,自身实现了接口ActionListener
this.add(bt);
this.add(bq1);
validate();
this.setBounds(20,20,200,200);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CL