我有一个加载的图像,但当我试图显示它时,什么也没有出现。
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更改为null,但没有什么改变。
发布于 2015-07-28 19:52:15
在您的代码中,方法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)来指定应该在按钮中调整图像大小的方法。
例如。
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 发布于 2015-07-28 20:14:38
无法查看图像是因为图像是在按钮之外绘制的。由于在按钮外没有任何面板,因此无法绘制。
原因是,您指定的图像的x和y轴为64,64,而按钮大小为64,64。因此,该图像将绘制在按钮的右下角,即按钮的角点。因此,您应该将图像点指定为0,0 (这些是图像的左上角),以便覆盖按钮的0,0(这些是按钮的左上角)点。
另外,您必须指定image.So的宽度和高度,这样它就不会超出button.If的边界--您不想指定宽度和高度--然后必须将图像的像素缩小到按钮的大小(至少)。
您可以将代码重写为:g.drawImage(image,0,0,64,64,null);
https://stackoverflow.com/questions/31685656
复制相似问题