程序功能:
使用Swing控件创建以下用户界面。
有了上一题的解题经验,这道题很快就有解题思路了。剩下的功夫就是敲代码实现了,总共花了半小时解决。
运行结果:
代码:
1. 测试类
import javax.swing.JFrame;
public class BlankFrame12_10Test {
public static void main(String[] args)
{
BlankFrame12_10 testFrame = new BlankFrame12_10();
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testFrame.setSize(368, 180);
testFrame.setVisible(true);
}
}
2. 实体类
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
//Java How to Program, Exercise 12.8
//by pandenghuang@163.com
/**
* 使用Swing控件创建用户界面
* 12.10 Create the following GUI.
* You do not have to provide any functionality.
* @author Pandenghuang@163.com
* @Date Jan 11, 2019, 12:45:51 AM
*
*/
public class BlankFrame12_10 extends JFrame{
//声明界面中的基本控件
private final JButton okJButton;
private final JButton cancelJButton;
private final JLabel backgroundJLabel;
private final JLabel foregroundJLabel;
private final JCheckBox backgroundJCheckBox;
private final JCheckBox foregroundJCheckBox;
private final JComboBox<String> colorJComboBox;
private static final String[] colors =
{"Red", "Yellow", "Blue", "Black","White"};
//声明容器控件
private final JPanel middleJPanel;
private final JPanel bottomJPanel;
public BlankFrame12_10 () {
super("Blank GUI for Java How to Program, exercise 12.10");
setLayout(new GridLayout(3,1,1,10));
//初始化基本控件
okJButton = new JButton("OK");
cancelJButton = new JButton("Cancel") ;
backgroundJLabel = new JLabel("Background");
foregroundJLabel = new JLabel("Foreground");
backgroundJCheckBox = new JCheckBox();
foregroundJCheckBox = new JCheckBox();
colorJComboBox = new JComboBox<String>(colors);
colorJComboBox.setBackground(Color.WHITE);
//初始化容器控件
middleJPanel = new JPanel();
bottomJPanel = new JPanel();
//向容器中填充基本控件
middleJPanel.setLayout(new FlowLayout(FlowLayout.CENTER,2,5));
middleJPanel.add(backgroundJCheckBox);
middleJPanel.add(backgroundJLabel);
middleJPanel.add(foregroundJCheckBox);
middleJPanel.add(foregroundJLabel);
bottomJPanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,5));
bottomJPanel.add(okJButton);
bottomJPanel.add(cancelJButton);
add(colorJComboBox);
add(middleJPanel);
add(bottomJPanel);
setVisible(true);
}
}