(는 "메가"ActionListener
을 쓰기를 다시 나란히 놓이는 같은 단일 Action
또는 ActionListener
교체) 기능을 대체 할 쉽게?
구성 요소를 참조하려면 인스턴스 변수를 만드십시오.
actionPerformed
메서드를 구현하려면 ActionListener
을 구현하는 클래스를 만듭니다. 이것은 익명의 클래스 또는 명명 된 클래스가 될 수 있습니다.
이 예제에서는 익명 내부 클래스로 두 개의 ActionListeners를 만듭니다.
이 마지막 예에서 나타낸 바와 같이
public class Scratch extends JFrame
implements java.awt.event.ActionListener // <- implements ActionListener
{
JButton button1 = new JButton("Click Me");
public Scratch() {
// layout, etc.
add(button1);
button1.addActionListener(this); // <- tell button1 to call my actionPerformed()
}
@Override
public void actionPerformed(java.awt.event.ActionEvent event) {
Object component = event.getSource(); // which control was clicked?
if (component == button1) {
// do something in response to button1 click event
}
}
}
우리에 ActionEvent.getSource()
방법을 사용할 수있다 :이 일부 예에서 Scratch.java
import javax.swing.*;
public class Scratch extends JFrame {
JButton button1 = new JButton("Click Me");
JCheckBox check1 = new JCheckBox("Check Me");
JRadioButton radio1 = new JRadioButton("Select Me");
JComboBox<String> combo1 = new JComboBox<String>(new String[] {"Choose Me", "No me!"});
public Scratch() {
setPreferredSize(new java.awt.Dimension(50, 170));
setLayout(new java.awt.FlowLayout());
add(radio1);
add(check1);
add(combo1);
add(button1);
radio1.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent event) {
check1.setSelected(!radio1.isSelected());
}
});
button1.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
combo1.setSelectedIndex(combo1.getSelectedIndex() == 0 ? 1 : 0);
}
});
pack();
}
public static void main(String[] args) {
new Scratch().setVisible(true);
}
}
는 Scratch
클래스 자체는 ActionListener
인 어떤 구성 요소가 이벤트를 트리거했는지 발견하십시오.
이 질문을 읽는 누군가에게 경고 : 응답을 방해하지 마세요,이 사람은 좋은 대답을 upvote하지 않지만 그의 기초적인 수학 코드가 작동하지 않는 방법에 대한 끝없는 논평 토론을 계속합니다. – gknicker
불행히도 귀하의 답변을 투표 할 수 없습니다. Lool man, 여기 upvotes 또는 다른 사람들을 돕기 위해 찾고 있습니까? 다른 사람들을 돕는 것이 투표를 구걸하는 것보다 훨씬 중요하다고 생각합니다! 어쨌든 도와 주셔서 감사합니다! 신의 축복이 있습니다! – user3545953
교환이라고합니다. 사람들은 당신을 도우며, 당신은 무언가를 대가로줍니다. 그러나 당신은 사람들이 당신을 도울 것으로 기대하고, 당신은 아무것도 돌려주지 않습니다. – gknicker