2017-02-27 49 views
-1

我需要1-5頁的運行訂單。在每個頁面上輸入數據後,我正在使用卡布局在每個頁面之間導航。導航到下一個頁面通過每個文本字段上的Action Listener工作。卡布局 - 從以前的卡獲取輸入

我的問題是如何將每張卡片/頁面的輸入傳遞給下一個?我可以在每個TextFeilds數據的System.out.println。但是我無法在下一張卡片/動作偵聽器中獲取這些信息。我需要這樣做的原因是我想比較每個頁面的字符串,並在頁面/ card2上顯示頁面1的輸入標籤。

對於大量代碼塊,我很抱歉...大多數人都會識別大部分代碼,因爲它是從CardLayout示例java代碼複製的。我剛剛添加了兩張牌,直到我獲得了將變量傳回第四個的基礎知識。

即使小推向正確的方向,所有的幫助表示讚賞。

import java.awt.*; 
import java.awt.CardLayout; 
import java.awt.Dimension; 
import java.awt.event.*; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.util.Scanner; 
import javax.swing.*; 

public class CardLayoutDemo implements ItemListener { 
    JPanel cards; //a panel that uses CardLayout 
    final static String TEXTPANEL = "Card1 with text"; 
    final static String TEXTPANEL2 = "Card with JTextField"; 

public void addComponentToPane(Container pane) { 
     //Put the JComboBox in a JPanel to get a nicer look. 
     JPanel comboBoxPane = new JPanel(); //use FlowLayout 
     String comboBoxItems[] = { TEXTPANEL, TEXTPANEL2}; 
     JComboBox cb = new JComboBox(comboBoxItems); 
     cb.setEditable(false); 
     cb.addItemListener(this); 
     comboBoxPane.add(cb); 

    //Create the "cards". 

    JPanel card1 = new JPanel(); 
     JTextField jtf=new JTextField("", 40); 
     jtf.setSize(40, 10); 
     card1.add(jtf); 

     JLabel lab1 = new JLabel("Page1 Text", JLabel.LEFT); 
      card1.add(lab1 = new JLabel("Page1")); 

    JPanel card2 = new JPanel(); 
     JTextField jtf2=new JTextField("", 40); 
     jtf2.setSize(40, 10); 
    card2.add(jtf2); 
     JLabel lab2 = new JLabel("Page2 Text", JLabel.LEFT); 
     card2.add(lab2 = new JLabel("Page2 ")); 

    //Create the panel that contains the "cards". 
    cards = new JPanel(new CardLayout()); 
    cards.add(card1, TEXTPANEL); 
    cards.add(card2, TEXTPANEL2); 
    pane.add(cards, BorderLayout.CENTER); 

jtf.addActionListener(new ActionListener(){ 

public void actionPerformed(ActionEvent e) 
{ 

    String getText1 = jtf.getText(); 
       System.out.println("PAGE1 "); 
       System.out.println(getText1); 

    CardLayout cl = (CardLayout)(cards.getLayout()); 
    cl.show(cards, TEXTPANEL2); 
     jtf2.requestFocus(); 
     jtf2.requestFocusInWindow(); 


    } 


    //JOptionPane.showMessageDialog(null,"Action Listener is working"); 
    }); 


    //PAGE2 

    jtf2.addActionListener(new ActionListener(){ 

    public void actionPerformed(ActionEvent e) 
    { 

    String getText2 = jtf2.getText(); 
       System.out.println("PAGE2 "); 
       System.out.println(getText2); 

    CardLayout cl = (CardLayout)(cards.getLayout()); 
    cl.show(cards, TEXTPANEL); 
     jtf.requestFocus(); 
     jtf.requestFocusInWindow(); 
     jtf.setText(""); 

    } 

    }); 

    }//ADD COMPONENT TO PANE 

    public void itemStateChanged(ItemEvent evt) { 
    CardLayout cl = (CardLayout)(cards.getLayout()); 
    cl.show(cards, (String)evt.getItem()); 

    //  String getLoginUser1 = jtf.getText(); 
    //System.out.println(getLoginUser1); 


    } 

    /** 
    * Create the GUI and show it. For thread safety, 
    * this method should be invoked from the 
    * event dispatch thread. 
    */ 
    private static void createAndShowGUI() { 
     //Create and set up the window. 
     JFrame frame = new JFrame("CardLayoutDemo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setPreferredSize(new Dimension(600, 300)); 
     JFrame.setDefaultLookAndFeelDecorated(true); 

    //Create and set up the content pane. 
    CardLayoutDemo demo = new CardLayoutDemo(); 
    demo.addComponentToPane(frame.getContentPane()); 

    //Display the window. 
    frame.pack(); 
    frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
    /* Use an appropriate Look and Feel */ 
    try { 
     //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
     UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
    } catch (UnsupportedLookAndFeelException ex) { 
     ex.printStackTrace(); 
    } catch (IllegalAccessException ex) { 
     ex.printStackTrace(); 
    } catch (InstantiationException ex) { 
     ex.printStackTrace(); 
    } catch (ClassNotFoundException ex) { 
     ex.printStackTrace(); 
    } 


    /* Turn off metal's use of bold fonts */ 
    UIManager.put("swing.boldMetal", Boolean.FALSE); 

    //Schedule a job for the event dispatch thread: 
    //creating and showing this application's GUI. 
    javax.swing.SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGUI(); 

     } 
    }); 
    } 
    } 
