这是一个pacman游戏,当我从我的电脑导入它时,它运行得很好.但是当我尝试从URL中获取它时,我的游戏开始滞后并且图像不显示.
URL url = new URL("https://www.dropbox.com/s/xpc49t8xpqt8dir/pacman%20down.jpg");
image = ImageIO.read(url);
G.drawImage(image, x, y, 20,20,null);
Run Code Online (Sandbox Code Playgroud)

https://www.dropbox.com/s/xpc49t8xpqt8dir/pacman%20down.jpg 返回HTML文本而不是图像数据.
这是一个黑客攻击,但请尝试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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1397 次 |
| 最近记录: |