我是新来的,对 Java 也很陌生。我正在制作一个可以选择图像区域的应用程序,它只返回选定的坐标。问题是,它不是显示图像,而是显示黑色区域而不是图像。还尝试了 BufferedImage.TYPE_INT_ARGB ,现在它显示一个空白区域。
这是代码。请帮忙。
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ScreenCaptureRectangle {
Rectangle captureRect;
ScreenCaptureRectangle(final Image im) {
final BufferedImage screenCopy = new BufferedImage(
im.getWidth(null),
im.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
final BufferedImage screenCopy1 = new BufferedImage(
im.getWidth(null),
im.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension(
(int)(im.getWidth(null)),
(int)(im.getHeight(null))));
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel selectionLabel = new JLabel(
"Drag a rectangle in the screen shot!");
panel.add(selectionLabel, BorderLayout.SOUTH);
repaint(screenCopy1, screenCopy);
screenLabel.repaint();
screenLabel.addMouseMotionListener(new MouseMotionAdapter() {
Point start = new Point();
@Override
public void mouseMoved(MouseEvent me) {
start = me.getPoint();
repaint(screenCopy1, screenCopy);
selectionLabel.setText("Start Point: " + start);
screenLabel.repaint();
}
@Override
public void mouseDragged(MouseEvent me) {
Point end = me.getPoint();
captureRect = new Rectangle(start,
new Dimension(end.x-start.x, end.y-start.y));
repaint(screenCopy1, screenCopy);
screenLabel.repaint();
selectionLabel.setText("Rectangle: " + captureRect);
}
});
JOptionPane.showMessageDialog(null, panel);
System.out.println("Rectangle of interest: " + captureRect);
}
public void repaint(BufferedImage orig, BufferedImage copy) {
Graphics2D g = copy.createGraphics();
g.drawImage(orig,0,0, null);
if (captureRect!=null) {
g.setColor(Color.RED);
g.draw(captureRect);
g.setColor(new Color(255,255,255,150));
g.fill(captureRect);
}
g.dispose();
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new ScreenCaptureRectangle(ImageIO.read(new File("Desert.jpg")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}