Java 使用文件目录(而不是URL)显示图像
当我链接到程序上的图像(当前代码)时,程序工作。当我将其替换为URL(“”)时,程序将在不显示图像的情况下运行。我尝试过很多变化,但都没有成功。有人知道为什么它不起作用吗Java 使用文件目录(而不是URL)显示图像,java,Java,当我链接到程序上的图像(当前代码)时,程序工作。当我将其替换为URL(“”)时,程序将在不显示图像的情况下运行。我尝试过很多变化,但都没有成功。有人知道为什么它不起作用吗 public class ImageViewer extends JFrame { public ImageViewer() { //create panel of actions JPanel actionPanel = new JPanel(); actionPanel.setLayout(new
public class ImageViewer extends JFrame {
public ImageViewer() {
//create panel of actions
JPanel actionPanel = new JPanel();
actionPanel.setLayout(new GridLayout(1, 4));
actionPanel.add(new JButton("Prev"));
actionPanel.add(new JButton("Add"));
actionPanel.add(new JButton("Del"));
actionPanel.add(new JButton("Next"));
//Create panel to hold pictures
JLabel label= new JLabel(new ImageIcon("C:/Users/Madison/Desktop/capture.png"), JLabel.CENTER);
JPanel imagePanel = new JPanel(new BorderLayout());
imagePanel.add(label, BorderLayout.CENTER );
//Add contents to frame
add(imagePanel, BorderLayout.NORTH);
add(actionPanel, BorderLayout.SOUTH);
}
public static void main (String args []){
ImageViewer frame = new ImageViewer();
frame.setTitle("Title");
frame.setSize(1000, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}您是否相应地编辑代码? 不能用url替换路径 试试这个:
URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg"); //set url
ImageIcon image = new ImageIcon(ImageIO.read(url)); //read image and create ImageIcon
JLabel label = new JLabel(image, JLabel.CENTER);
请记住检查
IO
和MalformedURL
异常 明白了。我是新手,所以我没有意识到这一点。非常感谢。