java Swing第4集:BorderLayout和CardLayout

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Swing第4集:BorderLayout和CardLayout相关的知识,希望对你有一定的参考价值。

import javax.swing.*;
import java.awt.*;

public class Main {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Episode 4");
        frame.setLocation(100,100);
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container content = frame.getContentPane();

        content.add(new JButton("Center"), BorderLayout.CENTER);
        content.add(new JButton("North"), BorderLayout.NORTH);
        content.add(new JButton("South"), BorderLayout.SOUTH);
        content.add(new JButton("West"), BorderLayout.WEST);
        content.add(new JButton("East"), BorderLayout.EAST);
        //Second set goes on top of first
        content.add(new JButton("Center2"), BorderLayout.CENTER);
        content.add(new JButton("North2"), BorderLayout.PAGE_START); //Same as North
        content.add(new JButton("South2"), BorderLayout.PAGE_END); //Same as South
        content.add(new JButton("West2"), BorderLayout.LINE_START); //If Left-Right, then its left. If right-left, its right
        content.add(new JButton("East2"), BorderLayout.LINE_END);//If Left-Right, then its right. If right-left, its left
        
        frame.pack();
        frame.setVisible(true);
        //episode 4 almost done lil boi(or gurl)
    }
}
import javax.swing.*;
import java.awt.*;

public class Main {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Episode 4");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        // Add a Next JButton in a JPanel to the content pane
        JPanel buttonPanel = new JPanel();
        JButton nextButton = new JButton("Next");
        buttonPanel.add(nextButton);
        contentPane.add(buttonPanel, BorderLayout.SOUTH);
        // Create a JPanel and set its layout to CardLayout
        final JPanel cardPanel = new JPanel();
        final CardLayout cardLayout = new CardLayout();
        cardPanel.setLayout(cardLayout);
        // Add five JButtons as cards to the cardPanel
        for (int i = 1; i <= 5; i++) {
            JButton card = new JButton("Card " + i);
            card.setPreferredSize(new Dimension(200, 200));
            cardPanel.add(card);
        }
        // Add the cardPanel to the content pane
        contentPane.add(cardPanel, BorderLayout.CENTER);
        // Add an action listener to the Next button
        nextButton.addActionListener(e -> cardLayout.next(cardPanel));
        frame.pack();
        frame.setVisible(true);

        //episode 4 done lil boi(or gurl)
    }
}

以上是关于java Swing第4集:BorderLayout和CardLayout的主要内容,如果未能解决你的问题,请参考以下文章

java Swing第5集:BoxLayout

java Swing第3集:FlowLayout

java Swing第1集:制作JFrame

java Swing第2集:向JFrame添加组件

我想用javaswing 做出这样的界面,要怎么做

《Java Swing》第4节:事件处理与监听器