2

我正在尝试在 java 中使用 jPanel 和 jFrame 使图像可滚动。我在 drawQuestion 类中绘制图像,然后将 drawQuestion 添加到 jScrollPanel 并且它不会滚动。请告诉我我的错误在哪里我一直试图找到几天,但我仍然找不到它。对不起,我的英语不好。

主.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);
}
}
4

1 回答 1

4

您没有为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如果无法加载图像会引发异常...

于 2013-04-27T06:59:37.677 回答