私はここが初めてで、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();
}
}
});
}
}