gpt4 book ai didi

java - PaintComponent 未被调用

转载 作者:行者123 更新时间:2023-12-02 09:57:05 25 4
gpt4 key购买 nike

很抱歉,这个问题可能已经解决了,但我已经到处搜索但找不到解决方案。我刚刚发现,无论如何,无论我把 repaint() 放在哪里,paintComponent都不会被调用

我已经尝试过将它放入几种不同的方法中,并尝试从不同的区域调用它,但无论如何,它似乎永远不会被调用。

import java.awt.*;
import java.awt.event.*;
import java.awt.Component;
import javax.swing.*;
import javax.swing.BoxLayout;
import javax.swing.event.*;
import java.awt.event.KeyEvent;
import java.util.Scanner;
public class LevelOne extends JPanel implements KeyListener
{
int width = 0;
int height = 0;
int bx = 0;
int hx = 0;
int by = 0;
int hy = 0;
Image joe = new ImageIcon("upgrademan.png").getImage();
ImagePanel2 panel2 = new ImagePanel2(new ImageIcon("levelone.png").getImage());
JFrame frame = new JFrame ("Level One");


public LevelOne()
{
frame.getContentPane().add(panel2);
Game game1 = new Game();
frame.setSize(600, 600);


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.WHITE);
frame.pack();
frame.setVisible(true);
levelOne();
requestFocus();
}

public void levelOne()
{
repaint(); // this doesn't call paintComponent below?
}

public void paintComponent(Graphics g)
{
super.paintComponent(g); //draw background color
System.out.println("this enters paintComponent");
g.drawImage(joe,100,100,200,200, null); // this doesn't seem to be drawing
requestFocus();

}
public void keyPressed(KeyEvent e) // all they keyListener methods
{
}
public void keyTyped(KeyEvent e)
{

}
public void keyReleased(KeyEvent e)
{

}

}
class ImagePanel2 extends JPanel { // this entire class simply exists to call in order to set a picture as a background

Image img;

public ImagePanel2(String img) { // just sets img in method to class img variable
this(new ImageIcon(img).getImage());
}

public ImagePanel2(Image img) { // sets size of picture
this.img = img;
Dimension dims = new Dimension(600,600);
setPreferredSize(dims);
setMinimumSize(dims);
setMaximumSize(dims);
setSize(dims);
setLayout(null);

}

public void paintComponent(Graphics g) { // draws image
g.drawImage(img, 0, 0, this);
}
}

我期望 ImagePanel 类打印背景,它确实做到了,但我也期望打印名为 joe 的图像,但它没有。

最佳答案

显示“joe”的唯一位置是 LevelOne 实例的 PaintComponent() 方法中。但您永远不会将 LevelOne 实例添加到您的框架或该框架中的任何面板。

关于java - PaintComponent 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55927957/

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