我有一个加载的图像,但当我尝试显示它时,没有任何东西出现。
public class JComponentButton extends JComponent implements MouseListener {
BufferedImage image;
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test Title3");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(1,1));
mainFrame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
JComponentButton button = new JComponentButton();
button.setSize(64,64);
controlPanel.add(button);
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
System.out.println("finishing");
}
public JComponentButton(){
super();
try {
this.image = ImageIO.read(new File("resources/default.png"));
} catch (IOException e) {
System.out.println("did not load image");
System.exit(1);
}
enableInputMethods(true);
addMouseListener(this);
}
@Override public void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println(image.getHeight() + "," + image.getWidth());
g.drawImage(image, 64, 64, null);
}
当64,64打印到控制台时,图像似乎被加载。但它应该出现在窗口的位置是空白的。我使用g.fillRect在那里画了一个没有问题的正方形。所以似乎问题必须与g.drawImage有关。我也尝试将视角从null更改为此,但没有任何改变。
在你的代码中,方法g.drawImage(image, 64, 64, null)
将以64,64的偏移量开始绘制图像的全分辨率。
用于drawImage的Javadoc:
绘制尽可能多的指定图像。在此图形上下文的坐标空间中,图像以其左上角(x,y)绘制。图像中的透明像素不会影响已存在的任何像素。
这意味着,当您的图像确实被绘制时,它将被绘制在按钮的可见坐标空间之外。
要解决此问题,请将64, 64
替换为0, 0
(如果图像大小为组件大小)或使用更明确的方法drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
指定图像应在按钮中调整大小的位置。
EG
g.drawImage(image, 0, 0, null); //draws image at full resolution
g.drawImage(image, 0, 0, 64, 64, null); //draws image at offset 0, for max resolution of 64x64
您无法查看图像是因为图像是在按钮之外绘制的。由于按钮外没有任何面板,因此无法绘制。
原因是,您指定的图像的x轴和y轴(即左上角)为64,64,按钮的大小为64,64.因此,此图像将在按钮的右下方绘制,这是按钮的角点。因此,您应该将图像点指定为0,0(这些是图像的左上角),以便它将覆盖按钮的0,0(这些是按钮的左上角)点。
此外,您必须指定图像的宽度和高度。因此,它不会超出按钮的边界。如果您不想指定宽度和高度,则必须将图像的像素减小到按钮的大小(至少)。
您可以将代码重写为:g.drawImage(image,0,0,64,64,null);