显示一个井字游戏的棋盘
编写程序,创建一个自定制面板,它可以显示 X、0 或者空白。注意:每次程序开始运行时,显示的 X、0 或者空白图形是在随机变化的。使用 Math.random()方法产生整数 0、1 或 2,对应于面板上显示 X、0 或者空白。创建一个包含九个自定制面板的框架,如下图所示:
import java.awt.*;
import javax.swing.*;
public class Test4 extends JFrame{
public Test4(){
setLayout(new GridLayout(3,3));
for(int i=0;i<9;i++){
add(new Panel2());
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Test4 frame = new Test4();
frame.setSize(250, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class Panel2 extends JPanel{
protected void paintComponent(Graphics g){
super.paintComponent(g);
int value = (int)(Math.random()*3);
int xCenter = getWidth()/2;
int yCenter = getHeight()/2;
int radius = (int)(Math.min(getWidth(), getHeight())*0.4);
int x = xCenter - radius;
int y = yCenter - radius;
if(value == 0){
g.drawLine(x, y, x+radius*2, y+radius*2);
g.drawLine(x, y+radius*2, x+radius*2, y);
}
if(value == 1){
g.drawOval(x, y, radius*2, radius*2);
}
}
}
import javax.swing.*;
public class Test4 extends JFrame{
public Test4(){
setLayout(new GridLayout(3,3));
for(int i=0;i<9;i++){
add(new Panel2());
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Test4 frame = new Test4();
frame.setSize(250, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class Panel2 extends JPanel{
protected void paintComponent(Graphics g){
super.paintComponent(g);
int value = (int)(Math.random()*3);
int xCenter = getWidth()/2;
int yCenter = getHeight()/2;
int radius = (int)(Math.min(getWidth(), getHeight())*0.4);
int x = xCenter - radius;
int y = yCenter - radius;
if(value == 0){
g.drawLine(x, y, x+radius*2, y+radius*2);
g.drawLine(x, y+radius*2, x+radius*2, y);
}
if(value == 1){
g.drawOval(x, y, radius*2, radius*2);
}
}
}