[英]Image is not drawing on top left of panel
當我加載圖像時,它不會加載到左上角(如果圖像很大以適合窗口大小)。這是因為我減小了代碼中所示的大小。 盡管我給出其坐標值0,0,但它不在該位置繪制。
import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class photo extends JFrame
{
Dimension screenwidth=getToolkit().getScreenSize();
int mx=(int)screenwidth.getWidth();
int my=(int)screenwidth.getHeight();
BufferedImage picture1;
JLabel label3;
int neww;
int newh;
public photo() {
JFrame f = new JFrame("Image Editor v1.0");
f.setLayout(null);
try{
File file=new File("e:\\8.jpg");
picture1=ImageIO.read(file);
}catch(Exception e)
{
}
JPanel panel2 = new JPanel();
panel2.setLayout(null);
panel2.setBounds(101,20,mx-100,my-20);
f.add(panel2);
label3 = new JLabel("");
label3.setBounds(110,30,mx-110,my-30);
panel2.add(label3);
f.setExtendedState(Frame.MAXIMIZED_BOTH);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage bi = null;
if(picture1.getWidth()>mx-110 ||picture1.getHeight()>my-30 )
{
neww= (int) Math.round(picture1.getWidth() * 0.25);
newh = (int) Math.round(picture1.getHeight() *0.25);
}
else
{
neww=picture1.getWidth();
newh=picture1.getHeight();
}
bi = new BufferedImage(neww,newh,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(picture1,0,0,neww,newh,0,0,picture1.getWidth(),picture1.getHeight(), null);
label3.setIcon(new ImageIcon(bi));
}
public static void main(String[] args)
{
new photo();
}
}
您可以添加g2d.translate(0, 0);
在g2d.addRenderingHints
和g2d.drawImage
之間嘗試。
編輯
因此,如果您希望圖像分別為101像素和20像素,則應label3.setBounds(0,0,neww,newh);
在label3.setIcon(new ImageIcon(bi));
而不是當前。 我認為這將如我剛剛測試的那樣工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.