2011-02-19 3 views
1

좋아, 두 개의 버튼과 화면이있는 간단한 자바 애플릿이있다. 두 버튼 모두 똑같은 기능을합니다. 나는 이것을 바꾸고 싶다. 단추 중 하나를 누를 때 수행되는 동작을 변경하는 것이 무엇인지 찾을 수 없습니다. 그들은 둘 다 똑같은 것이고 나는 이것을 원하지 않는다. 그래서 내 질문에 어떻게 줄 수 대신 "Hello world"표시하려면 인벤토리 단추를 변경할 것이라고?Java 버튼이 같은 일을 어떻게 수행합니까?

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.*; 

public class projectApplet extends JApplet implements ActionListener 
{ 
    /** 
    * 
    */ 
    private static final long serialVersionUID = 1L; 
private JTextArea textArea; 
    private int lineNumber = 0; // this is just to test 

    public void init() { 
    JPanel panel = new JPanel(); 
    textArea = new JTextArea(); 
    textArea.setBackground(Color.BLACK); 
    textArea.setForeground(Color.WHITE); 
    JScrollPane sp = new JScrollPane(textArea); 
    panel.add(sp); 

    Container window = getContentPane(); 
    window.setLayout(new BorderLayout()); 
    window.add(sp,BorderLayout.CENTER); 
    // this is just to test------------------ 

    JButton b = new JButton("Clik to add a line"); 
    b.addActionListener(this); 
    window.add(b, BorderLayout.SOUTH); 

    JButton inventory = new JButton("Inventory"); 
    inventory.addActionListener(this); 
    window.add(inventory, BorderLayout.NORTH); 
    //--------------------------------------- 
    } 

    public void actionPerformed(ActionEvent arg0) { 
     lineNumber++; 
     textArea.append("\nLine number: " + lineNumber); 

    } 
    public void actionPerformed1(ActionEvent arg0) { 
     lineNumber++; 
     textArea.append("RPFL"); 

} 
} 

답변

2

새 동작 수신기를 추가하십시오. 당신은이 이벤트를 발생시킨 버튼 체크 아웃 작업 수행 방법 내부 arg0.getSOurce() 할 수 없습니다

inventory.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent ae) { 
    textArea.append("Hello, world"); 
    } 
}); 
+0

고마워요. 나는이 답을 최대한 빨리 받아 들일 것이다! –

+0

이것은 현재의 목적을 위해 사용되지만, 어떤 동작을 일으켰는지 구분하는 기능은 event.getSource() 등을 사용하여 더 큰 애플리케이션을 개발할 때 도움이 될 것입니다. – sashank

+2

아니요, 'getSource'를 사용하지 않겠습니다. 수행 할 수있는 각 사용자 액션에 대해 서로 다른 ActionListener 또는 더 나은 Action 구현을하는 것이 낫습니다. – sjr

0

: 일반적으로 당신은 익명의 내부 클래스를 사용할 수 있습니다.

0

하나의 actionPerformed 메소드가 있고 트리거 된 버튼을 찾으십시오. 예를 들어

: 다른를 사용해야합니다 ... 그래서 내 머리 위로 떨어져 기억하는 당신이 생각해야 할 수 방법은 사용되지 않습니다()

public void actionPerformed(ActionEvent arg0) { 
    if(arg0.getLabel()=="Inventory") // Do the following 
    if(arg0.getLabel()=="Click to add a new line") // Do the following 
} 

주, getLabel ... 어쩌면 getName(). 그러나 이것은 어떤 버튼이 클릭되었는지 테스트하는 간단한 방법입니다.)

+0

자신이하는 일을 잘 모르는 경우 조언을 제공하지 않을 수도 있습니다. 원래의 포스터에는 Ben의 선의의 게시물을 모두 무시하십시오. –

+0

액션 이벤트의 getActionCommand()를 사용하여 구분할 수 있습니다. 하지만 srj의 답변에서 말한 것처럼 개별 ActionListeners를 갖는 것이 일반적으로 더 좋은 방법입니다. –

관련 문제