gpt4 book ai didi

Java JPanel 绘画不工作

转载 作者:行者123 更新时间:2023-12-02 08:06:20 25 4
gpt4 key购买 nike

我在创建一个从 JPanel 扩展的内部类以在其上绘制任何内容时遇到问题。我重写了paintComponent方法,无论我设置从这里绘制什么,都可以正常工作,但使用其他方法绘制则不起作用。

这是我的内部类代码:

private class Plot extends JPanel {

public Plot() {
this.setBackground(Color.WHITE);
}

@Override
public void paintComponent(Graphics graphic) {
super.paintComponent(graphic);
Graphics2D graphic2d = (Graphics2D) graphic;

graphic2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

graphic2d.drawOval(0, 0, this.getWidth() - 1, this.getHeight() - 1);
}

public void drawTitle(final String title) {
Graphics2D graphic2d = (Graphics2D) this.getGraphics();
graphic2d.setColor(Color.red);
graphic2d.drawString(title, 1, 10);
}
}

注意drawTitle方法。我只想显示自定义文本。在从 JFrame 扩展的外部类中,我创建了这个内部类的一个实例,如下所示:

private Plot plot;

/** Creates new form GraphicsView */
public GraphicsView() {
initComponents();
plot = new Plot();
this.add(plot, BorderLayout.CENTER);
}

public void drawTitle(final String title) {
this.plot.drawTitle(title);
}

我什至创建了一个方便的方法来调用内部类drawTitle方法(具有相同的名称)。我这样做是因为我希望这个 JFrame 外部类在按钮单击时可见,一旦它可见(这确保了图形的初始化),我调用外部类drawTitle,它又调用具有相同名称和位置的内部类方法字符串显示被绘制...但这不起作用,我在面板上看不到它。这是我的按钮点击事件:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
GraphicsView view = new GraphicsView();
view.setVisible(true);
view.drawTitle("Hello");
}

提前致谢,我将不胜感激任何帮助。 :)

最佳答案

I overrided the paintComponent method, and whatever I set to draw from here works fine

好了,问题有了答案。通过paintComponent() 方法完成所有绘图。

but using another method to draw does not work.

不要使用 getGraphics() 方法。您应该只使用传递给 PaintComponent() 方法的 Graphics 对象。

您无法控制 Swing 何时重新绘制() 组件。因此,每次重新绘制组件时,都会调用 PaintComponent() 方法,并且您的其他自定义绘制代码将会丢失。

关于Java JPanel 绘画不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8114287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com