如题,我现在做好了一个带背景图片的窗口,文件选择器也写好了,该怎么实现选中文件改变背景,求大神指点。
package com.xfonlineclass1;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class textBack extends JFrame implements ActionListener {
JPanel jp1, jp2;
JLabel label, imgLabel;
JButton btnChoose;
JFileChooser fileChoose;
File filBackground;
Image image,image2;
Container cp ;
public textBack(){
image = new ImageIcon("background\\1.jpg").getImage();
//System.out.println(image);
// 将背景图放在"标签"里。
imgLabel = new aLabel(image);
// 将背景标签添加到jfram的LayeredPane面板里
this.getLayeredPane().add(imgLabel, new Integer(Integer.MIN_VALUE));
cp = this.getContentPane();
//将内容面板设为透明
((JPanel) cp).setOpaque(false);
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setLocation(width / 2 - 200, height / 2 - 150);
this.setTitle("choose background");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
this.setResizable(false);
this.setVisible(true);
jp1 = new JPanel();
jp1.setLayout(null);
jp1.setOpaque(false);
this.add(jp1);
btnChoose = new JButton("Choose");
btnChoose.setBounds(30, 30, 80, 30);
jp1.add(btnChoose);
btnChoose.addActionListener(this);
// 设置背景标签的位置
imgLabel.setBounds(0, 0, this.getWidth(),this.getHeight());
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source.equals(btnChoose)) {
ChooseBackground();
}
}
public void ChooseBackground(){
//在这里选中图片文件,更改背景
fileChoose = new JFileChooser("D:\\");
int result = fileChoose.showOpenDialog(this);
if(result == JFileChooser.APPROVE_OPTION){
filBackground = fileChoose.getSelectedFile();
System.out.println(filBackground.getName());
}
}
//内部类
private class aLabel extends JLabel{
private Image image;
public aLabel(Image image){
this.image = image;
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
int x = this.getWidth();
int y = this.getHeight();
g.drawImage(image, 0, 0, x, y, null);
}
}
public static void main(String[] args){
new textBack();
}
}
------解决思路----------------------
ImageIcon image = new ImageIcon(filBackground.getAbsolutePath());
int imageWidth = (int) imgLabel.getSize().getWidth();
int imageHeight = (int) imgLabel.getSize().getHeight();
image.setImage(image.getImage().getScaledInstance(imageWidth , imageHeight , Image.SCALE_DEFAULT));
imgLabel.setIcon(image);
------解决思路----------------------
在aLabel类里添加
public void setImage(Image img) {
this.image = img;
}
在ChooseBackground方法的if里添加
imgLabel.setImage(new ImageIcon(filBackground.getPath()).getImage());