2012-11-26 2 views
2

이 코드는 MVC 디자인 재잘를 사용하는 다음 코드중복 값과 몇 가지 방법이

package test; 


import java.awt.*; 
import java.awt.event.*; 
import java.beans.PropertyChangeEvent; 
import java.beans.PropertyChangeListener; 

import javax.swing.*; 
import javax.swing.event.SwingPropertyChangeSupport; 

public class MainGui { 
    public MainGui() { 
     new WizardPanel().setVisible(true); 
    } 

    public static void main(String[] args) { 
     try { 
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
     new MainGui(); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
    } 
} 

class WizardPanel extends JDialog { 
    private JPanel cardPanel, buttonPanel; 
    private JButton next; 
    private CardLayout c1; 
    private SimpleModel simpleModel = new SimpleModel(); 

    private FileSelector fileSelector; 
    private DelemeterSelector delemeterSelector; 

    public WizardPanel() { 
     fileSelector = FileSelector.getInstance(); 
     delemeterSelector = DelemeterSelector.getInstance(); 

     fileSelector.setModel(simpleModel); //!! 
     delemeterSelector.setModel(simpleModel); //!! 

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

     cardPanel.add(fileSelector, "1"); 
     cardPanel.add(delemeterSelector, "2"); 

     c1.show(cardPanel, "1"); 

     buttonPanel = new JPanel(); 
     buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); 

     next = new JButton("Next"); 
     next.addActionListener(new WizardPanel.NextButtonAction()); 

     buttonPanel.add(next); 

     // Creating the GUI 
     this.setLayout(new BorderLayout()); 
     this.add(cardPanel, "Center"); 
     this.add(buttonPanel, "South"); 

     this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     this.setResizable(true); 
     this.pack(); 
     this.setVisible(true); 

    } 

    private class NextButtonAction implements ActionListener { 
     public void actionPerformed(ActionEvent ae) { 

     // c1.show(cardPanel, "2"); 
     c1.next(cardPanel); //!! 

     } 
    } 
} 

class FileSelector extends JPanel { 
    private JLabel fileName, description; 
    private JTextField fileTxt; 
    private JButton browse; 

    private GridBagLayout gbl; 
    private GridBagConstraints gbc; 
    private SimpleModel simpleModel; 

    private static FileSelector instance = null; 

    private FileSelector() { 
     // Intializing instance variables 
     fileName = new JLabel("File Name: "); 
     description = new JLabel("Specify the source of the data"); 

     fileTxt = new JTextField(10); 

     browse = new JButton("Browse"); 
     browse.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      if (simpleModel != null) { 
       simpleModel.setFileText(fileTxt.getText()); 
      } 
     } 
     }); 

     gbl = new GridBagLayout(); 
     gbc = new GridBagConstraints(); 

     // Creating GUI 
     this.setLayout(new GridLayout(2,1)); 

     this.add(description); 
     this.add(locationPanel()); 


     this.setBorder(BorderFactory.createEmptyBorder()); 
    } 

    public void setModel(SimpleModel simpleModel) { 
     this.simpleModel = simpleModel; 
    } 

    private JPanel locationPanel() { 
     JPanel panel = new JPanel(); 
     panel.setLayout(new FlowLayout()); 

     panel.add(fileName); 
     panel.add(fileTxt); 
     panel.add(browse); 

     return panel; 
    } 

    public static FileSelector getInstance() { 
     if (instance == null) { 
     instance = new FileSelector(); 
     } 

     return instance; 
    } 
} 

class DelemeterSelector extends JPanel { 
    private JLabel description; 
    private JRadioButton tabBtn, semicolanBtn, commaBtn, spaceBtn; 
    private JTextArea txtArea; 
    private JScrollPane scroll; 
    private ButtonGroup btnGroup; 

    private GridBagLayout gbl; 
    private GridBagConstraints gbc; 
    private SimpleModel simpleModel; 

    private String str; 

    private static DelemeterSelector instance = null; 

