我正在尝试使用java中的jPanel和jFrame来使图像可滚动。我在drawQuestion类中绘制我的图像然后我将drawQuestion添加到jScrollPanel并且它不滚动。请告诉我我的错误在哪里,我一直试图寻找好几天,但我仍然无法找到它。 抱歉我的英语不好。
main.java:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class main{
private static int width = 800;
private static int height = 450;
public static void main(String[] args){
JFrame window = new JFrame("DPA Physics 2013 9 class");
drawQuestion question = new drawQuestion();
JScrollPane scroll = new JScrollPane(question);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(width,height);
window.setLocationRelativeTo(null);
window.add(scroll);
window.setVisible(true);
}
}
drawQuestion.java:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class drawQuestion extends JPanel{
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g){
super.paintComponent(g);
Image image1 = new ImageIcon(this.getClass().getResource("Page1.png")).getImage();
g.drawImage(image1,0,0,this);
}
}
答案 0 :(得分:3)
您没有为drawQuestion
面板指定(首选)大小,这意味着现在所有布局都认为它的大小为0x0 ....
在任何paint
方法中,您都不应该加载或执行任何可能需要很短时间才能完成的任务......
您需要覆盖getPreferredSize
方法以返回所需的面板大小。这将允许滚动窗格确定面板是否需要滚动...
public class DrawQuestion extends JPanel{
private static final long serialVersionUID = 1L;
private Image image1;
public DrawQuestion() {
image1 = new ImageIcon(this.getClass().getResource("Page1.png")).getImage();
}
public Dimension getPreferredSize() {
return image1 == null ? super.getPreferredSize() : new Dimension(image1.getWidth(this), image1.getHeight(this));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if (image1 != null) {
g.drawImage(image1,0,0,this);
}
}
}
当我在我的墙上时...我还建议ImageIO
超过ImageIcon
因为ImageIO
如果无法加载图片,则会抛出异常... < / p>