【发布时间】:2019-01-11 21:50:56
【问题描述】:
我正在制作一个简单的 Java 程序。现在它只是制作了一个 8x8 跳棋字段。但是,当启动我的 JFrame 的程序背景时,就像为我的屏幕拍照一样,它并没有改变。但是,我将其设置为白色。是代码有问题还是有其他问题?
我将背景设置为白色,根本没有设置。都没有帮助。
package mainpackage;
import com.sun.prism.paint.*;
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.io.File;
class Field extends JFrame {
Field() //little constructor with no arguments
{
this(800, 800);
}
Field(int a, int b) //the most big constructor
{
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBackground(Color.white);
setLayout(new FlowLayout());
setResizable(false);
setSize(a, b);
}
void makeVisible() //making frame visible
{
setVisible(true);
}
public void makeInvisible() //making frame invisible
{
setVisible(false);
}
public void paint(Graphics g) //painting the board
{
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
g.setColor(getCurrentColor(x,y)); // get and set color of current square
{
if (x % 2 == 0) // if x even
{
if (y % 2 == 0) {
g.setColor(Color.lightGray); // if x even y even make gray
} else {
g.setColor(Color.pink); // if x even and y odd make pink
}
} else { // if odd even
if (y % 2 == 0) {
g.setColor(Color.pink); // if x odd and y even make pink
} else {
g.setColor(Color.lightGray); // if x odd and y odd make gray
}
}
}
if(x>0&&x<9&&y>0&&y<9) { // only if 0 < x < 9 and 0 < y < 9
g.fillRect(50 + 60 * x, 50 + 60 * y, 60, 60); // fill current rectangle
}
else if(y==0&&x>0&&x<9)
{
g.setColor(Color.black);
g.drawString(Integer.toString(x),50 + 60 * x, 50 + 60 * y);
}
/* if (y == 2&& x== 1) {
*//* JLabel label = new JLabel();
label.setLocation(x*60, y*60);
label.setSize(60, 60);
label.setLayout(new GridBagLayout());
label.setIcon(new ImageIcon("C:/Users/Asus/Desktop/My Work/checkers/res/images/checkerimage.png"));
add(label);*//*
}*/
}
}
}
private Color getCurrentColor(int x, int y) //set the color of current square
{
if (x % 2 == 0) // if x even
{
if (y % 2 == 0) {
return Color.red;
} else {
return Color.blue;// if x even and y odd make blue
}
} else { // if odd even
if (y % 2 == 0) {
return Color.blue; // if x odd and y even make blue
} else {
return Color.red; // if x odd and y odd make red
}
}
}
}
package mainpackage;
public class MainClass {
public static void main(String[] args) throws InterruptedException {
Field f1 = new Field();
f1.makeVisible();
}
}
【问题讨论】:
-
你不应该覆盖
JFrame的paint,它是一个复合组件,这意味着框架上已经有许多组件可以干扰绘画过程,而且,你必须调用paints 超级方法,除非你准备好承担它的所有责任 -
只需添加 super.paint(g);在 ' public void paint(Graphics g) // 画板 {'?看起来它真的帮助了我