I am a beginner to java. In second cardpanel the username and password alignment is not coming properly. Is there any way to fix it? I would also like to know what is the disadvantage of using multiple frames.

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;

    public class CardLayoutTest extends JFrame {

        private static final long serialVersionUID = 1L;
        private JPanel cardPanel, jp1, jp2, buttonPanel;
        private JLabel jl1, jl2;
        private JTextField jt1;
        private JPasswordField jt2;
        private JButton btn1, btn2;
        private CardLayout cardLayout = new CardLayout();

        public CardLayoutTest() {
            setTitle("Login");
            setSize(400, 300);
            cardPanel = new JPanel();
            buttonPanel = new JPanel();
            cardPanel.setLayout(cardLayout);
            jp1 = new JPanel();
            jp2 = new JPanel();
            jt1=new JTextField();
            jt2=new JPasswordField();
            jl1 = new JLabel("Username");
            jl2 = new JLabel("Password");
            //jp1.add(jl1);
            jp2.add(jl1);
            jp2.add(jt2);
            jp2.add(jl2);
            jp2.add(jt2);
            cardPanel.add(jp1, "1");
            cardPanel.add(jp2, "2");
            btn2 = new JButton("Show Card 2");
            btn2.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    cardLayout.show(cardPanel, "2");
                }
            });
            buttonPanel.add(btn2);
            add(cardPanel, BorderLayout.CENTER);
            add(buttonPanel, BorderLayout.SOUTH);
        }

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    CardLayoutTest frame = new CardLayoutTest();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setVisible(true);
                }
            });
        }
    }
有帮助吗?

解决方案

In second cardpanel the username and password alignment is not coming properly.

By default a JPanel uses a FlowLayout so the components are displayed on a single line.

Is there any way to fix it?

Use an appropriate layout manager (or combination of layout managers) to get the desired alignment.

Read the section from the Swing tutorial on Layout Managers for more information and examples.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top