    private DelemeterSelector() { 
     description = new JLabel(
      "What delemeter separates your fields? Select the appropreiate delemeter"); 

     tabBtn = new JRadioButton("Tab"); 
     tabBtn.addItemListener(new RadioAction()); 
     semicolanBtn = new JRadioButton("Semicolan"); 
     semicolanBtn.addItemListener(new RadioAction()); 
     commaBtn = new JRadioButton("Comma"); 
     commaBtn.addItemListener(new RadioAction()); 
     spaceBtn = new JRadioButton("Space"); 
     spaceBtn.addItemListener(new RadioAction()); 

     btnGroup = new ButtonGroup(); 
     btnGroup.add(tabBtn); 
     btnGroup.add(semicolanBtn); 
     btnGroup.add(commaBtn); 
     btnGroup.add(spaceBtn); 

     txtArea = new JTextArea(20, 70); 

     scroll = new JScrollPane(txtArea); 

     gbl = new GridBagLayout(); 
     gbc = new GridBagConstraints(); 

     this.setLayout(new GridLayout(3,1)); 

     // Creating the GUI 
     this.add(description); 
     this.add(radioPanel()); 
     this.add(scroll);  
    } 

    private JPanel radioPanel() { 
     JPanel panel = new JPanel(); 
     panel.setLayout(new FlowLayout()); 

     panel.add(tabBtn); 
     panel.add(semicolanBtn); 
     panel.add(commaBtn); 
     panel.add(spaceBtn); 

     panel.setBorder(BorderFactory 
      .createTitledBorder("Choose the Delimeter that seperates your fields")); 

     return panel; 
    } 

    //!! 
    public void setModel(final SimpleModel simpleModel) { 
     this.simpleModel = simpleModel; 
     simpleModel.addPropertyChangeListener(new PropertyChangeListener() { 

     @Override 
     public void propertyChange(PropertyChangeEvent evt) { 
      txtArea.append("File Text: " + simpleModel.getFileText() + "\n");    
     } 
     }); 
    } 

    public static DelemeterSelector getInstance() { 
     if (instance == null) { 
     instance = new DelemeterSelector(); 
     } 

     return instance; 
    } 

    private class RadioAction implements ItemListener 
    { 
     public void itemStateChanged(ItemEvent ae) 
     { 
      if(ae.getStateChange()==ItemEvent.SELECTED){ 
      if(ae.getSource().equals(commaBtn)) 
      { 
       str = "."; 
      } 
      else if(ae.getSource().equals(spaceBtn)) 
      { 
       str = " "; 
      } 
      else if(ae.getSource().equals(semicolanBtn)) 
      { 
       str = ";"; 
      } 

      simpleModel.setDelemeter(str);} 
     } 
    } 
} 

class SimpleModel { 
    public static final String FILE_TEXT = "file text"; 
    public static final String FILE_DELEMETER = "dELEMETERtext"; 
    private SwingPropertyChangeSupport pcSupport = 
     new SwingPropertyChangeSupport(this); 
    private String fileText; 
    private String str; 

    public void addPropertyChangeListener(PropertyChangeListener listener) { 
     pcSupport.addPropertyChangeListener(listener); 
    } 

    public void removePropertyChangeListener(PropertyChangeListener listener) { 
     pcSupport.removePropertyChangeListener(listener); 
    } 

    public void setFileText(String fileText) { 
     String oldValue = this.fileText; 
     String newValue = fileText; 
     this.fileText = fileText; 
     pcSupport.firePropertyChange(FILE_TEXT, oldValue , newValue); 

    } 

    public String getFileText() { 
     return fileText; 
    } 

    public void setDelemeter(String str) 
    { 
     String oldValue = this.str; 
     String newValue = str; 
     this.str = str; 
     pcSupport.firePropertyChange(FILE_DELEMETER, oldValue , newValue); 

     System.out.println(str); 
    } 

} 

에서 참조하시기 바랍니다. 첫 번째 슬라이딩 윈도우에서 JTextField의 텍스트를 기록합니다. 사용자가 두 번째 창으로 이동하면 첫 번째 창에 입력 한 텍스트가 JTextArea에 표시됩니다.

