我有一个使用 CardLayout 的类,它有两张卡片,上面有一个按钮。我想做的是在 Windows 中放置一个类似于背景的图像,例如桌面背景。该程序最终将有几张不同的卡片,我希望能够在每张卡片上放置不同的背景。我已经尝试了在该站点上其他类似问题中提出的许多建议,以及通过谷歌搜索可以找到的任何建议,但我似乎无法让它发挥作用。我知道使用 CardLayout 我不能将面板放在面板顶部,因此将图像放在 JPanel 上是行不通的。所以我的问题是,根据下面发布的代码,有没有更好的方法来设置我的布局,以便它更好地工作,而且,我应该如何显示图像以使其位于按钮的背景中?任何帮助将不胜感激。
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Cards implements ActionListener {
private JPanel cards;
private JButton button1;
private JButton button2;
private Image backgroundImage;
public void addComponentToPane(Container pane) throws IOException {
backgroundImage = ImageIO.read(new File("background.jpg"));
//create cards
JPanel card1 = new JPanel()
{
@Override
public void paintComponent(Graphics g)
{
g.drawImage(backgroundImage, 0, 0, null);
}
};
JPanel card2 = new JPanel();
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button1.addActionListener(this);
button2.addActionListener(this);
card1.add(button1);
card2.add(button2);
//create panel that contains cards
cards = new JPanel(new CardLayout());
cards.add(card1, "Card 1");
cards.add(card2, "Card 2");
pane.add(cards, BorderLayout.SOUTH);
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
public static void createAndShowGUI() throws IOException {
//create and setup window
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create and setup content pane
Cards main = new Cards();
main.addComponentToPane(frame.getContentPane());
//display window
frame.pack();
frame.setSize(800, 600);
frame.setResizable(false);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == button1) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, "Card 2");
} else if (ae.getSource() == button2) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, "Card 1");
}
}
public static void main(String[] args) {
//set look and feel
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
//schedule job for the event dispatch thread creating and showing GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGUI();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}