📄 showcardlayout.java
字号:
// ShowCardLayout.java: Using CardLayout to display images
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ShowCardLayout extends JApplet
implements ActionListener, ItemListener
{
private CardLayout queue = new CardLayout();
private JPanel cardPanel = new JPanel();
private JButton jbtFirst, jbtNext, jbtPrevious, jbtLast;
private JComboBox jcboImage;
public void init()
{
// Use CardLayout for cardPanel
cardPanel.setLayout(queue);
// Add 15 labels for displaying images into cardPanel
for (int i=1; i<=15; i++)
cardPanel.add
(new JLabel(new ImageIcon("images/L"+i+".gif")),
String.valueOf(i));
// Panel p to hold buttons and a combo box
JPanel p = new JPanel();
p.add(jbtFirst = new JButton("First"));
p.add(jbtNext = new JButton("Next"));
p.add(jbtPrevious= new JButton("Previous"));
p.add(jbtLast = new JButton("Last"));
p.add(new JLabel("Image"));
p.add(jcboImage = new JComboBox());
// Initialize combo box items
for (int i=1; i<=15; i++)
jcboImage.addItem(String.valueOf(i));
// Place panels in the frame
getContentPane().add(cardPanel, BorderLayout.CENTER);
getContentPane().add(p, BorderLayout.NORTH);
// Register listeners with the source objects
jbtFirst.addActionListener(this);
jbtNext.addActionListener(this);
jbtPrevious.addActionListener(this);
jbtLast.addActionListener(this);
jcboImage.addItemListener(this);
}
// This main method enables the applet to run as an application
public static void main(String[] args)
{
// Create a frame
JFrame frame = new JFrame("CardLayout Demo");
// Create an instance of the applet
ShowCardLayout applet = new ShowCardLayout();
// Add the applet instance to the frame
frame.getContentPane().add(applet, BorderLayout.CENTER);
// Invoke init() and start()
applet.init();
applet.start();
// Display the frame
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
// Handle button actions
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof JButton)
if ("First".equals(actionCommand))
// Show the first component in queue
queue.first(cardPanel);
else if ("Last".equals(actionCommand))
// Show the last component in queue
queue.last(cardPanel);
else if ("Previous".equals(actionCommand))
// Show the previous component in queue
queue.previous(cardPanel);
else if ("Next".equals(actionCommand))
// Show the next component in queue
queue.next(cardPanel);
}
// Handle selection of combo box item
public void itemStateChanged(ItemEvent e)
{
if (e.getSource() == jcboImage)
// Show the component at specified index
queue.show(cardPanel, (String)e.getItem());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -