如何在Java中访问另一个文件或类上的JButton



我有一个问题与JButton。我需要更改goPauseButton上的文本时,它已被点击,但我得到这个错误:goPauseButton cannot be resolved。我对Java很陌生,所以我开始尝试使用其他语言(如Free Pascal)的技术来解决这个问题。这里需要引用按钮所在的类,然后是按钮。在我的代码中,它看起来像这样:

PrisonersDilemma.goPauseButton.setText("Pause");

然后我得到这个错误:Cannot make a static reference to the non-static field PrisonersDilemma.goPauseButton

这是我的代码(到目前为止),我已经删除了不重要的东西:

主类

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.util.Hashtable;
//...
public class PrisonersDilemma /* possible extends... */ {
// declaring
JFrame frame;
PlayingField field;
JPanel componentPanel;
public JButton goPauseButton;
public JPanel createComponentPanel() {
componentPanel = new JPanel();
componentPanel.setLayout(new GridLayout(2,6));

// set goPauseButton
goPauseButton = new JButton("GO!");
goPauseButton.addActionListener(field);
goPauseButton.setBounds(110,350, 80,20); // first coordinates, then size
frame.add(goPauseButton);
return componentPanel;
}
void buildGUI() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
field = new PlayingField();
// set frame
frame = new JFrame("Prisoners Dilemma");
frame.add(field);
createComponentPanel();
frame.add(field, BorderLayout.CENTER);
frame.setLocation(200, 200);
frame.pack();
frame.setVisible(true);
frame.setSize(400, 450);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} );
}

类与ActionEventHandler

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JButton;
public class PlayingField extends JPanel 
implements ActionListener, 
ChangeListener {

private boolean started;
@Override
public void actionPerformed(ActionEvent e) {
// TODO
if ("GO!".equals(e.getActionCommand())){
System.out.println("GO!");
started = true;
goPauseButton.setText("Pause"); // here is the error
} else if ("Pause".equals(e.getActionCommand())){
System.out.println("Pause");
started = false;
} else if ("Reset".equals(e.getActionCommand())){
System.out.println("Reset");
}
}
}

我认为你需要改变处理这个问题的方式。PlayingField不负责修改PrisonersDilemmagoPauseButton的状态。相反,PrisonersDilemma应该更新goPauseButton并调用PlayingField

的适当方法。例如…

goPauseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
goPauseButton.setText("Pause");
field.start();
}
});

public class PlayingField extends JPanel {
public void start() {
System.out.println("GO!");
started = true;
}
public void pause() {
started = false;
System.out.println("Pause");
}
public void reset() {
System.out.println("Reset");
}
}