java swing换背景图片
发布网友
发布时间:2022-05-02 15:51
我来回答
共1个回答
热心网友
时间:2022-06-20 18:12
// 回答完毕,采纳即可
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Bar extends JPanel
{
private static final long serialVersionUID = 1L;
private JButton open;
private static final int W = 300;
private static final int H = 300;
public Bar()
{
super(new BorderLayout());
JPanel panel = new JPanel();
open = new JButton("打开");
open.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JDialog dialog = new JDialog();
dialog.setTitle("设置背景图");
dialog.setSize(160, 60);
dialog.setModal(true);
dialog.setLocationRelativeTo(Bar.this);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final JComboBox comboBox = new JComboBox(new String[]{ "图片a", "图片b" });
dialog.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
try
{
int index = comboBox.getSelectedIndex();
switch(index)
{
case 0:
img = ImageIO.read(Bar.class.getResource("a.jpg"));
Bar.this.repaint();
break;
case 1:
img = ImageIO.read(Bar.class.getResource("layout.png"));
Bar.this.repaint();
break;
default:
break;
}
}
catch(IOException e1)
{
e1.printStackTrace();
}
}
});
dialog.add(comboBox);
dialog.setVisible(true);
}
});
panel.add(open);
add(panel, BorderLayout.PAGE_START);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
Image img = null;
@Override
public void paint(Graphics g)
{
super.paint(g);
g.clearRect(0, 0, W, H);
g.drawImage(img, 0, 0, null);
g.dispose();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("bar");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Bar b = new Bar();
b.setOpaque(true);
frame.setContentPane(b);
frame.setSize(W, H);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}