import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ExampleFrame_02 extends JFrame {
private JPanel cardPanel;
private CardLayout cardLayout;
public static void main(String[] args) {
ExampleFrame_02 frame = new ExampleFrame_02();
frame.setVisible(true);
}
public ExampleFrame_02() {
super();
setTitle("卡片布局管理器");
setBounds(100, 100, 600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cardLayout = new CardLayout();
cardPanel = new JPanel(cardLayout);
getContentPane().add(cardPanel, BorderLayout.CENTER);
String[] labelNames = {"D:\\tank_Img\\double.jpg", "D:\\tank_Img\\max.jpg", "D:\\tank_Img\\solo.jpg", "D:\\qingwa.png"};
for (int i = 0; i < labelNames.length; i++) {
final JLabel label = new JLabel(new ImageIcon(labelNames[i]));
label.setHorizontalAlignment(SwingConstants.CENTER);
//label.setFont(new Font("", Font.BOLD, 16));
label.setForeground(new Color(255, 0, 0));
cardPanel.add(label, labelNames[i].substring(11));
}
final JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
String[] buttonNames = {"第一个", "前一个", "后一个", "最后一个"};
for (int i = 0; i < buttonNames.length; i++) {
final JButton button=new JButton(buttonNames[i]);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String buttonText=button.getText();
if (buttonText.equals("第一个")) {
cardLayout.first(cardPanel);
} else if (buttonText.equals("前一个")) {
cardLayout.previous(cardPanel);
} else if (buttonText.equals("后一个")) {
cardLayout.next(cardPanel);
} else if (buttonText.equals("最后一个")) {
cardLayout.last(cardPanel);
}
}
});
buttonPanel.add(button);
}
}
}