怎么在java面板中显示一张图片

怎么在java面板中显示一张图片,第1张

是这样的,你在面板上搞一个和面板一样大的JLabel

然后,通过JFileChooser获得路径,利用这个图片的路径,构建一个ImageIcon

最后,根据这个ImageIcon去给JLabel对象setIcon(ImageIcon对象)

具消早体地:

1.panel.add(label,BorderLayout.CENTER)

2.ImageIcon icon = new ImageIcon(url)

3.label.setIcon(icon)

下面的代码你把 .JPG改成BMP试试看,O(∩灶返_∩)O~

package com.shlq.sample

import java.awt.BorderLayout

import java.awt.event.WindowAdapter

import java.awt.event.WindowEvent

import javax.swing.ImageIcon

import javax.swing.JFrame

import javax.swing.JLabel

import javax.swing.JPanel

public class ImagePane extends JPanel

{

JLabel jl = null

ImageIcon img = null

public ImagePane()

{

img = new ImageIcon( "E:\\Picture\隐桥饥\1.jpg ")

jl = new JLabel(img)

this.setLayout(new BorderLayout())

this.add(jl, BorderLayout.CENTER)

}

public static void main(String[] args)

{

JFrame test = new JFrame( "Image Pane ")

test.getContentPane().add(new ImagePane())

test.pack()

test.setVisible(true)

test.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

System.exit(0)

}

})

}

}

有两个问题:

图片路径没有写对,图片在 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)

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12527989.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-26
下一篇 2023-05-26

发表评论

登录后才能评论

评论列表(0条)

保存