gpt4 book ai didi

java - 尝试将图像绘制到 JPanel 上

转载 作者:太空宇宙 更新时间:2023-11-04 14:59:21 25 4
gpt4 key购买 nike

抱歉,我知道有很多关于这个主题的信息,但我仍然卡住了。我有两个面板 mainPanel 和 sidePanel。我想做的是将图像绘制到侧面板上。我的侧面板将有其他组件,例如按钮和标签。我可以使用 JLabel 将图像添加到 sidePanel,但是调整图像的大小和位置是一个问题。因此,我正在尝试使用 Graphics g 将图像绘制到侧面板上。如果有人可以提供帮助,我们将不胜感激。感谢所有帮助。` import java.awt.BorderLayout;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;



public class Gui extends JFrame {
private JPanel j;
private ImageIcon i;

public Gui(){
this.setSize(800,600);
this.setUp();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setUp(){
j = new JPanel();
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BorderLayout());
contentPanel.setSize(new Dimension(800,600));
JPanel mainPanel = new JPanel();
JPanel sidePanel = new JPanel();

sidePanel.setPreferredSize(new Dimension(200,600));
mainPanel.setPreferredSize(new Dimension(600,600));

ImagePanel v = new ImagePanel();
//v.setBackground(Color.BLUE);
v.setPreferredSize(new Dimension(100,100));

sidePanel.add(v);

mainPanel.setBackground(Color.BLACK);
sidePanel.setBackground(Color.RED);


contentPanel.add(sidePanel, BorderLayout.WEST);
contentPanel.add(mainPanel, BorderLayout.CENTER);

this.add(contentPanel);


}
private class ImagePanel extends JPanel{
public void createImage(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("/GUI Practice/src/images.jpeg");
Image ii = i.getImage();
g.drawImage(ii, 10, 10, 90, 90, Color.WHITE, this);

repaint();
validate();
updateUI();



}

}
public static void main(String [] args){

Gui g = new Gui();

}

}
`

最佳答案

摘自 bcash 的回答 here .

public class ImagePanel extends JPanel {

private BufferedImage image;

public ImagePanel() {
try {
image = ImageIO.read(new File("image name and path"));
} catch (IOException ex) {
// handle exception...
}
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}

}

关于java - 尝试将图像绘制到 JPanel 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798216/

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