【问题标题】:paintComponent is not working at all油漆组件根本不工作
【发布时间】:2018-09-15 11:21:33
【问题描述】:

我正在使用paintComponent 为类分配制作GUI,它根本不会影响GUI 的外观。首先,我只是将背景设置为白色。以下代码有效:

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

public class PA05a extends JPanel {
  public static void main(String[] args) {
    JFrame window = new JFrame("MouseDrawDemo");
    JPanel content = new JPanel();

    content.setBackground(Color.WHITE);

    window.setContentPane(content);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLocation(120,70);
    window.setSize(400,300);
    window.setVisible(true);
  }
}

但事实并非如此:

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

public class PA05a extends JPanel {
  public static void main(String[] args) {
    JFrame window = new JFrame("MouseDrawDemo");
    JPanel content = new JPanel();

    window.setContentPane(content);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLocation(120,70);
    window.setSize(400,300);
    window.setVisible(true);
  }

  @Override
  public void paintComponent(Graphics g) {
    //add backdrop
    super.paintComponent(g);
    g.setColor(Color.WHITE);
    g.fillRect(0,0,getWidth(),getHeight());
  }
}

我不能不使用paintComponent,因为我稍后会添加会随着帧而变化的东西。有人能指出我遗漏了什么吗?

【问题讨论】:

    标签: java swing user-interface paintcomponent


    【解决方案1】:
    JPanel content = new PA05a();
    

    您没有创建 PA05a 的对象。 ;)

    【讨论】:

      【解决方案2】:

      你只是忘了创建你的对象。将您的代码更改为:

      import javax.swing.*;
      import java.awt.*;
      
      public class PA05a extends JPanel {
        public static void main(String[] args) {
          JFrame window = new JFrame("MouseDrawDemo");
          JPanel content = new PA05a();
      
          window.setContentPane(content);
          window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          window.setLocation(120,70);
          window.setSize(400,300);
          window.setVisible(true);
        }
      
        @Override
        public void paintComponent(Graphics g) {
          //add backdrop
          super.paintComponent(g);
          g.setColor(Color.WHITE);
          g.fillRect(0,0,getWidth(),getHeight());
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-10
        • 1970-01-01
        相关资源
        最近更新 更多