java - 将 JScrollPane 添加到显示图像的面板

标签 java swing jscrollpane

我有这个用于在面板上显示图像的小程序..但我无法向其添加滚动条..这是我的代码

扩展 jpanel 以显示图像的类:

public class ShowPanel extends JPanel{

public ShowPanel(BufferedImage image, int height, int width) {
  this.image = image;
  this.height = height;
  this.width = width;
  //this.setBounds(width, width, width, height);

}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, height, width, null);
}

public void setImage(BufferedImage image, int height, int width) {
    this.image = image;
    this.height = height;
    this.width = width;

}

private BufferedImage image;
private int height;
private int width;

还有一个主框架的示例,它有另一个名为 imageContainer 的面板来保存显示面板:

public class MainFrame extends javax.swing.JFrame {

/** Creates new form MainFrame */
public MainFrame() {
    initComponents();
    image = null;
    path = "PantherOnLadder.gif";
    image = Actions.loadImage(path);
    showPanel = new ShowPanel(image, 0, 0);
    spY = toolBar.getY() + toolBar.getHeight();
    showPanel.setBounds(0, spY, image.getWidth(), image.getHeight());
    showPanel.repaint();
    imageContainer.add(showPanel);
    JScrollPane scroller = new JScrollPane(imageContainer);
    scroller.setAutoscrolls(true);


}

那么我在这里做错了什么?

最佳答案

当添加到滚动 Pane 的组件的首选大小 超过滚动 Pane 的大小时,滚动条会自动出现。您的自定义面板没有首选大小,因此永远不会出现滚动条。一种解决方案是仅返回等于图像大小的首选大小。

当然,我一直不明白为什么人们会不厌其烦地做这种定制画。不需要自定义类。只需从 BufferedImage 创建一个 ImageIcon,然后将 Icon 添加到 JLable,然后将标签添加到滚动 Pane ,您就不会遇到任何这些问题。进行自定义绘画的唯一原因是您需要缩放图像或提供一些其他奇特的效果。

关于java - 将 JScrollPane 添加到显示图像的面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1689850/

相关文章:

java - 如何使 JFrame 具有与其他组件不同的外观(多路复用)?

Java:Jscrollpane 或 Jsplitpane 的自定义光标?

java - JScrollPane 中的 JScrollPane

java - 当使用 Java 中的 MigLayout 将高度或宽度设置为 100% 时,子级将扩展到其父级的边界

Java Swing - JScrollPane 使视口(viewport)宽度适合 JScrollPane 宽度

java - 如何以编程方式设置android系统时间?

java - Selenium GRID : org. openqa.selenium.SessionNotCreatedException:无法创建新服务:ChromeDriverService

java - 无法使用 jhat、jps、jstack 调试 Java Windows 服务

java - 如何在java中的图像上添加可移动的TextArea?

java - 单击后退按钮会导致强制关闭/NullPointerException