2

我想做一些最能用这张照片解释的事情:

jpanel上的图片

换句话说,我需要将图片的右下部分放入 jpanel 的左上部分,我尝试将 x 和 y 设置为负数,但没有成功,图像根本不显示。有一种简单的方法可以做到这一点吗?

我目前正在使用

g.drawImage(img, x, y, null)
//x and y are negative

画它。

4

1 回答 1

3

我会验证您的 x/y 位置是否计算正确,如果您正在屏幕上绘画,请添加ImageObserver对您的参考g.drawImage

在此处输入图像描述

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class NegativeImage {

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

    public NegativeImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage img;

        public TestPane() {
            try {
                img = ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/Evil_Small.jpg"));
            } catch (IOException ex) {
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); 
            int x = (getWidth() - img.getWidth()) / 2;
            int y = (getHeight()- img.getHeight()) / 2;
            // Center...
            g.drawImage(img, x, y, this);

            // Off to the left...
            x = -(img.getWidth() / 2);
            g.drawImage(img, x, y, this);

            // Off to the right...
            x = getWidth() - (img.getWidth() / 2);
            g.drawImage(img, x, y, this);
        }        
    }    
}
于 2013-06-22T09:54:49.260 回答