2

我有一个 JFrame,我在其中从外部类创建和删除面板,问题是,当我来回移动时(多次删除和创建面板,我不希望引用所有面板,所有应该传递的数据on (frame and boolean [即将实现]) 将在构造函数中)它将整个内容向下移动。

我正在使用GridBagLayout,也许这有一些隐藏的问题。我不想使用 CardLayout,所以请不要推荐它。

为什么会这样做,我应该怎么做才能阻止它?

代码

deleteContract = new JButton("Usuń kontrakt");
        deleteContract.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {

                ACDeleteContract ACDeleteContract = new ACDeleteContract(frame);
                removeAll();
            add(ACDeleteContract);
            revalidate();
            repaint();
        }
    });
    deleteContract.setPreferredSize(new Dimension(200, 50));
    c.gridy = 2;
    menu.add(deleteContract, c);

    back = new JButton("Powrót");
    back.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
           ACMenu menu = new ACMenu(frame);
           removeAll();
           add(menu);
           revalidate();
           repaint();
       } 
    });
4

1 回答 1

2

好吧,安德鲁·汤普森(Andrew Thompson)引导我走上了我之前不想走的好路。

对于后代的一些提示:D。

在你的框架中做

CardLayout cards = new CardLayout();
    JPanel cardPanel = new JPanel();
    cardPanel.setLayout(cards);

    ACReadContract ACReadContract = new ACReadContract(cards, cardPanel);
    //your external JPanel classes with arguments such as above
    ACMenu ACMenu = new ACMenu(cards, cardPanel);

    cardPanel.add(ACMenu, "Menu");
    cardPanel.add(ACReadContract, "ReadContract");
    //naming and adding them for easy moving between them

    //adding this to frame
    add(cardPanel);

在外部类中(构造函数的开始,类应该扩展 JPanel)

private JPanel menu, cardPanel1;
private CardLayout cardLayout1;

public ACMenu(CardLayout cardLayout, JPanel cardPanel) {

    cardLayout1=cardLayout;
    cardPanel1 = cardPanel;

在外部类中的动作监听器

cardLayout1.next(cardPanel1);

或者

cardLayout1.show(cardPanel1, "ReadContract");

我希望我对那些有类似问题的人有所帮助。

于 2012-12-16T11:30:03.163 回答