如何将IMAGE大小放入JPanel

时间:2014-04-01 14:11:30

标签: java swing

我有点做GUI,当你按下" NEXT"按钮,它逐个显示某些目录中的图像。

我的问题是:如何使用JPanles维度调整IMG的大小,我使用6个或更多MP图像,我需要查看整个图像。

以下代码为我提供了imageIcon以及我将其添加到JPanel的位置。

JButton btnNextImg = new JButton("Next IMG");
    btnNextImg.setBounds(96, 179, 110, 23);
    btnNextImg.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (i == nImg)
                i = 0;
            try {
                selectedImage = ImageIO.read(new File("C:\\IMAGES\\"+ String.valueOf(i+1) + ".jpg"));
                iSelect = new ImageIcon(selectedImage);
                originalImage.setIcon(iSelect);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            i++;
        }
    });
    contentPane.add(btnNextImg);

我在哪里添加它。

JPanel panel = new JPanel();
    originalImage = new JLabel();
    panel.add(originalImage);
    panel.setBounds(5, 226, 309, 280);
    contentPane.add(panel);

非常感谢你。

2 个答案:

答案 0 :(得分:1)

这是我在互联网上找到同样问题时在某处找到的图像面板:

public class ImagePanel extends JPanel {

private java.awt.Image image;
private boolean stretched = true;
private int xCoordinate;
private int yCoordinate;

public ImagePanel() {

}

public ImagePanel(Image image) {
    this.image = image;
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (image != null) {
        if (isStretched()) {
            g.drawImage(image, xCoordinate, yCoordinate, getWidth(), getHeight(), this);
        } else {
            g.drawImage(image, xCoordinate, yCoordinate, this);
        }
    }
}

public java.awt.Image getImage() {
    return image;
}

public void setImage(java.awt.Image image) {
    this.image = image;
    repaint();
}

public boolean isStretched() {
    return stretched;
}

public void setStretched(boolean stretched) {
    this.stretched = stretched;
    repaint();
}

public int getXCoordinate() {
    return xCoordinate;
}

public void setXCoodinate(int xCoordinate) {
    this.xCoordinate = xCoordinate;
}

public int getYCoordinate() {
    return xCoordinate;
}

public void setYCoordinate(int yCoordinate) {
    this.yCoordinate = yCoordinate;
    repaint();
}
}

将图像添加到面板使用如下:

ImagePanel imagePanel = new ImagePanel();
BufferedImage image = ImageIO.read(new File("C:\\IMAGES\\"+ String.valueOf(i+1) + ".jpg"));
imagePanel.setImage(image);

答案 1 :(得分:0)

  

以下代码为我提供了imageIcon以及我将其添加到JPanel的位置。

查看Darryl的Stretch Icon。它将允许Icon填充JLabel可用的整个空间。