我有一个JButton
,我厌倦了从我的电脑上加载一个图标。
如何从网上打开图像?我试图添加类似地址,但它并没有显示在按钮上。
ImageIcon icon = new ImageIcon("http://s22.postimg.org/4gttei2rl/nv070_binary_jpg.jpg");
jButton1.setIcon(icon);
答案 0 :(得分:0)
考虑这段代码 - 它会处理您遇到的几个问题:
考虑到这一点,这是工作代码:
public class Panel extends JPanel {
public Panel() throws InterruptedException, IOException {
JButton btnNewButton = new JButton();
URL url = new URL("http://s22.postimg.org/4gttei2rl/nv070_binary_jpg.jpg");
URLConnection uc = url.openConnection();
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
ImageIcon icon = new ImageIcon(IOUtils.toByteArray(uc.getInputStream()));
btnNewButton.setIcon(icon);
add(btnNewButton);
}
public static void main(String[] a) {
try {
JOptionPane.showMessageDialog(null, new Panel());
} catch (Exception e) {
e.printStackTrace();
}
}
}