2010-05-17 23 views
1

我有JPanel包裹在JScrollPane中,我想要矩形總是在相同的位置=使用滾動條移動不會影響矩形的可見性。如何在JPanel上繪製固定位置?

我嘗試下面的代碼:

public void paintComponent(Graphics g) { 
     g.setColor(Color.red); 
     g.drawRect(50, (int)getVisibleRect().getY(), 20 , 20); 
    } 

但是當整個JPanel的大小發生變化,也只有重新繪製的矩形。

+0

發表SSCCE:http://sscce.org,你的問題,所以我們可以看到確切的問題。例如,你的代碼中沒有包含super.paintComponent()的問題? – camickr 2010-05-17 03:32:57

回答

1

IIRC,JScrollPane將盡量減少重繪完成滾動的數量,所以它不會總是導致您的組件被更新。標準技術是使用JLayeredPane。將您的JScrollPane添加到較低層,以及其上方的不透明玻璃面板組件。請參閱Swing教程中的How to Use a Layered Pane

+0

我甚至用JLayeredPane做過HUD。 – 2010-05-17 02:54:37

2

也許是這樣的:

import java.awt.*; 
import javax.swing.*; 

public class ScrollPanePaint extends JFrame 
{ 
    public ScrollPanePaint() 
    { 
     JPanel panel = new JPanel(); 
     panel.setOpaque(false); 
     panel.setPreferredSize(new Dimension(400, 400)); 

     JViewport viewport = new JViewport() 
     { 
      public void paintComponent(Graphics g) 
      { 
       super.paintComponent(g); 
       g.setColor(Color.BLUE); 
       g.drawArc(100, 100, 80, 80, 0, 360); 
      } 
     }; 

     viewport.setView(panel); 
     JScrollPane scrollPane = new JScrollPane(); 
     scrollPane.setViewport(viewport); 
     scrollPane.setPreferredSize(new Dimension(300, 300)); 
     getContentPane().add(scrollPane); 
    } 

    public static void main(String[] args) 
    { 
     JFrame frame = new ScrollPanePaint(); 
     frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
}