我对如何在 paintComponent
方法中创建其他参数有疑问。
我还没有找到其他方法。
import javax.swing.*;
import java.awt.*;
public class Interface extends JPanel
{
protected void paintComponent(Graphics g *here(not part of code btw)*) {
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(0, 0, 100, 100);
}
public void CreateWindow(String name, int Xsize, int Ysize) {
//laver et JFrame og klader det "frame" !
JFrame frame= new JFrame();
frame.setTitle(name);
frame.setSize(Xsize, Ysize);
frame.setLocation(200, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
Interface JPanel = new Interface();
frame.add(JPanel);
Graphics Grafik = getGraphics();
paintComponent(Grafik);
}
}
当我使用参数运行代码时,它不会绘制矩形。
但是如果只有 Graphics
参数,它运行得很好。
最佳答案
正如您在 Javadoc 中看到的那样,JComponent 中为paintComponent 定义的方法只有一个。这意味着如果不创建自己的 JComponent 和 JComponent 的扩展(子类)(这将变得不必要的复杂和困难),就没有办法可以做到这一点。相反,您可以考虑使用类中的字段来存储输入 PaintComponent 方法时所需的持久状态。另一方面,临时变量最好定义为方法的局部变量。
此外,将类命名为 Interface
并不是一个好习惯,因为 interface
是保留的 keyword在Java中。
tl;dr - 本质上,不。使用字段/局部变量来存储您的附加数据。
关于java - 有什么方法可以获取paintComponent中的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57529483/