我试图创建一个超级简单的组件,但它并没有出现。
组件类:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Player extends JComponent{
public Player()
{
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.fillRect(40,40,150,150);
}
}面板类im添加到:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.JPanel;
public class Game extends JPanel{
public Game()
{
this.setBackground(Color.yellow);
this.setPreferredSize(new Dimension(500,500));
Player p = new Player();
this.add(p);
}
}JFrame:
import javax.swing.JFrame;
public class Launcher {
public static void main(String[] args) {
JFrame frame = new JFrame("Key Collector Demo");
frame.add(new Game());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
}唯一出现的是黄色背景。JFrame和JPanel运行良好;在构建jcomponents时,这个问题一直发生在我身上。我遗漏了什么?
任何帮助都将不胜感激!
发布于 2022-07-13 15:59:52
用于绘制组件的坐标是在该组件的空间中定义的。
如果你这样做:
public void paint(Graphics g)
{
g.setColor(Color.green);
System.out.println(getSize());
g.fillRect(40,40,150,150);
}您将看到,在试图绘制它的时候,它的大小是1x1。因此,从40,40中提取它显然是从组件的可见区域中提取出来的。
现在将方法更改为:
public void paint(Graphics g)
{
g.setColor(Color.green);
System.out.println(getSize());
setSize(45, 45);
g.fillRect(40,40,150,150);
}现在你可以看到小填充矩形。这是因为您强制大小为45x45,现在有5个像素显示在组件的空间,而其余的部分仍然在区域之外。
发布于 2022-07-13 16:18:57
不要假设播放机面板有固定大小。对于第一次测试,您的画图方法可能如下所示:
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(0,0,getWidth(),getHeight());
} 下一个问题是组件可能没有大小或位置。向面板中添加一个LayoutManager并添加组件:
public Game() {
this.setBackground(Color.yellow);
this.setPreferredSize(new Dimension(500,500));
this.setLayout(new BorderLayout());
Player p = new Player();
this.add(p, BorderLayout.CENTER);
}这样,你的球员可能会占据全部空间,你看到的是绿色而不是黄色。玩LayoutManager和玩家的preferredSize。
https://stackoverflow.com/questions/72968933
复制相似问题