【发布时间】:2012-09-19 06:26:57
【问题描述】:
大家好,我有这个问题,我似乎无法解决。我得到了一些代码,并且必须制作一个“井字游戏”游戏。相当原始。目前它想要我做的是接受用户输入(它只是询问您要放置标记的行/列)并且它的目的是在板的适当正方形上绘制一个椭圆形。我当前的代码是按照工作指定的,我创建了一个新类来处理用户输入。
我目前只是在尝试让它向 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);
}
}
【问题讨论】:
-
你为什么用
paint??除了你没有打电话给super.paint,你应该使用paintComponent -
好的,我快速浏览了您的代码,您的
GameBoard方法绝对不可能工作。JFrame不接受Rectangle通过我知道的任何add方法,它通常需要Component。如果没有合适的SSCCE,您将很难为您提供帮助 -
如何将 Oval 组件添加到 JFrame 中?如果您只是调用 add(new Oval()) 并且您保留了 JFrame 内容窗格的默认 LayoutManager,那么您将使用 BorderLayout 它将覆盖您对 setBounds 的调用并使椭圆占据整个区域。
-
是的,这几乎就是它正在做的事情,只是我也落后于画在框架上的其他任何东西。我可以通过添加 JPanel 或类似的东西来解决这个问题吗?
-
永远不会在 Swing 中进行任何手动调整大小/定位,这是合适的 LayoutManager 的专属任务