62,614
社区成员
发帖
与我相关
我的任务
分享
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BackgroundExample {
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame frame = new JFrame("Rich");
final String[] images = {"background/01.jpg",
"background/02.jpg",
"background/03.jpg",
"background/04.jpg"};
final JComboBox backgrounds;
final BackgroundPanel backgroundPanel = new BackgroundPanel();
backgrounds = new JComboBox(images);
//backgrounds.setSelectedIndex(1);
backgrounds.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
JComboBox box = (JComboBox)e.getSource();
String background = (String)box.getSelectedItem();
try {
backgroundPanel.changeBackground(background);
backgroundPanel.repaint();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
frame.setUndecorated(false);
backgroundPanel.setOpaque(false);
frame.getContentPane().add(backgroundPanel,BorderLayout.CENTER);
frame.getContentPane().add(backgrounds,BorderLayout.NORTH);
frame.setBounds(100, 100, 750, 560);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class BackgroundPanel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 11111111111111L;
private BufferedImage background;
private TexturePaint texture;
public void changeBackground(final String image) throws IOException {
this.background = ImageIO.read(this.getClass().getClassLoader().getResource(image));
Rectangle rect = new Rectangle(0,0,this.background.getWidth(),this.background.getHeight());
this.texture = new TexturePaint(this.background,rect);
}
@Override
public void paintComponent(final Graphics g) {
if(this.texture!= null) {
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(this.texture);
g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
}
super.paintComponent(g);
}
}
import javax.swing.*;
import java.awt.*;
@SuppressWarnings("serial")
class PicPanel extends JPanel {
int p_width = 0;
int p_height = 0;
Image im = null;
public PicPanel(String picName) {
ImageIcon imageIcon = new ImageIcon(picName);
im = imageIcon.getImage();
p_width = imageIcon.getIconWidth();
p_height = imageIcon.getIconHeight();
setBounds(0, 0, p_width, p_height);
}
public void paint(Graphics g) {
g.drawImage(im, 0, 0, p_width, p_height, null);
}
}