所以我在 JScrollPane
中有一个 JPanel
。
现在我想在面板上画一些东西,但它总是在同一个地方。
我可以向各个方向滚动,但它没有移动。无论我在面板上绘制什么都不会滚动。
我已经试过了:
- 自定义
JViewPort
- 在 Opaque = true 和 Opaque = false 之间切换
我还考虑过重写面板的 paintComponent
方法,但这在我的代码中很难实现。
public class ScrollPanePaint{
public ScrollPanePaint() {
JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(1000, 1000));
//I tried both true and false
panel.setOpaque(false);
JScrollPane scrollPane = new JScrollPane(panel);
frame.add(scrollPane);
frame.setSize(200, 200);
frame.setVisible(true);
//To redraw the drawing constantly because that wat is happening in my code aswell because
//I am creating an animation by constantly move an image by a little
new Thread(new Runnable(){
public void run(){
Graphics g = panel.getGraphics();
g.setColor(Color.blue);
while(true){
g.fillRect(64, 64, 3 * 64, 3 * 64);
panel.repaint();
}
}
}).start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ScrollPanePaint();
}
});
}
我犯的错误可能很容易改正,但我就是不知道怎么改正。
最佳答案
如何在JPanel
上实现paintComponent()
?
覆盖 getPreferredSize()
方法而不是使用 setPreferredSize()
final JPanel panel = new JPanel(){
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
// your custom painting code here
}
@Override
public Dimension getPreferredSize() {
return new Dimension(40, 40);
}
};
几点:
覆盖 JComponent#getPreferredSize()而不是使用
setPreferredSize()
阅读更多 Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
使用 Swing Timer而不是 Java Timer更适合Swing应用。
使用 UIManager.setLookAndFeel() 设置默认外观
关于java - 在 JScrollPane 内的 JPanel 上绘画不会在正确的位置绘画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23974009/