import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends Frame implements ActionListener {
public MyFrame(){
super("测试");
Button btn1 = new Button("改背景");
Button btn2 = new Button("关闭");
Font f=new Font("宋体",Font.BOLD,28);//设置字体
btn1.setFont(f);//设置按钮1的字体
btn2.setFont(f);//设置按钮2的字体
setLayout(new FlowLayout());//设置为FlowLayout
add(btn1);//将按钮加入窗体
add(btn2);//将按钮加入窗体
btn1.addActionListener(this);
btn2.addActionListener(this);
setSize(400,200);//设置窗体大小
setVisible(true);//设置窗体可见
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("改背景")){//当按下“改背景”的按钮时,改变颜色
int R=(int)(Math.random()*256);
int G=(int)(Math.random()*256);
int B=(int)(Math.random()*256);
setBackground(new Color(R,G,B));//设置窗体背景颜色
}
if(e.getActionCommand().equals("关闭")){//当按下“关闭”按钮时,关闭窗体
dispose();
}
}
public static void main(String[] args) {
new MyFrame();//创建窗体
}
}
编写窗体应用,窗体中安排2个按钮,按钮上面的标签分别为“改背景”、“关闭”,点击“改背景”按钮,用随机产生的颜色更改窗体的背景,点击“关闭”按钮可关闭窗体。
最新推荐文章于 2021-02-17 00:16:45 发布