的paintComponent();没有工作/被叫

时间:2015-08-17 15:39:59

标签: java swing paintcomponent

这是我的代码。我对编码有点新意,所以请详细说明。

public class main extends JPanel{


    public static Window f = new Window();
        public static int Width = 600;
        public static int Hight = 400;
        public static void main(String args[]){ 

            f.setSize(Width, Hight);
            f.setVisible(true);
            f.setResizable(false);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("FightForYourLife");
            f.setLocationRelativeTo(null);
        }

        public void main(){
            JPanel panel = this;
        }

        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.fillRect(100, 100, 50, 30);
            System.out.println("IT IS PAINTING");
        }



}

1 个答案:

答案 0 :(得分:0)

一堆问题但是数字1:

  • 您永远不会将主对象添加到顶级窗口,GUI,因为它永远不会添加到GUI,它永远不会显示也不会呈现,因此永远不会调用paintComponent。在public static void main方法中创建一个新的Main对象并将其添加到Window(为什么是Window而不是JFrame?)。

其他问题:

  • 你的班级作为"伪"构造函数public void main(){。请记住,构造函数不具有返回类型,而不是无效,而不是任何东西。所以它应该是public main() {
  • 您的伪构造函数没有任何用处。 JPanel panel = this; ???
  • 您需要遵循Java命名规则:类名称以大写字母开头,字段和方法以小写字母开头。因此public class main {应为public class Main {
  • 再次,为什么选择Window而不是JFrame?

例如:

import java.awt.*;
import javax.swing.*;

// rename main to Main
public class Main extends JPanel{

        public static int WIDTH = 600;
        public static int HEIGHT = 400;

        public static void main(String args[]){ 
            Main main = new Main(); // *** create your main object ***

            JFrame f = new JFrame("FightForYourLife");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(main);  // *** add your main object to the top-level window
            f.pack();  
            f.setResizable(false);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }

        public Main(){
            // JPanel panel = this; // this is not helpful, delete it
        }

        @Override // let the JPanel size itself.
        public Dimension getPreferredSize() {
            return new Dimension(WIDTH, HEIGHT);
        }

        @Override  // paintComponent should be protected, not public
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.fillRect(100, 100, 50, 30);
            System.out.println("IT IS PAINTING");
        }
}
相关问题