该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
示例代码:
public class TryCardLayout extends JFrame {
private JButton button1 = new JButton("进入");
private JButton button2 = new JButton("返回");
private JPanel cardPane = new JPanel();
private JPanel firstPane = new JPanel();
private JPanel nextPane = new JPanel();
private static final String card1 = "1";
private static final String card2 = "2";
private CardLayout cardLayout = new CardLayout();
public TryCardLayout() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
cardPane.setLayout(cardLayout);
//card1 是对应 firstPane 的标记,要通过这个来切换界面
cardPane.add(firstPane, card1);
//card2 是对应 nextPane 的标记,要通过这个来切换界面
cardPane.add(nextPane, card2);
firstPane.add(button1);
firstPane.add(new JLabel("first"));
firstPane.setBackground(Color.CYAN);
nextPane.add(button2);
nextPane.add(new JLabel("second"));
nextPane.setBackground(Color.RED);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//通过 card2 标记切换到 nextPane
cardLayout.show(cardPane, card2);
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//通过 card1 标记切换到 firstPane
cardLayout.show(cardPane, card1);
}
});
add(cardPane);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TryCardLayout();
}
});
}
}
博客给出了Java使用按钮切换界面的示例代码。通过创建JButton和JPanel,利用CardLayout布局,为按钮添加事件监听器,根据标记实现不同面板界面的切换,如点击“进入”按钮切换到对应面板,点击“返回”按钮回到原面板。
7万+

被折叠的 条评论
为什么被折叠?



