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

Python014

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)

}

}

其实有很多种方法可以解决图片显示大小的问题:

使用photoshop修改. 优点是可以节省系统资源, 显示图片的时候,不用做处理,缺点是需要了解ps的基本操作

使用JDialog 自定义对话框. 优点 可以实现复杂的效果, 缺点,代码量比较多

使用ImageIcon, Image 类 实现图片的缩放,. 优点: 纯java代码解决, 缺点: 如果大量的图片需要缩放, 那么可能影响程序的速度.

方案3的代码如下

import java.awt.Image

import javax.swing.ImageIcon

import javax.swing.JOptionPane

public class Test {

public static void main(String[] args) {

ImageIcon icon = new ImageIcon("imgs/1.png") // 得到icon对象 .注意我的图片地址和你的不一样,注意修改!!

Image image = icon.getImage() //icon--->Image

float scale = 0.5f //缩放比例 50%

int width = Math.round(icon.getIconWidth()*scale) // 变小 50%的宽

int height= Math.round(icon.getIconHeight()*scale)// 变小50%的高

Image miniIcon = image.getScaledInstance(width, height, Image.SCALE_SMOOTH)

// image 变成指定大小. 缩放模式为 SCALE_SMOOTH(平滑优先)

ImageIcon smallIcon = new ImageIcon(miniIcon)// Image--->icon

JOptionPane.showInputDialog(null, "吃了吗?", "标题", 0, smallIcon, null, "默认值")

}

}

效果图

图1 图片显示比例为原图的50%

图2 图片显示比例为原图的120%

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

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()

}

}