2012-03-16 4 views
1

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

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

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

+0

If * «как он был первоначально построен» * означает «пустой/нет компонентов», то он, кажется, больше смысла добавлять новые карты. –

+0

Просто используйте [removeLayoutComponent (...)] (http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html#removeLayoutComponent (java.awt.Component)), чтобы удалить настоящую карту из «Макета», при предыдущей кнопке нажмите, а затем добавьте новый экземпляр карты, используя [addLayoutComponent (...)] (http://docs.oracle.com/javase/7/docs/api /java/awt/CardLayout.html#addLayoutComponent(java.awt.Component, java.lang.Object)). –

+0

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

ответ

1

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

1

Вот окончательный вариант разобрали, чтобы извлечь карту, после выполнения изменений в него, смотрите, используйте 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); 
    } 
} 
+0

Что делать, если вы не удаляете компонент из CardLayout, а скорее удаляете его из самого контейнера (centerPanel)? –

+0

@HovercraftFullOfEels: Да, удалив его прямо из 'centerPanel', работала нормально, как и ожидалось. Поэтому где-то «CardLayout» не работает так, как должно быть :-) Спасибо, что нашли время, чтобы посмотреть на код. –

+0

это не ошибка, это ошибка пользователя (IMO, возможно, я не совсем понимаю) способ удаления компонента из его родителя - это _allways_, чтобы вызвать parent.remove (...), который внутренне сообщает макет .removeLayoutComponent, который очищает себя. Поэтому, если код приложения вызывает последний, этот компонент все еще находится в дочернем дереве родителя, который может или не может путать некоторого соавтора. @Hovercraft хороший улов :-) – kleopatra