Overriding the paint() method

ぐ巨炮叔叔 提交于 2019-12-31 05:29:06

问题


I've got a beginner question here that I was hoping someone with some Java experience could help me with. Currently taking an intro to OOP course focused on Java. My instructor is currently covering awt and swing, specifically the need to override the paint method so that graphics are redrawn when a window is resized, etc. I like to do as much outside reading as possible, and my concern is that the examples that my professor gives involve things that I've read are not best practices. To get to the point...

I understand that it's necessary to override the paint method, but I don't know the best way to do so. My professor's examples are all similar to the following:

class Example extends JFrame {
  public void paint(Graphics g) {
    super.paint(g);
    g.drawString("Blah, blah");
  }

  public static void main(String[] args) {
    Example a = new Example();
    a.setDefaultCl...
    \\Etc...
  }
}

This bothers me because it doesn't seem right to include everything for the GUI in the same class as my main method. Also, I read on a different thread here that you shouldn't extend JFrame, but there wasn't an explanation as to why. My solution was to create a class handling the gui and instantiate JFrame within the constructor. However, unless I'm mistaken, doing so won't let me override the paint method. I feel compelled to extend JFrame to allow me to override paint, but again I read that was the wrong thing to do.

Any help would be sincerely appreciated, I know I can just model my code off of what he has but I really want to understand this and know the best way to handle it.


回答1:


I understand that it's necessary to override the paint method

No you should not override the paint() method.

You should override the paintComponent() method of a JPanel and then add the panel to the frame.

Read the section from the Swing tutorial on Custom Painting for more information and working examples.

The tutorial will also show you how to better structure your code so that the GUI is created on the Event Dispatch Thread (EDT). The tutorial also has a section on Concurrency which will explain why this is important.



来源:https://stackoverflow.com/questions/34036540/overriding-the-paint-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!