https://www.dropbox.com/s/xpc49t8xpqt8dir/pacman%20down.jpg
是返回 HTML 文本而不是图像数据。
这是一个 hack,但请尝试https://www.dropbox.com/s/xpc49t8xpqt8dir/pacman%20down.jpg?dl=1
。但请注意,drop box 将来可能会更改此查询。
public class TestURL02 {
public static void main(String[] args) {
new TestURL02();
}
public TestURL02() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new PacPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PacPane extends JPanel {
private BufferedImage image;
public PacPane() {
InputStream is = null;
try {
URL url = new URL("https://www.dropbox.com/s/xpc49t8xpqt8dir/pacman%20down.jpg?dl=1");
// StringBuilder sb = new StringBuilder(1024);
// byte[] buffer = new byte[1024 * 1024];
// is = url.openStream();
// int in = -1;
// while ((in = is.read(buffer)) != -1) {
// sb.append(new String(buffer));
// }
// System.out.println(sb.toString());
image = ImageIO.read(url);
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
is.close();
} catch (Exception e) {
}
}
}
@Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(), image.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight() - image.getHeight()) / 2;
g.drawImage(image, x, y, this);
}
}
}
}