[英]Jframe not working properly for me
if i run this only a window appear and it does not draw. 如果我运行此仅出现一个窗口,它不会绘制。 if i start the program, that execute with exit code null but when the window is appear its empty.
如果我启动程序,则以退出代码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();
}}
To have custom drawing, you should override paintComponent(Graphics g). 要具有自定义图形,应重写paintComponent(Graphics g)。 In addition, you seem to have some confusion around component containment - you create one, then create another inside draw()..
此外,您似乎对组件包含有一些困惑-创建一个,然后在draw()内部创建另一个。
Fixing those issues, this seems to work (I replaced some variables which you didn't post with constants): 解决这些问题后,这似乎可行(我用常量替换了一些您没有发布的变量):
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.