+0

粗略瀏覽一下你的問題表明你想要使用模型 - 視圖 - 控制器或MVC類型模式,以便模型(底層程序邏輯和數據)從視圖(GUI)中提取出來。 –

+0

...........你好?? –

+0

你好,謝謝你的回覆:)我很抱歉花了一段時間才能回來。今天我會看看這個,我一直在忙着其他的事情,我沒有機會實施所提到的建議... –

回答

0

你得埋在addComponentToPane(...)方法中關鍵部件的變量聲明中,只限制其範圍,以這種方法,防止你得到你所需要的信息。雖然這種問題的典型解決方案是使用模型視圖控制器或MVC類型模式,以便模型(底層程序邏輯和數據)從視圖(GUI)中提取出來,但您可以快速和骯髒的解決方案只是通過給你的變量私人類作用域

例如,如果JTextField的被稱爲文本框,並充當「卡」一個JPanel舉行,說叫CardPanel都,你可以創建一個看起來像這樣一類:

public class CardPanel extends JPanel { 
    // constants to give the GUI a bigger size 
    private static final int PREF_W = 300; 
    private static final int PREF_H = 100; 

    // our key JTextField declared at class level 
    private JTextField textField = new JTextField(20); 

    // a JLabel to display the previous cardpanel's text 
    private JLabel label = new JLabel(" "); 

    // create the JPanel 
    public CardPanel(String name) { 
     setName(name); 
     setBorder(BorderFactory.createTitledBorder("Panel " + name)); 
     JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); 
     labelPanel.add(new JLabel("Prior Card's Word: ")); 
     labelPanel.add(label); 

     setLayout(new BorderLayout()); 
     add(textField, BorderLayout.PAGE_START); 
     add(labelPanel, BorderLayout.CENTER); 
    } 

    // have to jump through this hoop if we want to JTextField to 
    // have focus when a card is swapped 
    public void setFocusOnTextField() { 
     textField.requestFocusInWindow(); 
     textField.selectAll(); 
    } 

    // to make our GUI larger 
    @Override 
    public Dimension getPreferredSize() { 
     if (isPreferredSizeSet()) { 
      return super.getPreferredSize(); 
     } 
     return new Dimension(PREF_W, PREF_H); 
    } 

    // allow outside classes to add a listener to the JTextField 
    public void addActionListener(ActionListener listener) { 
     textField.addActionListener(listener); 
    } 

    // allow outside classes to get text from the text field 
    public String getTextFieldText() { 
     return textField.getText(); 
    } 

    // allow outside classes to put text into the JLabel 
    public void setLabelText(String text) { 
     label.setText(text); 
    } 
} 

而且那麼我們就可以使用它,像這樣:

public class MyCardLayoutDemo extends JPanel { 
    private static final String[] NAMES = {"One", "Two", "Three", "Four"}; 
    private Map<String, CardPanel> namePanelMap = new HashMap<>(); 
    private CardLayout cardLayout = new CardLayout(); 
    private int nameIndex = 0; 

    public MyCardLayoutDemo() { 
     setLayout(cardLayout); 
     MyListener listener = new MyListener(); 

     for (String name : NAMES) { 
      CardPanel cardPanel = new CardPanel(name); 
      cardPanel.addActionListener(listener); 
      add(cardPanel, name); 
      namePanelMap.put(name, cardPanel); 
     } 
    } 

    private class MyListener implements ActionListener { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      // get the current CardPanel 
      String name = NAMES[nameIndex]; 
      CardPanel currentCard = namePanelMap.get(name); 

      // advance the name index to get the next CardPanel 
      nameIndex++; 
      nameIndex %= NAMES.length; 
      name = NAMES[nameIndex]; 
      CardPanel nextCard = namePanelMap.get(name); 

      // get text from current CardPanel 
      String text = currentCard.getTextFieldText(); 
      nextCard.setLabelText(text); // and put it into next one 

      // swap cards 
      cardLayout.show(MyCardLayoutDemo.this, name); 
      nextCard.setFocusOnTextField(); 
     } 
    } 

    private static void createAndShowGui() { 
     MyCardLayoutDemo mainPanel = new MyCardLayoutDemo(); 

     JFrame frame = new JFrame("My CardLayout Demo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> createAndShowGui()); 
    } 
} 
1

