2013-05-06 4 views
2

많은 질문을 많이 받았지만 문제가 해결되지 않았습니다. 나는 자바에서 상당히 새로운 편이다. JTextField에서 일부 입력을 얻으려고하고 String으로 반환하므로 다른 클래스에서 비교할 때 사용할 수 있습니다. 이것은 내가 대답으로 보는 것입니다, 나는이 클래스의 다른 부분에서 str을 사용할 수 있기를 바랍니다.자바 스윙이 JTextField에서 입력 받기

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Container; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JTextArea; 

public class ClassFrame extends JFrame { 

private static final long serialVersionUID = 2451829341034438685L; 

public static JButton inputButton = new JButton("Send"); 
public static JTextArea editTextArea = new JTextArea("Type Here!"); 
public static JTextArea uneditTextArea = new JTextArea(); 

public ClassFrame(String title) { 
    //SET LAYOUT MANAGER (How it arranges components) 
setLayout(new BorderLayout()); 
//////CREATE SWING COMPONENTS//////////// 
//OUTPUT TEXT AREA 
uneditTextArea.setEditable(false); 

//INPUT TEXT AREA 
editTextArea.setBackground(Color.BLUE); 
editTextArea.setForeground(Color.WHITE); 

//SET CONTENT PANE 
Container c = getContentPane(); 

//ADD COMPONENTS TO CONTENT PANE   
c.add(uneditTextArea, BorderLayout.CENTER); 
c.add(editTextArea, BorderLayout.SOUTH); 
c.add(inputButton, BorderLayout.WEST); 

ClassFrame.inputButton.addActionListener(new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     String str = editTextArea.getText(); 
     editTextArea.setText(" "); 
     System.out.println(str);     
    } 
}); 
} 
} 
+2

정적 변수를 사용하지 마십시오! – camickr

+0

간단한'actionListener'와'field.getSource()'는 당신을 놀라게 할 것입니다. – Tdorno

답변

5

내 의견보기

package applet; 

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Container; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 


import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JTextArea; 


public class ClassFrame extends JFrame { 


    private static final long serialVersionUID = 2451829341034438685L; 

    public static JButton inputButton = new JButton("Send"); 
    public static JTextArea editTextArea = new JTextArea("Type Here!"); 
    public static JTextArea uneditTextArea = new JTextArea(); 

    // MA - Your String, defined here and usable throughout the class 

    private String myString; 

    public ClassFrame(String title) { 

     // MA - Indent your code properly so that it's more readable to both you 
     // and others 

     //SET LAYOUT MANAGER (How it arranges components) 
     setLayout(new BorderLayout()); 
     //////CREATE SWING COMPONENTS//////////// 
     //OUTPUT TEXT AREA 
     uneditTextArea.setEditable(false); 

     //INPUT TEXT AREA 
     editTextArea.setBackground(Color.BLUE); 
     editTextArea.setForeground(Color.WHITE); 

     //SET CONTENT PANE 
     Container c = getContentPane(); 

     //ADD COMPONENTS TO CONTENT PANE   
     c.add(uneditTextArea, BorderLayout.CENTER); 
     c.add(editTextArea, BorderLayout.SOUTH); 
     c.add(inputButton, BorderLayout.WEST); 

     ClassFrame.inputButton.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 

       // MA - Using the class field myString to receive text from text area 

       myString = editTextArea.getText(); 

       // MA - Don't use a space when you actually want an empty string. 
       // As it stands, your code will test for a single space character. 
       // You really want it to test whether the text area is empty. 

       //editTextArea.setText(" "); 

       // MA - Do this instead. An empty string means the text area has 
       // no input at all. 

       editTextArea.setText(""); 

       System.out.println(myString);     
      } 
     }); 
    } 
} 

Java에서 변수 범위 지정에 대해 읽는 것이 좋습니다. 당신은 구글 수 있습니다.

+0

uneditTextArea는 여기서 무엇을합니까? 이 코드 예에서는 관계없는 것으로 나타납니다. –

+0

원본 포스터의 질문에 따라 Swing 컨트롤에서 텍스트를 가져 오는 방법을 데모하기 위해 코드 샘플을 변경했습니다. 그 목적을 위해, 나는'uneditTextArea'가 무엇인지 알지도 않고 신경도 쓰지 않습니다. 원래 코드 샘플을 제공 한 사람에게 물어보십시오 (4 년 후에도 기억한다고 가정). – MarsAtomic

2

질문에 대한 나의 이해에서, 문자열을 비교하고 출력을 JTextArea에 첨부하는 간단한 예제가 있습니다.

enter image description here

public class Test 
{ 
    private static String ENTER = "Enter"; 
    static JButton enterButton; 
    public static JTextArea output; 
    public static JTextField input; 
    static JFrame frame; 
    static JPanel panel; 
    public static String testString = "test"; 

    public static void main(String... args) 
    { 
     try 
     { 
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
     } 
     catch (Exception ex) 
     { 
      ex.printStackTrace(); 
     } 
     createFrame(); 
    } 

    public static void createFrame() 
    { 
     frame = new JFrame("Test"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     panel = new JPanel(); 
     panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 
     panel.setOpaque(true); 
     ButtonListener buttonListener = new ButtonListener(); 
     output = new JTextArea(15, 50); 
     output.setWrapStyleWord(true); 
     output.setEditable(false); 
     JScrollPane scroller = new JScrollPane(output); 
     scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
     scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 
     JPanel inputpanel = new JPanel(); 
     inputpanel.setLayout(new FlowLayout()); 
     input = new JTextField(20); 
     enterButton = new JButton("Enter"); 
     enterButton.setActionCommand(ENTER); 
     enterButton.addActionListener(buttonListener); 
     // enterButton.setEnabled(false); 
     input.setActionCommand(ENTER); 
     input.addActionListener(buttonListener); 
     DefaultCaret caret = (DefaultCaret) output.getCaret(); 
     caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); 
     panel.add(scroller); 
     inputpanel.add(input); 
     inputpanel.add(enterButton); 
     panel.add(inputpanel); 
     frame.getContentPane().add(BorderLayout.CENTER, panel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     // Center of screen 
     // frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
     frame.setResizable(false); 
     input.requestFocus(); 
    } 

    public static class ButtonListener implements ActionListener 
    { 

     public void actionPerformed(final ActionEvent ev) 
     { 
      if (!input.getText().trim().equals("")) 
      { 
       String cmd = ev.getActionCommand(); 
       if (ENTER.equals(cmd)) 
       { 
        output.append(input.getText()); 
        if (input.getText().trim().equals(testString)) output.append(" = " + testString); 
        else output.append(" != " + testString); 
        output.append("\n"); 
       } 
      } 
      input.setText(""); 
      input.requestFocus(); 
     } 
    } 
} 
+1

'JTextArea # append()'는 더 이상 Java 7에서는 thread-safe가 아닙니다. – trashgod

+1

@trashgod이 프로젝트는 필자가 스레드를 필요로하는 것으로부터 추출한 것입니다. 더 이상 필요 없으므로 제거했습니다. – syb0rg