gpt4 book ai didi

java - Jframe 对我来说不能正常工作

转载 作者:行者123 更新时间:2023-12-02 12:01:38 24 4
gpt4 key购买 nike

如果我运行这个,只会出现一个窗口并且不会绘制。如果我启动程序,则以退出代码 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();
}}

最佳答案

要进行自定义绘图,您应该重写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);
}
}

关于java - Jframe 对我来说不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47207624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com