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

Python013

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)

}

}

}