所以我有两个类,一个用于创建GUI,另一个用于处理事件。
我的GUI中有一个JCheckBox,我想在检查完JCheckBox后更改JButton的文本。
桂,这里有以下课程:
import javax.swing.*;
import java.awt.*;
public class Motion extends JFrame {
MotionEvent controller = new MotionEvent();
//row 0
JPanel row0 = new JPanel();
//row 1
JPanel row1 = new JPanel();
JButton up = new JButton("Up");
//row 2
JPanel row2 = new JPanel();
JButton left = new JButton("Left");
JButton right = new JButton("Right");
JCheckBox compassFormat = new JCheckBox("compassFormat", false);
//row 3
JPanel row3 = new JPanel();
JButton down = new JButton("Down");
Motion(){
super("Motion Detector");
setSize(500,325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layoutMaster = new GridLayout(5,1,10,10);
setLayout(layoutMaster);
add(row0);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER);
row1.setLayout(layout1);
up.addActionListener(controller);
row1.add(up);
add(row1);
GridLayout layout2 = new GridLayout(1, 3, 10, 10);
row2.setLayout(layout2);
left.addActionListener(controller);
compassFormat.addItemListener(controller);
right.addActionListener(controller);
row2.add(left);
row2.add(compassFormat);
row2.add(right);
add(row2);
FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER);
row3.setLayout(layout3);
row3.add(down);
add(row3);
setVisible(true);
}
public static void main(String[] args){
Motion passedInGui = new Motion();
}
}
事件处理程序:
import java.awt.event.*;
import javax.swing.*;
public class MotionEvent implements ActionListener, ItemListener{
public void actionPerformed(ActionEvent event){
Object objSource = event.getActionCommand();
if(objSource.equals("Up")){
JOptionPane.showMessageDialog(null, "You have moved up", "Navigator", JOptionPane.INFORMATION_MESSAGE);
}
else if(objSource.equals("Down")){
JOptionPane.showMessageDialog(null, "You have moved down", "Navigator", JOptionPane.INFORMATION_MESSAGE);
}
else if(objSource.equals("Left")){
JOptionPane.showMessageDialog(null, "You have moved left", "Navigator", JOptionPane.INFORMATION_MESSAGE);
}
else if(objSource.equals("Right")){
JOptionPane.showMessageDialog(null, "You have moved right", "Navigator", JOptionPane.INFORMATION_MESSAGE);
}
}
public void itemStateChanged(ItemEvent event){
Object objS = event.getStateChange();
if(objS.equals(ItemEvent.SELECTED)){
JOptionPane.showMessageDialog(null, "Need help on stackOverflow", "Tester", JOptionPane.WARNING_MESSAGE);
}
}
}
我在itemStateChanged方法中创建messageDialog的行,我想用一行来替换它,该行允许我更改JButtons的文本。
类似于。。。Motion.down.setText("South"(;
我该怎么做?我知道我需要一个某种类型的引用变量。引用变量必须在方法中定义,因为如果它在方法外部,就会发生stackerflow错误。
公共类Motion{
private String buttonLabel;
public Motion(){
MotionEvent evt = new MotionEvent(this);
}
public static void main(String args[]){
Motion m = new Motion();
}
public void setButtonLabel(String str){
this.buttonLabel = str;
}
public String getButtonLabel(){
return buttonLabel;
}
}
公共类MotionEvent{
private Motion motion;
public MotionEvent(Motion motion){
this.motion = motion;
}
public void someMethod(){
motion.setButtonLabel("SomeTxt");
}
}