我将JPanel包裹在JScrollPane中,并且我希望始终将矩形绘制在同一位置上;使用滚动条移动不会影响矩形的可见性。
我尝试了以下代码:
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.drawRect(50, (int)getVisibleRect().getY(), 20 , 20);
}
但是它仅在更改整个JPanel的大小时才重新绘制矩形。
[IIRC,JScrollPane
将尝试最大程度地减少滚动完成后的重绘,因此它不会总是导致组件被更新。
标准技术是使用JLayeredPane
。将JScrollPane
添加到下一层,并在其上面添加不透明的玻璃面板组件。请参见Swing教程中的How to Use a Layered Pane。
也许像这样:
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);
}
}
尝试setLocation
方法。访问setLocation了解更多信息。