這裏是關於問題的另一種看法。您可以創建某種卡片管理器,並在其中保存所有必需的信息。這裏是一個例子:

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

public class CardLayoutDemo implements ItemListener { 

    private static class QuizManager { 
     final java.util.List<String> quizData = new ArrayList<>(); 
     final java.util.List<JPanel> cards = new ArrayList<>(); 
     final JPanel rootView; 

     public QuizManager(JPanel root){ 
      rootView = root; 
     } 

     private JPanel createQuizPanel(String pageText, final int index) { 
      JPanel card = new JPanel(); 
      JTextField jtf=new JTextField("", 40); 
      jtf.setSize(40, 10); 
      JLabel prev = new JLabel("", JLabel.LEFT); 
      card.add(prev); 
      card.add(jtf); 
      card.add(new JLabel(pageText, JLabel.LEFT)); 


      jtf.addActionListener(new ActionListener() { 
       public void actionPerformed(ActionEvent e) { 
        QuizManager.this.onCardSubmited(card, index, jtf.getText()); 
       } 
      }); 

      card.addComponentListener(new ComponentAdapter() { 
       @Override 
       public void componentShown(ComponentEvent e) { 
        super.componentShown(e); 
        jtf.requestFocus(); 
        jtf.requestFocusInWindow(); 
        String text = QuizManager.this.getPrevStringFor(index); 
        if (text != null) { 
         prev.setText(text); 
        } 
       } 
      }); 

      return card; 
     } 

     private String getPrevStringFor(int index) { 
      if (index == 0) return null; 

      return quizData.get(index-1); 
     } 
     private String buildPanelName(int index) { 
      return String.format("card-%d", index); 
     } 
     public QuizManager addCard(String title) { 
      int index = cards.size(); 
      quizData.add(null);//not set yet, just allocating 
      JPanel card = createQuizPanel(title, index); 
      cards.add(card);//this array looks like redundant 
      rootView.add(card, buildPanelName(index)); 
      return this; 
     } 

     private void showCard(int index) { 
      CardLayout cl = (CardLayout) (rootView.getLayout()); 
      cl.show(rootView, buildPanelName(index)); 
     } 

     public void show() { 
      showCard(0); 
     } 

     public void onCardSubmited(JPanel card, int cardIndex, String text) { 
      System.out.println("page " + cardIndex); 
      System.out.println("text : " + text); 
      quizData.set(cardIndex, text); 
      if (cardIndex < cards.size() - 1) { 
       showCard(cardIndex + 1); 
      } else { 
       System.out.println("WE FINISHED"); 
       //add finalazing code here 
      } 
     } 
    } 

    JPanel cardsRoot; 
    public void addComponentToPane(Container pane) { 
     cardsRoot = new JPanel(new CardLayout()); 
     QuizManager manager = new QuizManager(cardsRoot) 
       .addCard("First page") 
       .addCard("Second page") 
       .addCard("Third card") 
       .addCard("Forth card"); 

     pane.add(cardsRoot, BorderLayout.CENTER); 
     manager.show(); 
    } 

    public void itemStateChanged(ItemEvent evt) { 
     CardLayout cl = (CardLayout)(cardsRoot.getLayout()); 
     cl.show(cardsRoot, (String)evt.getItem()); 
    } 

    /** 
    * Create the GUI and show it. For thread safety, 
    * this method should be invoked from the 
    * event dispatch thread. 
    */ 
    private static void createAndShowGUI() { 
     //Create and set up the window. 
     JFrame frame = new JFrame("CardLayoutDemo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setPreferredSize(new Dimension(600, 300)); 
     JFrame.setDefaultLookAndFeelDecorated(true); 

     //Create and set up the content pane. 
     CardLayoutDemo demo = new CardLayoutDemo(); 
     demo.addComponentToPane(frame.getContentPane()); 

     //Display the window. 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
    /* Use an appropriate Look and Feel */ 
     try { 
      //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
     } catch (UnsupportedLookAndFeelException ex) { 
      ex.printStackTrace(); 
     } catch (IllegalAccessException ex) { 
      ex.printStackTrace(); 
     } catch (InstantiationException ex) { 
      ex.printStackTrace(); 
     } catch (ClassNotFoundException ex) { 
      ex.printStackTrace(); 
     } 


    /* Turn off metal's use of bold fonts */ 
     UIManager.put("swing.boldMetal", Boolean.FALSE); 

     //Schedule a job for the event dispatch thread: 
     //creating and showing this application's GUI. 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 

      } 
     }); 
    } 
} 

看看創建許多卡是多麼容易。

+0

謝謝,這是我期待做的,有沒有一種方法來添加每個頁面的數組輸入? –

+0

它已經在'QuizManager' - 'quizData'的列表中。只需添加一個getter方法即可解壓出來,如果您需要它可以訪問 – j2ko

+0

Дякую!我真的很感激幫助:)! –