我创建了一个演示程序,可以绘制一组不寻常的对象。它通过重写扩展 JPanel
的类的 paintComponent
方法来实现此目的。该类已实例化,并且对象和文本在 JPanel
中绘制。
我想在之前包含在 JFrame
中的 JPanel
中绘制这些对象,以响应对其菜单的点击。
需要在 a 中重写 paintComponent
方法
private void demoMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
}
是否可以重写先前定义的 JPanel
的 paintComponent
方法?
谢谢
最佳答案
s it possible to override the paintComponent method of a previously defined JPanel?
是的,您向面板提供属性。然后,paintComponent() 方法在进行自定义绘制时检查这些属性的状态。
因此,actionPerformed() 方法所做的就是获取对面板的引用,然后设置属性。
例如,您可以有一个绘制矩形的基本类:
public class RectanglePanel extends JPanel
{
private boolean squareFilled = false;
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor( getBackground() );
g.drawRect(10, 10, 50, 50);
if (squareFilled)
{
g.setColor( getForeground() );
g.fillRect(10, 10, 50, 50);
}
}
public void toggleSquareFilled()
{
squareFilled = !squareFilled;
repaint();
}
}
那么 ActionListener 代码就是:
rectanglePanel.toggleSquareFilled();
上面的代码假设“rectanglePanel”是一个指向您的 RectanglePanel 的实例变量。
关于java - 有没有办法重写 MenuItemActionPerformed 中的 PaintComponent 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61309453/