2014-06-16 2 views
0

실제로 저는 초보자입니다. 그래서 두 개의 입력 필드가 두 개의 입력란에 사용자가 채우는 Swing을 사용하여 GUI를 만들려고 했으므로 새 텍스트 필드가 있습니다. 입력 된 2 개의 값을 더하고 싶습니다.Swing을 사용하여 입력 용 텍스트 필드가있는 GUI

2 개의 텍스트 필드의 정수를 추가하고 두 개의 값을 모두 추가하고 다른 텍스트 필드에 표시하려고합니다. JTextField 정수 값을 다른 JTextField에 어떻게 추출합니까? // 오류 : 내가 메시지 대화 상자 국지적 인 문제에 합계 값을 검색 할 수있는이 편집 된 코드에서

import java.io.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
public class GUI 
{ 
public JFrame f; 
    public JPanel p; 
    public JLabel l1,l2; 
    public JButton b1; 
    public JButton b2; 
    public JTextField t1; 
    public JTextField t2; 
    public JTextField t3; 
    public GUI() 
     { 
      f=new JFrame("hello world application"); 
      p=new JPanel(true); 
      l1=new JLabel("enter first number"); 
      t1=new JTextField(30); 
      l2=new JLabel("\n enter the second number"); 
      t2=new JTextField(30); 
      t3=new JTextField(30); 
      b1=new JButton("check here"); 
      b2=new JButton("clear all"); 
      //b1.addActionCommand1("checking...."); 
      //b2.addActionCommand2("clearing all input's ...."); 

     } 
    public void launch() 
     { 
      f.setSize(400,500); 
      p.add(l1); 
      p.add(t1); 
      p.add(l2); 
      p.add(t2); 
      p.add(t3); 
      p.add(b1); 
      p.add(b2); 
      f.pack(); 
      f.add(p); 

      //l.setFont(Times Roman); 
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      p.setSize(400,500); 
      p.setForeground(Color.red); 
      p.setBackground(Color.green); 
      f.setLayout(new BorderLayout()); 
      b1.addActionListener(new Button1handler(t1,t2,t3)); 
      b2.addActionListener(new Button2handler()); 
      f.setVisible(true); 


     } 
    public static void main(String a[]) 
     { 
      javax.swing.SwingUtilities.invokeLater(new Runnable() 
       { 
        public void run() 
         { 
          GUI br=new GUI(); 
          br.launch(); 

         } 
       }); 
     } 
} 

class Button1handler implements ActionListener 
{ 

       private JTextField t1; 
    private JTextField t2; 
    private JTextField t3; 
      public Button1handler(JTextField t1, JTextField t2, JTextField t3) 
        { 
        this.t1 = t1; 
        this.t2 = t2; 
        this.t3 = t3; 
    } 
     public void actionPerformed(ActionEvent e) 
     { 
    System.out.println("action occurred for checking"); 
    String firstnumber=t1.getText(); 
    String secondnumber=t2.getText(); 
    int num1=Integer.parseInt(firstnumber); 
    int num2=Integer.parseInt(secondnumber); 
    int sum=num1+num2; 
      String str=Integer.toString(sum); 
      String sum2=t3.setText(str); 
    JOptionPane.showMessageDialog(null, "The sum is " + sum,"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE); 



     } 
} 
class Button2handler implements ActionListener 
{ 
    public void actionPerformed(ActionEvent r) 
     { 
      System.out.println("clearing all"); 

     } 
}   

내가 3 JtextField.It에서 특정 문자열이 줄에 오류가 표시 얻을 수 있다는 것입니다 호환되지 않는 유형 문자열 sum2 = t3.setText (str); 이 필요합니다 : 찾을 문자열 : 무효 1 오류 :(

답변

2

를 코드를 실행받지 않고, 여기에 문제가 ...

t3.setText(total); 

JTextField 있기 때문에 setText(int) 방법이없는 대신 당신에게. String에 값을 변환해야합니다.

예를

를 들어, 당신은 Integer.toString(total)를 사용할 수 있지만, 대신 NumberFormat.getNumberInstance().format(total))를 사용하는 것이 더 나은 결과를 얻을 수 있습니다
t3.setText(NumberFormat.getNumberInstance().format(total)); 

업데이트 나에서 빙빙 실행했다 당신이 "기타"문제는, Button1handler은,이 의미 GUI

class Button1handler extends GUI implements ActionListener { 

확장한다는 사실은

때를 그 t1t2 필드에 액세스하십시오.이 필드는 화면의 필드와 같지 않으므로 값이 비어 있습니다.

당신의 ActionListener는 외부 파일/클래스의 경우, 예를 들어, 클래스에 컨텍스트를 제공해야합니다 ...

class Button1handler implements ActionListener { 

    private JTextField f1; 
    private JTextField f2; 
    private JTextField f3; 

    public Button1handler(JTextField f1, JTextField f2, JTextField f3) { 
     this.f1 = f1; 
     this.f2 = f2; 
     this.f3 = f3; 
    } 

    public void actionPerformed(ActionEvent e) { 
     int firstnumber = Integer.parseInt(f1.getText()); 
     int secondnumber = Integer.parseInt(f2.getText()); 
     int total = firstnumber + secondnumber; 
     f3.setText(NumberFormat.getNumberInstance().format(total)); 
    } 
} 

는 그런 다음 작업 처리기의 새로운 인스턴스를 만들어야합니다 ...이 화면에서 사용자에 의해 조작되어있는 실제 필드에 대한 참조를 사용하여 액션 핸들러를 제공

b1.addActionListener(new Button1handler(t1, t2, t3)); 

... 같은 것을 사용

Nested Classes (참조를 전달해야하는)이 요구 사항을 능가하는 몇 가지 추가 기능을 제공하지만, 이동하기 전에 객체의 컨텍스트를 매우 정교해야합니다.)

+0

나에게 설명 할 수 있습니까? 코드 조각 : t3.setText (NumberFormat.getNumberInstance(). format (total)); "NumberFormat"에 대한 오류가 발생합니다. – user3522245

+0

"오류가 발생했습니다"또는 컴파일러 오류가 발생합니까? 컴파일러 오류 일 경우 NumberFormat을 가져 오지 않았을 수 있습니다. IDE를 사용하고 있습니까? –

+0

단순한 텍스트 편집기를 사용하지 않고 "notepad ++" – user3522245

관련 문제