Java图片显示不出来,怎么解决

Python021

Java图片显示不出来,怎么解决,第1张

有两个问题:

图片路径没有写对,图片在 src 下,图片路径应是 src/海洋.png,正确的写法应是 image = new ImageIcon("src/海洋.png")

image = new ImageIcon("src/海洋.png") 应该放在 label = new JLabel(image)前面。

如下例:

import javax.swing.*

class JPanelDemo extends JPanel {

JLabel label

JTextField text

JButton button

ImageIcon image

public JPanelDemo() {

image = new ImageIcon("src/test.png")

label = new JLabel(image)

text = new JTextField(20)

button = new JButton("确定")

add(label)

add(text)

add(button)

}

}

public class App extends JFrame {

public App() {

this.setSize(500, 400)

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

this.add(new JPanelDemo())

}

public static void main(String[] args) {

new App().setVisible(true)

}

}

--------------------------------------------------------------------------------------------

import java.awt.Graphics

import javax.swing.ImageIcon

import javax.swing.JFrame

import javax.swing.JPanel

public class ImageApp extends JFrame {

public ImageApp() {

setDefaultCloseOperation(EXIT_ON_CLOSE)

setLocationRelativeTo(null)

setSize(400, 300)

setResizable(false)

getContentPane().setLayout(null)

JPanel panel = new ImagePanel()

panel.setBounds(0, 0, 400, 300)

getContentPane().add(panel)

setVisible(true)

}

public static void main(String[] args) {

new ImageApp()

}

class ImagePanel extends JPanel {

public void paint(Graphics g) {

super.paint(g)

ImageIcon icon = new ImageIcon("D:\\14405937jqhjsppeninjf9.ico")

g.drawImage(icon.getImage(), 0, 0, 400, 300, this)

}

}

}

参考代码.  你可以对照修改

import java.awt.BorderLayout

import java.awt.Image

import java.awt.Toolkit

import javax.swing.*

public class Picture extends JFrame {

private JLabel picture

public Picture() {

ImageIcon[] icons = new ImageIcon[4]//四张图的icon对象

String photopath = ""

for (int i = 1 i <= 4 i++) {

//这里的目录是我的图片所在的目录 1.gif~4.gif

photopath = "src/images/" + i + ".gif"

Image img = Toolkit.getDefaultToolkit().createImage(photopath)

icons[i-1] = new ImageIcon(img)

}

picture = new JLabel()

JPanel jp = new JPanel()

jp.add(picture)

add(jp,BorderLayout.CENTER)

setBounds(500, 200, 200, 200)

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

int n = Integer.parseInt(JOptionPane.showInputDialog("input: "))

//先设置Jlabel应该显示的图片

picture.setIcon(icons[n-1])

//然后才开始显示窗口

this.setVisible(true)

}

public static void main(String[] args) {

new Picture()

}

}