我正在制作类似于星球大战游戏sabacc的游戏。我正在尝试创建一个已经在屏幕上有三个卡套件的Jtextfield。用户将按下按钮,根据按钮,他们按下卡套装将更改为不同的套装。如果他们获得三个相同的套房,他们就赢了。我在将文本输入屏幕时遇到问题。截至目前,我一直收到一条错误,说静态内容无法引用非静态方法。
以下是主要应用程序的代码:
if
///这就是我的错误!//
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardApp extends JFrame implements ActionListener {
private JButton oneButton,
twoButton,
threeButton;
private int width = 25;
private int height = 15;
public CardApp() {
//JPanel boardPanel = new JPanel(new GridLayout(height,width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
JTextField TextField = new JTextField(30);
Hand settingTheText = new Hand();
TextField.setText(settingTheText.ListOfCards());
oneButton = new JButton("1");
twoButton = new JButton("2");
threeButton = new JButton("3");
// Listen for events on each button
oneButton.addActionListener(this);
twoButton.addActionListener(this);
threeButton.addActionListener(this);
// Add each to the panel of buttons
buttonPanel.add(oneButton);
buttonPanel.add(twoButton);
buttonPanel.add(threeButton);
// Add everything to a main panel attached to the content pane
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel);
mainPanel.add(TextField, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setTitle("Sabacc Example by Angela Rucci");
setSize(375, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
int pressed = 0;
if (e.getSource() == oneButton){
pressed = 1;}
if (e.getSource() == twoButton){
pressed = 2;}
if (e.getSource() == threeButton){
pressed = 3;}
Hand handObject = new Hand();
这是我得到西装清单的另一个文件
String screenText = handObject.ListOfCards();
TextField.setText(screenText);
}
public static void main(String[] args) {
CardApp c = new CardApp();
}
}
答案 0 :(得分:1)
变量是方法的本地变量。 JTextField TextField仅对CardApp()可见。如果您希望它可供全班使用,请将其作为私有类成员:
public class CardApp extends JFrame implements ActionListener {
private JButton oneButton,
twoButton,
threeButton;
private int width = 25;
private private int height = 15;
// available to all methods
// better naming convention was JTextfield tf = new JTextField(30);
// even stackoverflow thinks its a class name :)
// see the color highlighting
private JTextField TextField = new JTextField(30);
public CardApp() {
//JPanel boardPanel = new JPanel(new GridLayout(height,width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
//JTextField TextField = new JTextField(30);
Hand settingTheText = new Hand();
TextField.setText(settingTheText.ListOfCards());
}
//
// code continues here ...
//
}