大家好,我有这个问题,我似乎无法解决。我得到了一些代码,并且必须制作一个“井字游戏”游戏。相当原始。目前它想要我做的是接受用户输入(它只是询问您要放置标记的行/列),并且它意味着在板的适当正方形上绘制一个椭圆形。我当前的代码如下工作所示,我创建了一个新类来处理用户输入。
我目前只是在尝试让它向 JFrame 添加新项目,但收效甚微。我有一个虚拟的输入调用,它不会检查我输入的内容,它只是调用一个椭圆形,它应该位于左上角的第一个正方形中。我可以让对象绘制到 JFrame 上(尽管它占据了整个框架),但它总是在实际板的后面(即:如果我拉伸框架,我可以看到圆圈)。我已经尝试添加 JPanel 等,以便它们位于板的顶部,但到目前为止我运气不佳。
这是我为该任务提供的用于创建椭圆形的代码。我所做的只是实例化一个位置为 (0,0,10,10) 的新椭圆。然而,当它绘制时,它占据了整个 JFrame,但它也在实际电路板的后面......有什么想法吗?
package lab4;
import javax.swing.*;
import java.awt.*;
/** Oval Supplier Class
* Author: David D. Riley
* Date: April, 2004
*/
public class Oval extends JComponent {
/** post: getX() == x and getY() == y
* and getWidth() == w and getHeight() == h
* and getBackground() == Color.black
*/
public Oval(int x, int y, int w, int h) {
super();
setBounds(x, y, w, h);
setBackground(Color.black);
}
/** post: this method draws a filled Oval
* and the upper left corner of the bounding rectangle is (getX(), getY())
* and the oval's dimensions are getWidth() and getHeight()
* and the oval's color is getBackground()
*/
public void paint(Graphics g) {
g.setColor( getBackground() );
g.fillOval(0, 0, getWidth()-1, getHeight()-1);
paintChildren(g);
}
}
编辑:这就是我们现在正在查看的代码——
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lab4;
/**
*
* @author Scott
*/
import java.awt.*;
import java.util.Scanner;
import javax.swing.*;
public class GameBoard {
private JFrame win;
private int count = 1;
//Create new GUI layout
GridLayout layout = new GridLayout(3, 3);
JPanel panel = new JPanel(layout);
//Create a new Array of Rectangles
Rectangle[][] rect = new Rectangle[3][3];
public GameBoard() {
//Create new JFrame + Set Up Default Behaviour
win = new JFrame("Tic Tac Toe");
win.setBounds(0, 0, 195, 215);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setResizable(true);
//Loop goes through each line of the array. It creates a new rectangle
//determines it's colour based on modulus division
//Add's the rectangle to the JPanel.
for (int i = 0; i < rect.length; i++) {
for (int j = 0; j < rect[i].length; j++) {
rect[i][j] = new Rectangle(0, 0, 1, 1);
if (count % 2 != 0) {
rect[i][j].setBackground(Color.black);
} else {
rect[i][j].setBackground(Color.red);
}
panel.add(rect[i][j]);
count++;
}
}
//Sets the game to be visible.
win.add(panel);
win.setVisible(true);
//userInput();
}
private void userInput() {
Scanner scan = new Scanner(System.in);
}
}