使用JScrollArea滚动时如何处理这种奇怪的效果:
代码:
import java.util.*;
import java.util.prefs.BackingStoreException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;
public class Main extends JFrame implements ActionListener, AdjustmentListener{
CustomComponent cc;
JScrollPane jsp;
public static void main(String[] args) {
Main m = new Main();
}
public Main(){
setTitle( "Diverse Testari 7");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
cc = new CustomComponent();
cc.setImage("rgbcmy.jpg");
jsp = new JScrollPane( cc,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
jsp.setPreferredSize( new Dimension( getWidth(), getHeight() ) );
jsp.setOpaque( true );
jsp.setBackground( Color.DARK_GRAY );
jsp.getVerticalScrollBar().addAdjustmentListener(this);
jsp.getHorizontalScrollBar().addAdjustmentListener(this);
setBackground( Color.red );
add( jsp );
setVisible( true );
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("EVENT: " + e.toString() );
}
@Override
public void adjustmentValueChanged(AdjustmentEvent arg0) {
// TODO Auto-generated method stub
}
}
class CustomComponent extends JPanel{
BufferedImage img = null;
public void setImage( String str ){
try {
img = ImageIO.read( new File( str ) );
System.out.println(img.getColorModel().toString());
System.out.println("SUCCESS!");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
// TODO Auto-generated method stub
return new Dimension(img.getWidth(), img.getHeight() );
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setClip(100, 100, 100, 100);
System.out.println("paintComponent");
if( img != null )
{
System.out.println("Obs: Imagine existenta!");
g2d.drawImage(img, null, 0,0);
}
else
{
System.out.println("Eroare: nu este imaginea!");
}
}//*/
}
答案 0 :(得分:3)
尝试在paintComponent重写方法的开头调用super.paintComponent(g)。像这样:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// rest of the method's code
希望这有帮助!祝你好运!
答案 1 :(得分:1)
这是常见问题,其中paint code isn't optimized
,可以通过禁用闪烁删除副作用的一部分,必须为JViewports ScrollMode
设置附加参数
JViewport viewPort = jsp.getViewport();
viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE);
viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
并通过super.paintComponent(g);
通知+1 for Óscar Gómez Alcañiz