【问题标题】:paintComponent method mixes different JPanel componentspaintComponent 方法混合了不同的 JPanel 组件
【发布时间】:2014-01-21 20:15:53
【问题描述】:

我正在开发一个软件,它为我的 GUI 绘制 2 个不同的JPanel:一个乐谱和一个桅杆吉他。 score 是一个扩展 JPanel 并具有 paintComponent() 方法的类,如下所示:

public class PanelPartitura extends JPanel implements MouseListener{
  public void paintComponent(Graphics comp){
    super.paintComponent(comp);
    comp2D = (Graphics2D)comp;
    comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);

    paintBackground();
    paintStave();
    paintNotes();

    [...]
  }
}

桅杆吉他也是一类:

public class PanelGuitarra extends JPanel implements MouseListener
  public void paintComponent(Graphics comp){
    super.paintComponent(comp);
    comp2D = (Graphics2D)comp;
    comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);

    //Then I call secondary methods to paint it:
    paintBackground();              
    PaintPoints();
  }

  [...]
}

它仍然可以正常工作。我将 PanelPartitura 类添加到 JScrollPane 以便在播放时滚动:

partitura = new PanelPartitura();
JScrollPartitura = new JScrollPane(partitura, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

两个JPanels 在软件播放和滚动时相互混合绘制的组件。我想问一下,如果有人知道到底发生了什么?在我看来:

  1. 这可能是因为我分离了我们上面看到的绘画方法:

    paintBackground();
    paintStave();
    paintNotes();
    

    然后,当软件开始绘制时,它会绘制第一个JPanel(例如paintBackground())的一些部分,然后绘制桅杆吉他的一些部分(paintBackground()),然后它会再次更改,结果是两者的混合体。

    我认为这是因为它每次都会混合不同的部分,我的意思是它每次播放时的行为方式都不一样。

    我真的不希望这种情况发生,所以让我问你:我怎样才能创建原子方法来确保这不会成为问题?

  2. 我误解了滚动方法。我这样滚动:

    //the note playing currently position is saved in positionBar
    positionBar = 150 + 50*PGuitarra.composicion.getAcordeSeleccionado().getPosicionXAcorde();      
    
    //horizontalScrollBar is moved to this position
    PGuitarra.JScrollPartitura.getHorizontalScrollBar().setValue(positionBar);
    

【问题讨论】:

    标签: java jpanel jscrollpane paint paintcomponent


    【解决方案1】:

    我看到您的绘制方法没有使用相同的 Graphics 对象(在 JPanel 范围内)。这可能是原因吗?如果是,请尝试将 comp(Graphics 对象)作为参数传递给paintBackground、paintStave 和paintNotes。

    【讨论】:

    • 猜得好。根据描述和发布的sn-ps,很可能在代码(部分省略)的某处调用了getGraphics,这可以解释渲染错误
    • 每个类都有一个属性,我在处理它:private Graphics2D comp2D; 这解决了你之前说的问题,不是吗?问题依然存在。
    猜你喜欢
    • 2014-10-02
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多