java - 我如何让 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);
}
}
解决方案
您只需要添加一个新的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);
}
}
推荐阅读
- django - 在 Django ORM 的子查询中返回多个值
- google-cloud-platform - 出现错误:[Errno 60] Google 函数创建操作超时
- javascript - 如何让 app.js 调用外部包
- node.js - 无法使用 NodeJS Azure 函数从 Cosmos DB(MongoDB 架构)返回 JSON
- android - 屏幕关闭时Android后台服务停止
- ajax - 为什么我的 ajax 在查询 yelp api 时出现验证错误?
- sql-server - 加快对大型表的长时间运行查询
- swift - 使用 Combine 的发布者和订阅者发布实时 HealthKit 数据?
- python-3.x - 如何根据特定列按升序对python Sqlite数据库进行排序?
- javascript - 如何从 json 中分离键和值并将其存储在数组中使用 useState 挂钩反应