gpt4 book ai didi

java - 如何将IMAGE尺寸调整到JPanel中

转载 作者:行者123 更新时间:2023-12-01 13:11:56 25 4
gpt4 key购买 nike

我正在做一个 GUI,当你按下“NEXT”按钮时,它会一一显示某个目录中的图像。

我的问题是:如何使 IMG 的大小与 JPanles 尺寸相匹配,我正在处理 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);

非常感谢。

最佳答案

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

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);

关于java - 如何将IMAGE尺寸调整到JPanel中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22788477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com