CardLayout标签重叠

时间:2018-03-21 19:40:08

标签: java jpanel overlay cardlayout

我有一个非常简单的CardLayout示例代码。问题是当我放入不同的卡片元素,例如JTextFieldsJTextAreas时,在运行Java示例时,这些元素会叠加在第一张卡片上(参见屏幕截图)。

当我点击切换按钮时,要在标签之间切换,问题就会消失(每个元素都在卡片上应该是),但是当我第一次运行代码全部或部分时(或者没有,有时它)正确显示前视图上的JTextField/Areas重叠。谁能向我解释一下我做错了什么?

screenshot

以下是代码:

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

public class temporary{

    CardLayout cards = new CardLayout();
    JPanel topPanel = new JPanel();
    JPanel bottomPanel = new JPanel();
    JButton switchButton = new JButton("Switch!");



    temporary(){

        JFrame ramka = new JFrame("CardLayout Example");

        topPanel.add(switchButton);
        ListenForButton lForButton = new ListenForButton();
        switchButton.addActionListener(lForButton);


        //panel1
        JPanel panel1 = new JPanel();

        JTextField text1 = new JTextField("TextExample1", 50);
        JTextField text2 = new JTextField(50);
        panel1.add(text1);
        panel1.add(text2);


        //panel2        
        JPanel panel2 = new JPanel();

        JTextField text3 = new JTextField("TextExample2",40);
        panel2.add(text3);

        //panel3
        JPanel panel3 = new JPanel();

        JTextField text4 = new JTextField("TextExample3", 20);
        panel3.add(text4);

        panel1.setBackground(Color.white);
        panel2.setBackground(Color.lightGray);
        panel3.setBackground(Color.gray);

        bottomPanel.add(panel1);
        bottomPanel.add(panel2);
        bottomPanel.add(panel3);

        bottomPanel.setLayout(cards);
        cards.show(bottomPanel, "CardLayout");

        ramka.getContentPane().add(topPanel, BorderLayout.NORTH);
        ramka.getContentPane().add(bottomPanel, BorderLayout.CENTER);

        ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ramka.setSize(1200, 700);
        ramka.setLocationRelativeTo(null);
        ramka.setVisible(true);
    }

    public static void main(String[] args){
        new temporary();
    }

    public class ListenForButton implements ActionListener{
        public void actionPerformed(ActionEvent e){
            cards.next(bottomPanel);
        }
    }
}

0 个答案:

没有答案