图像未显示在 JPanel 中
Image not showing in a JPanel
这是我的两个代码示例:
public class Display extends JPanel
{
protected BufferedImage buffer;
private static final long serialVersionUID = 1L;
public Display()
{
super();
//setBackground(Color.BLACK);
buffer = new BufferedImage(PONG_WIDTH, PONG_WIDTH, BufferedImage.TYPE_INT_RGB);
}
protected void paintComponent(Graphics2D g)
{
super.paintComponent(g);
g.drawImage(buffer, 0, 0, this);
}
}
和
public class Server extends Display
{
private static final long serialVersionUID = 1L;
public Server() throws IOException
{
super();
Graphics2D g = buffer.createGraphics();
g.setBackground(Color.BLACK);
g.setColor(Color.WHITE);
g.fillRect(0, (PONG_HEIGHT-RACKET_HEIGHT)/2, RACKET_WIDTH, RACKET_HEIGHT);
repaint();
编辑:添加main
方法:
public class Test {
public static void main(String args[])
{
JFrame f = new JFrame();
f.setTitle("Test2");
f.setSize(1000, 1000);
f.setLocationRelativeTo(null);
try{
Server s = new Server();
f.add(s); //or f.setContentPane(s);
s.repaint();
f.setVisible(true);
s.play();
}
catch (IOException e){}
}
}
当我在子类中绘制多个形状时,如果取消注释 Display
的构造函数的第二行,为什么面板显示为空白或黑色?我一直在努力寻找答案,但我的每一次尝试都失败了。
组件层级中没有这个方法protected void paintComponent(Graphics2D g)
,实际应该是protected void paintComponent(Graphics g)
<- 注意方法的形参要求
您应该在从 BufferedImage
创建的 Graphics
上下文中调用 Graphics#dispose
完成后,这可能会阻止某些平台正确渲染图像(以及防止程序消耗系统资源)。
您应该仅在 EDT 的上下文中创建和修改 UI 的状态,有关详细信息,请参阅 Initial Threads。
直接从 JFrame
扩展也需要理由,除了给您的代码带来混乱之外,您实际上并没有向 class 添加任何功能。
这是我的两个代码示例:
public class Display extends JPanel
{
protected BufferedImage buffer;
private static final long serialVersionUID = 1L;
public Display()
{
super();
//setBackground(Color.BLACK);
buffer = new BufferedImage(PONG_WIDTH, PONG_WIDTH, BufferedImage.TYPE_INT_RGB);
}
protected void paintComponent(Graphics2D g)
{
super.paintComponent(g);
g.drawImage(buffer, 0, 0, this);
}
}
和
public class Server extends Display
{
private static final long serialVersionUID = 1L;
public Server() throws IOException
{
super();
Graphics2D g = buffer.createGraphics();
g.setBackground(Color.BLACK);
g.setColor(Color.WHITE);
g.fillRect(0, (PONG_HEIGHT-RACKET_HEIGHT)/2, RACKET_WIDTH, RACKET_HEIGHT);
repaint();
编辑:添加main
方法:
public class Test {
public static void main(String args[])
{
JFrame f = new JFrame();
f.setTitle("Test2");
f.setSize(1000, 1000);
f.setLocationRelativeTo(null);
try{
Server s = new Server();
f.add(s); //or f.setContentPane(s);
s.repaint();
f.setVisible(true);
s.play();
}
catch (IOException e){}
}
}
当我在子类中绘制多个形状时,如果取消注释 Display
的构造函数的第二行,为什么面板显示为空白或黑色?我一直在努力寻找答案,但我的每一次尝试都失败了。
组件层级中没有这个方法protected void paintComponent(Graphics2D g)
,实际应该是protected void paintComponent(Graphics g)
<- 注意方法的形参要求
您应该在从 BufferedImage
创建的 Graphics
上下文中调用 Graphics#dispose
完成后,这可能会阻止某些平台正确渲染图像(以及防止程序消耗系统资源)。
您应该仅在 EDT 的上下文中创建和修改 UI 的状态,有关详细信息,请参阅 Initial Threads。
直接从 JFrame
扩展也需要理由,除了给您的代码带来混乱之外,您实际上并没有向 class 添加任何功能。