【问题标题】:Java JPanel wont scrollJava JPanel不会滚动
【发布时间】:2013-04-27 06:57:12
【问题描述】:

我正在尝试使用 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);
}
}

【问题讨论】:

  • 1) drawQuestion 应该被称为 DrawQuestion 或更好的 DrawableQuestion 并且它应该返回与图像相同大小的首选尺寸。 2) Image image1 = new ImageIcon(this.getClass().getResource("Page1.png")).getImage();图像应该在创建面板时加载,或者在构造函数中传递给面板。 3) 在滚动窗格中以JLabel 显示图像要容易得多。 E.G.

标签: java image swing jframe jpanel


【解决方案1】:

您没有为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 会抛出异常...

【讨论】:

  • @AndrewThompson 从技术上讲,最小值或最大值也是如此,但是是的 - 已更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 2019-06-22
相关资源
最近更新 更多