此代码不会填充矩形。我试图扩展JComponent但我收到了一个错误。我如何扩展JComponent?
package com.lewis.GooseEgg;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class GooseEgg extends Canvas{ //I couldn't extend JComponent
//How would I also extend JComponent
protected void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0,0, 100, 100);
}
public static void main(String[] args) {
//This is just all the basic stuff I learned
JFrame frame = new JFrame();
GooseEgg goose = new GooseEgg();
frame.setResizable(false);
frame.setTitle("Goose Egg");
frame.add(goose);
frame.pack();
frame.setSize(900, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//The website keeps asking me to add more detail because it says my post is mostly code so I added this. If anyone wants to tutor me at Java
//I could pay money.
}
}
答案 0 :(得分:0)
您无需从Canvas
和JComponent
延伸:您应该只从JComponent
延伸。
此外,您不应该pack()
和setSize(…)
。它们都设置了框架的大小,这没有意义。要么执行pack()
(在这种情况下,您还需要指定首选大小,例如通过覆盖getPreferredSize()或将其设置为setPreferredSize(…))或执行setSize(…)
}。
将Canvas
更改为JComponent
并删除pack()
方法调用似乎会产生正确的结果。