Выпуск CardLayout - PullRequest
       79

Выпуск CardLayout

1 голос
/ 16 марта 2012

У меня есть макет карты, первая карта - это меню.

Я выбираю вторую карту и выполняю некоторые действия. Мы скажем добавить JTextField, нажав кнопку. Если я вернусь к карточке меню, а затем вернусь ко второй карточке, тот JTextField, который я добавил в первый раз, все еще будет там.

Я хочу, чтобы вторая карта была такой, какой я ее изначально создавал, каждый раз, когда получаю к ней доступ, с помощью кнопок, но без текстового поля.

Ответы [ 2 ]

1 голос
/ 19 марта 2012

Вот окончательно отсортированная версия, чтобы вынуть карту, после внесения в нее изменений, посмотрите, используйте обычные вещи revalidate() и repaint(): -)

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

public class ApplicationBase extends JFrame
{
    private JPanel centerPanel;
    private int topPanelCount = 0;

    private String[] cardNames = {
                                                        "Login Window",
                                                        "TextField Creation"
                                                   };

    private TextFieldCreation tfc;
    private LoginWindow lw;

    private JButton nextButton;
    private JButton removeButton;

    private ActionListener actionListener = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            if (ae.getSource() == nextButton)
            {   
                    CardLayout cardLayout = (CardLayout) centerPanel.getLayout();
                    cardLayout.next(centerPanel);
            }
            else if (ae.getSource() == removeButton)
            {
                    centerPanel.remove(tfc);
                    centerPanel.revalidate();
                    centerPanel.repaint();
                    tfc = new TextFieldCreation();
                    tfc.createAndDisplayGUI();  
                    centerPanel.add(tfc, cardNames[1]);
            }
        }
    };

    private void createAndDisplayGUI()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        centerPanel = new JPanel();
        centerPanel.setLayout(new CardLayout());

        lw = new LoginWindow();
        lw.createAndDisplayGUI();
        centerPanel.add(lw, cardNames[0]);
        tfc = new TextFieldCreation();
        tfc.createAndDisplayGUI();
        centerPanel.add(tfc, cardNames[1]);

        JPanel bottomPanel = new JPanel();
        removeButton = new JButton("REMOVE");
        nextButton = new JButton("NEXT");       
        removeButton.addActionListener(actionListener);
        nextButton.addActionListener(actionListener);

        bottomPanel.add(removeButton);
        bottomPanel.add(nextButton);

        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);

        pack();
        setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new ApplicationBase().createAndDisplayGUI();
            }
        });
    }
}

class TextFieldCreation extends JPanel
{
    private JButton createButton;
    private int count = 0;

    public void createAndDisplayGUI()
    {
        final JPanel topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(0, 2));

        createButton = new JButton("CREATE TEXTFIELD");
        createButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                JTextField tfield = new JTextField();
                tfield.setActionCommand("JTextField" + count);

                topPanel.add(tfield);
                topPanel.revalidate();
                topPanel.repaint();
            }
        });

        setLayout(new BorderLayout(5, 5));
        add(topPanel, BorderLayout.CENTER);
        add(createButton, BorderLayout.PAGE_END);
    }
}

class LoginWindow extends JPanel
{
    private JPanel topPanel;
    private JPanel middlePanel;
    private JPanel bottomPanel;

    public void createAndDisplayGUI()
    {
        topPanel = new JPanel();

        JLabel userLabel = new JLabel("USERNAME : ", JLabel.CENTER);
        JTextField userField = new JTextField(20);
        topPanel.add(userLabel);
        topPanel.add(userField);

        middlePanel = new JPanel();

        JLabel passLabel = new JLabel("PASSWORD : ", JLabel.CENTER);
        JTextField passField = new JTextField(20);
        middlePanel.add(passLabel);
        middlePanel.add(passField);

        bottomPanel = new JPanel();

        JButton loginButton = new JButton("LGOIN");
        bottomPanel.add(loginButton);

        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        add(topPanel);
        add(middlePanel);
        add(bottomPanel);
    }
}

Если вы просто хотите удалить Latest Edit, сделанный на карту, попробуйте этот код:

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

public class ApplicationBase extends JFrame
{
    private JPanel centerPanel;
    private int topPanelCount = 0;

    private String[] cardNames = {
                                                        "Login Window",
                                                        "TextField Creation"
                                                   };

    private TextFieldCreation tfc;
    private LoginWindow lw;

    private JButton nextButton;
    private JButton removeButton;

    private ActionListener actionListener = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            if (ae.getSource() == nextButton)
            {   
                    CardLayout cardLayout = (CardLayout) centerPanel.getLayout();
                    cardLayout.next(centerPanel);
            }
            else if (ae.getSource() == removeButton)
            {
                    TextFieldCreation.topPanel.remove(TextFieldCreation.tfield);
                    TextFieldCreation.topPanel.revalidate();
                    TextFieldCreation.topPanel.repaint();
            }
        }
    };

    private void createAndDisplayGUI()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        centerPanel = new JPanel();
        centerPanel.setLayout(new CardLayout());

        lw = new LoginWindow();
        lw.createAndDisplayGUI();
        centerPanel.add(lw, cardNames[0]);
        tfc = new TextFieldCreation();
        tfc.createAndDisplayGUI();
        centerPanel.add(tfc, cardNames[1]);

        JPanel bottomPanel = new JPanel();
        removeButton = new JButton("REMOVE");
        nextButton = new JButton("NEXT");       
        removeButton.addActionListener(actionListener);
        nextButton.addActionListener(actionListener);

        bottomPanel.add(removeButton);
        bottomPanel.add(nextButton);

        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);

        pack();
        setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new ApplicationBase().createAndDisplayGUI();
            }
        });
    }
}

class TextFieldCreation extends JPanel
{
    private JButton createButton;
    private int count = 0;
    public static JTextField tfield;
    public static JPanel topPanel;

    public void createAndDisplayGUI()
    {
        topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(0, 2));

        createButton = new JButton("CREATE TEXTFIELD");
        createButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                tfield = new JTextField();
                tfield.setActionCommand("JTextField" + count);

                topPanel.add(tfield);
                topPanel.revalidate();
                topPanel.repaint();
            }
        });

        setLayout(new BorderLayout(5, 5));
        add(topPanel, BorderLayout.CENTER);
        add(createButton, BorderLayout.PAGE_END);
    }
}

class LoginWindow extends JPanel
{
    private JPanel topPanel;
    private JPanel middlePanel;
    private JPanel bottomPanel;

    public void createAndDisplayGUI()
    {
        topPanel = new JPanel();

        JLabel userLabel = new JLabel("USERNAME : ", JLabel.CENTER);
        JTextField userField = new JTextField(20);
        topPanel.add(userLabel);
        topPanel.add(userField);

        middlePanel = new JPanel();

        JLabel passLabel = new JLabel("PASSWORD : ", JLabel.CENTER);
        JTextField passField = new JTextField(20);
        middlePanel.add(passLabel);
        middlePanel.add(passField);

        bottomPanel = new JPanel();

        JButton loginButton = new JButton("LGOIN");
        bottomPanel.add(loginButton);

        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        add(topPanel);
        add(middlePanel);
        add(bottomPanel);
    }
}
1 голос
/ 16 марта 2012

Убедитесь, что панель, которую вы пытаетесь сбросить, имеет код, который возвращает ее в исходное состояние.Затем, когда вы обрабатываете любое событие, которое вызывает смену карт, вызовите этот код, чтобы восстановить исходное состояние, прежде чем показывать карту.

...