我周圍有一齣戲,我似乎沒有任何問題......
(我沒有改變縮放級別,所以我並沒有總是以「藍色」結束)
public class TestGoogleMaps {
public static void main(String[] args) {
new TestGoogleMaps();
}
public TestGoogleMaps() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final MapPane mapPane = new MapPane();
JButton random = new JButton("Random");
random.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String lat = Double.toString((Math.random() * 180) - 90);
String longt = Double.toString((Math.random() * 360) - 180);
new LoadMapTask((JButton)e.getSource(), mapPane, lat, longt).execute();
((JButton)e.getSource()).setEnabled(false);
}
});
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(mapPane);
frame.add(random, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MapPane extends JPanel {
private BufferedImage mapImage;
private String latitude;
private String longitude;
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public void setMap(String lat, String log, BufferedImage image) {
mapImage = image;
latitude = lat;
longitude = log;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mapImage != null) {
int x = (getWidth() - mapImage.getWidth())/2;
int y = (getHeight() - mapImage.getHeight())/2;
g.drawImage(mapImage, x, y, this);
FontMetrics fm = g.getFontMetrics();
g.drawString(latitude + "x" + longitude, 0, fm.getAscent());
}
}
}
public class LoadMapTask extends SwingWorker<BufferedImage, Object> {
private String latitude;
private String longitude;
private MapPane mapPane;
private JButton master;
public LoadMapTask(JButton master, MapPane mapPane, String latitude, String lonitude) {
this.mapPane = mapPane;
this.latitude = latitude;
this.longitude = lonitude;
this.master = master;
}
@Override
protected BufferedImage doInBackground() throws Exception {
BufferedImage mapImage = null;
try {
URL map = new URL("http://maps.google.com/staticmap?center=" + latitude + "," + longitude + "&zoom=5&size=500x500");
System.out.println(map);
mapImage = ImageIO.read(map);
} catch (Exception exp) {
exp.printStackTrace();
}
return mapImage;
}
@Override
protected void done() {
try {
mapPane.setMap(latitude, longitude, get());
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
master.setEnabled(true);
}
}
}
向我們展示了您是如何嘗試去做的。 – jlordo
如果你的'longitude'和'lat'變量改變了,'map'和'mapImage'變量什麼都沒有發生,所以'repaint()'不會顯示任何不同的東西。 – jlordo
顯示你的'map()'調用,或更多的相關代碼。你如何處理'map()'的返回值? – jlordo