我有一个装饰模式对话框,显示与桌面对齐的屏幕截图:
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ImageDialog extends JDialog {
public ImageDialog() throws AWTException {
Rectangle screenArea = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration().getBounds();
BufferedImage image = new Robot().createScreenCapture(screenArea);
ImagePanel panel = new ImagePanel(image);
JScrollPane scrollPane = new JScrollPane(panel);
getContentPane().add(scrollPane, BorderLayout.CENTER);
setSize(400, 400);
setLocation(100, 100);
addNotify(); // XXX addNotify seems necessary. Better solution?
Point p = new Point(getInsets().left, getInsets().top);
SwingUtilities.convertPointToScreen(p, this);
scrollPane.getViewport().setViewPosition(p);
setModal(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
private class ImagePanel extends JPanel {
private BufferedImage image;
public ImagePanel(BufferedImage image) {
this.image = image;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new ImageDialog();
} catch (AWTException ignore) {
}
System.out.println("Done");
}
});
}
}
我不想调用addNotify
,因为document这么说,但如果我不这样做,屏幕截图就没有很好地对齐:(啊......周围的装饰品我的对话框)
那么,这是一个我应该致电addNotify
的案例,还是有更好的选择?