如果我运行它只显示一个窗口,它不会绘制。 如果我启动程序,使用退出代码执行null但是当窗口显示为空时。
public class Component extends JComponent implements IComponent {
public void init(Graphics g) {
int cellWidth = 7;
int cellHeight = 7;
// Background:
super.paintComponent(g);
g.setColor(Color.white);
for (int i = 0; i <= 5; i++) {
for (int j = 0; j <= 5; j++) {
g.setColor(Color.black);
g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight);
g.setColor(Color.decode("#00ffff"));
g.fillRect(i * cellWidth, j * cellHeight, cellWidth - borderThickness, cellHeight - borderThickness);
}
}
g.setColor(Color.BLACK);
}
public void draw() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Component c = new Component(gameStatus);
f.add(c);
f.setSize(screenWidth, screenHeight);
f.setVisible(true);
}}
public class app {
public static void main(String[] args) {
Component component = new Component(gameStatus);
component.draw();
}}
答案 0 :(得分:1)
要进行自定义绘图,您应该覆盖paintComponent(Graphics g)。另外,你似乎对组件包含有一些困惑 - 你创建一个,然后创建另一个内部draw()..
修复这些问题,这似乎有用(我替换了一些你没有用常量发布的变量):
import javax.swing.*;
import java.awt.*;
public class Component extends JComponent {
static final int cellWidth = 7;
static final int cellHeight = 7;
static final int borderThickness = 1;
@Override
protected void paintComponent(Graphics g) {
// Background:
super.paintComponent(g);
for (int i = 0; i <= 5; i++) {
for (int j = 0; j <= 5; j++) {
g.setColor(Color.BLACK);
g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight);
g.setColor(Color.CYAN);
g.fillRect(i * cellWidth + borderThickness, j * cellHeight + borderThickness,
cellWidth - 2 * borderThickness, cellHeight - 2 * borderThickness);
}
}
g.setColor(Color.BLACK);
}
public static void main(String[] args) {
Component component = new Component();
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(component);
f.setSize(500, 500);
f.setVisible(true);
}
}