首页 > 解决方案 > 我如何让 paincomponent 从其他方法或类中提取东西

问题描述

我想请 TestGraphics 类中的paintcomponent 画一条线,我这样做的方式只是给我一个 NullPointer 异常,如果你能告诉我我怎么能这样,我会很感激你

测试图形类:


import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

@SuppressWarnings("serial")
public class TestGraphics extends JPanel {
    
    
    public JPanel panel = new JPanel() {
        public void paintComponent (Graphics g) {
            
            super.paintComponent(g);
            
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawLine(120, 234, 23, 43);
            
        }
    };
    
}

主类:


import javax.swing.*;

public class Main {
    
    static int width = 600;
    static int height = 800;

    public static void main(String[] args) {
        
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        TestGraphics p = new TestGraphics();
        
        // draw Line
        p.panel.getGraphics().drawLine(123, 23, 43, 21);
        
        
        frame.add(p.panel);
        
        
        frame.setSize(height, width);
        frame.setVisible(true);
        
        
        
    }
    
}

标签: java

解决方案


您只需要添加一个新的TestGraphics 对象,而不是调用“p.panel.getGraphics().drawLine(123, 23, 43, 21);”。以下是简单的修复:

测试图形.java

import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

@SuppressWarnings("serial")
public class TestGraphics extends JPanel {
    
        public void paintComponent (Graphics g) {
            
            super.paintComponent(g);
            
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawLine(120, 234, 23, 43);
            
        }
  
    }

和 Main.java

import javax.swing.*;

public class Main {
    
    static int width = 600;
    static int height = 800;

    public static void main(String[] args) {
        
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        TestGraphics p = new TestGraphics();
        
        // draw Line
        frame.add(p);
        frame.setSize(height, width);
        frame.setVisible(true);
           
    }
   
}

这是一个小例子:https ://repl.it/repls/ExtrovertedSoulfulClients


推荐阅读