이제 할당 된 라디오 버튼 중 하나를 클릭하십시오. JTextArea가 첫 번째 창에 입력 된 데이터를 표시하고있는 것을 볼 수 있습니다. 심지어 그 곳에서 getFileText() 메서드를 호출하지 않습니다. getFileText() 메서드를 계속 호출하고 JRadioButton을 클릭 할 때마다 JTextArea를 계속 업데이트하는 것처럼 보입니다. 하지만 JRadioButton의 액션 클래스 안에서는 결코 그런 액션을 요구하지 않았습니다.

왜이 오류가 발생하고 있습니까? 도와주세요!

+1

당신은 훨씬 단순한 코드가됩니다. 또한 무국적으로 만들었으므로 RadioButtonAction을 여러 번 인스턴스화 할 필요가 없습니다. 한번 인스턴스화하고 어디서나 설정할 수 있습니다. 그리고 btw, 당신은 오타가 있습니다 : 그것은 "Delemeter"가 아니라 "구분 기호"입니다 –

+0

원래 코드를 완료했습니다. 그러나 문제는 여전히 거기에있다 : ( –

답변

3

귀하의 문제가이 라인 :

이와 함께
simpleModel.addPropertyChangeListener(new PropertyChangeListener() { 

    @Override 
    public void propertyChange(PropertyChangeEvent evt) { 
     txtArea.append("File Text: " + simpleModel.getFileText() + "\n");    
    } 
    }); 

:

public void setFileText(String fileText) { 
     String oldValue = this.fileText; 
     String newValue = fileText; 
     this.fileText = fileText; 
     pcSupport.firePropertyChange(FILE_TEXT, oldValue , newValue); 

    } 

    public void setDelemeter(String str) 
    { 
     String oldValue = this.str; 
     String newValue = str; 
     this.str = str; 
     pcSupport.firePropertyChange(FILE_DELEMETER, oldValue , newValue); 

     System.out.println(str); 
    } 

당신은 (코드의 첫 번째 세트) 해고 속성의 이름을 검사하지 않는, 따라서 setFileText 또는 setDelemeter이 호출되면 firePropertyChange이 실행되어 파일 이름을 표시합니다.

쉬운 솔루션과 같이 속성의 이름을 확인하는 것입니다 : 당신이 대신 된 ItemListener의 ActionListener를 사용하는 경우

simpleModel.addPropertyChangeListener(new PropertyChangeListener() { 

    @Override 
    public void propertyChange(PropertyChangeEvent evt) { 
     if(evt.getPropertyName().equale(SimpleModel.FILE_TEXT) 
      txtArea.append("File Text: " + simpleModel.getFileText() + "\n");    
    } 
    }); 
+0

굉장! 고마워요! 정말 감사!! –

2

나는 모든 코드를 검토하지는 않았지만 라디오 버튼을 변경할 때 두 가지 이벤트가 발생한다는 점에 유의하십시오. 첫 번째 버튼을 선택 취소하고 새 버튼을 선택합니다.

ItemEvent에서 상태를 확인할 수 있습니다. ItemEvent#getStateChangeItemEvent.SELECTEDItemEvent.DESELECTED 상수를 참조하십시오.

단추가 선택 될 때만 동작을 트리거하려면 ActionListener을 라디오 단추에 연결하는 것이 더 쉽습니다. 이것은 radio button tutorial에 나와 있습니다.

+0

회신 로빈 감사합니다 :). 내 두 번째 질문에 대한 대답을 주셨습니다. 첫 번째 질문에도 도움을 주시겠습니까? "getFileText() 메서드를 계속 호출하고 JRadioButton을 클릭 할 때마다 JTextArea를 계속 업데이트하는 것처럼 보입니다.하지만 JRadioButton의 액션 클래스에서는 결코 그런 액션을 호출하지 않습니다. 방금 측정기를 설정했습니다! " –

+0

이미 두 번째 질문을 편집하고 제거 했으므로 이미 답변 해주었습니다. –

관련 문제