有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing Java图形组件问题。似乎找不到错误

我正在制作一个用于绘制图像的程序,似乎我犯了一个错误,我的程序只是不想绘制图像。有人能指出mi的错误吗,因为我真的看不出来

package basic_game_programing;

import java.awt.Graphics;
import java.awt.Image;


import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Practise extends JPanel {

public Image image;

        //#####PAINT__FUNCTION#####
        public void PaintComponent(Graphics g){
            super.paintComponent(g);

              ImageIcon character = new ImageIcon("C:/Documents and Settings/Josip/Desktop/game Šlije/CompletedBlueGuy.PNG");
              image = character.getImage();

              g.drawImage(image,20,20,null);
              g.fillRect(20, 20, 100, 100);
        }



//######MAIN__FUCTION#######
public static void main(String[]args){

    Practise panel = new Practise();


    //SETTING UP THE FRAME
    JFrame frame = new JFrame();
    //
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,500);
    frame.add(panel);


    //SETTING UP THE PANEL

    //









}

}


共 (1) 个答案

  1. # 1 楼答案

    使用paintComponent(注意第一个“p”)是对paintComponent的错误投资

    • 因此,将PaintComponent更改为paintComponent
    • 使用方法上方的@Override注释,让编译器在您犯这种错误时告诉您
    • 永远不要将图像读入绘画方法中,因为这会减慢需要快速的方法的速度,并在一次读取足够时使图像被反复读取
    • 方法应该是protected而不是public
    • 使用ImageIO.read(...)读取图像,使用jar文件中的资源和相对路径,而不是使用文件或图像图标
    • 在添加了所有组件之后,不要在JFrame上调用setVisible(true),否则一些组件可能不会显示
    • 一定要阅读教程,因为大部分内容都在这里得到了很好的解释

    例如

    public class Practise extends JPanel {
    
        private Image image;
    
        public Practice() {
            // read in your image here
            image = ImageIO.read(.......); // fill in the ...
        }
    
        @Override // use override to have the compiler warn you of mistakes
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
    
            // never read within a painting method
            // ImageIcon character = new ImageIcon("C:/Documents and Settings/Josip/Desktop/game Šlije/CompletedBlueGuy.PNG");
            // image = character.getImage();
    
            g.drawImage(image, 20, 20, this);
            g.fillRect(20, 20, 100, 100);
        }
    }