题目:编写一个简单的图形界面程序,要求在窗体里显示四个按钮,名称分别为红色、白色、绿色、蓝色,布局管理器设为FlowLayout,要求单击红色按钮,窗体背景显示为红色,点击其它按钮同样。
1.创建窗体与按钮
JFrame jf = new JFrame("FlowLayout窗口");
Container con=jf.getContentPane(); //定义窗口容器;一个 content pane 是一个包含除菜单条(如果有的话)外所有框架的可视组件的容器。
jf.setSize(400, 400); //设置窗口大小
jf.setLocation(700, 500); //设置窗口边距
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true); //设置窗体可见
2.设置流式布局并且创建需要的组件(按钮、面板)
//设置流式布局
jf.setLayout(new FlowLayout(FlowLayout.CENTER)); //居中对齐
//AncestorListener redButton;
//创建按钮
JButton redButton,whiltButton,greenButton,blueButton;
redButton=new JButton("红色");
whiltButton=new JButton("白色");
greenButton=new JButton("绿色");
blueButton=new JButton("蓝色");
//添加面板
JPanel jp=new JPanel();
jp.add(redButton);
jp.add(whiltButton);
jp.add(greenButton);
jp.add(blueButton);
jf.add(jp);
jp.setBackground(Color.GREEN); //按钮背景色
以下是可以给组件配色
//设置按钮颜色
redButton.setForeground(Color.RED);
whiltButton.setForeground(Color.WHITE);
greenButton.setForeground(Color.GREEN);
blueButton.setForeground(Color.BLUE);
3.实现按钮功能
//实现按钮监听
redButton.addActionListener((AncestorListener-> {
con.setBackground(Color.red);
}));
whiltButton.addActionListener((AncestorListener-> {
con.setBackground(Color.white);
}));
greenButton.addActionListener((AncestorListener-> {
con.setBackground(Color.green);
}));
blueButton.addActionListener((AncestorListener-> {
con.setBackground(Color.blue);
}));
主函数如下:
/*
* @author:code超
* 功能:按钮改变-->窗口颜色改变
* 声明:如有不当之处,可以交流,加以改正。(内容简单 供参考)
*
*/
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FlowLayout_test {
public static void main(String args[]) {
JFrame jf = new JFrame("FlowLayout窗口");
Container con=jf.getContentPane();
jf.setSize(400, 400); //设置窗口大小
jf.setLocation(700, 500); //设置窗口边距
//设置流式布局
jf.setLayout(new FlowLayout(FlowLayout.CENTER)); //居中对齐
//AncestorListener redButton;
//创建按钮
JButton redButton,whiltButton,greenButton,blueButton;
redButton=new JButton("红色");
whiltButton=new JButton("白色");
greenButton=new JButton("绿色");
blueButton=new JButton("蓝色");
//添加面板
JPanel jp=new JPanel();
jp.add(redButton);
jp.add(whiltButton);
jp.add(greenButton);
jp.add(blueButton);
jf.add(jp);
jp.setBackground(Color.GREEN); //按钮背景色
//设置按钮颜色
redButton.setForeground(Color.RED);
whiltButton.setForeground(Color.WHITE);
greenButton.setForeground(Color.GREEN);
blueButton.setForeground(Color.BLUE);
//实现按钮监听
redButton.addActionListener((AncestorListener-> {
con.setBackground(Color.red);
}));
whiltButton.addActionListener((AncestorListener-> {
con.setBackground(Color.white);
}));
greenButton.addActionListener((AncestorListener-> {
con.setBackground(Color.green);
}));
blueButton.addActionListener((AncestorListener-> {
con.setBackground(Color.blue);
}));
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true); //设置窗体可见
}
}
运行结果: