java制作窗体九宫格按钮中间一标签

java制作窗体九宫格按钮中间一标签

功能是:使用GridLayout布局为3行3列,每个按钮的名称为1-9中的随机数字,如果数字为单数,则单击该按钮时弹出消息框“这是一个单数”,并使标签显示单击按钮上数字的值;如果数字为双数,则单击该按钮时弹出消息框“这是一个双数”,并使标签显示单击按钮上数字的值。
java制作窗体九宫格按钮中间一标签_第1张图片

import java.awt.GridLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

public class Ly4 extends JFrame implements ActionListener {

	private JLabel label = new JLabel("随机");

	public Ly4() {
		setBounds(300, 300, 400, 400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("实验四");
		setLayout(new GridLayout(3, 3));
		addButton("1", Color.blue);
		addButton("2", Color.blue);
		addButton("3", Color.blue);
		addButton("4", Color.blue);
		add(label);
		addButton("6", Color.blue);
		addButton("7", Color.blue);
		addButton("8", Color.blue);
		addButton("9", Color.blue);

	}

	public void addButton(String name, Color color) {
		JButton bt = new JButton(name);
		bt.setBackground(Color.pink);
		bt.setForeground(color);
		bt.addActionListener(this);
		add(bt);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("0") || e.getActionCommand().equals("2") || e.getActionCommand().equals("4")
				|| e.getActionCommand().equals("6") || e.getActionCommand().equals("8")) {
			label.setText(e.getActionCommand());
			JOptionPane.showMessageDialog(null, "这是一个偶数");
		} else if (e.getActionCommand().equals("1") || e.getActionCommand().equals("3")
				|| e.getActionCommand().equals("5") || e.getActionCommand().equals("7")
				|| e.getActionCommand().equals("9")) {
			label.setText(e.getActionCommand());
			JOptionPane.showMessageDialog(null, "这是一个单数");
		} else {
			JOptionPane.showMessageDialog(null, "错误");
		}

	}

	public static void main(String args[]) {
		Ly4 framel = new Ly4();
		framel.setVisible(true);
	}

}

你可能感兴趣的:(java窗体设计)