在动作事件方法中,它找不到我的 Jbutton 对象。我正在尝试制作一个字符 select 类型的东西,但我找不到可行的解决方案

In the action event method, it cant find my Jbutton objects. I'm trying to make a character select type thing and I cannot find a working solution

这是我的代码。问题出在动作监听器的最底层。你可以看出我已经实例化了所有按钮对象。我试过在方法之外制作按钮对象。我真的找不到解决办法。请帮助

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

 public class Select implements ActionListener {
 boolean shipSelect1=false;
 boolean shipSelect2=false;
 boolean shipSelect3=false;
 boolean shipSelect4=false;
 boolean shipSelect5=false;
 public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Select().createGui();
        }
      });

}

 public void createGui() {
    JFrame frame = new JFrame("Java Stocks");
    frame.setSize(700, 700);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridBagLayout());
    frame.add(panel);
    frame.getContentPane().add(panel, BorderLayout.WEST);

    GridBagConstraints c = new GridBagConstraints();

    JButton button1 = new JButton("Dorito");
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(40, 40, 40, 40);
    panel.add(button1, c);
    button1.addActionListener(this);
    button1.setToolTipText("Your gonna fly a dorito in space son.");

    JButton button2 = new JButton("Otirod");
    c.gridx = 0;
    c.gridy = 1;
    panel.add(button2, c);
    button2.addActionListener(this);
    button2.setToolTipText("(?rosnopS elbissoP).nos ecaps ni ortirod"); 

    JButton button3 = new JButton("Ship");
    c.gridx = 0;
    c.gridy = 2;
    panel.add(button3, c);
    button3.addActionListener(this);
    button3.setToolTipText("Basic Ship");

    JButton button4 = new JButton("pihS");
    c.gridx = 0;
    c.gridy = 3;
    panel.add(button4, c);
    button4.addActionListener(this);
     button4.setToolTipText("pihS cisaB");

    JButton button5 = new JButton("Good Ship");
    c.gridx = 0;
    c.gridy = 4;
    panel.add(button5, c);
    button5.addActionListener(this);
    button5.setToolTipText("The ship is the best ship. Your not gonna");
}

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
     if(source == button1)
    {
        shipSelect1=true;

    } else if(source == button2)
    {
        shipSelect2=true;
    }
    else if(source == button3)
    {
        shipSelect3=true;
    }
    else if(source == button4)
    {
        shipSelect4=true;
    }
    else if(source == button4)
    {
        shipSelect5=true;
    }
    else{

    }
  }
}

您想了解 scope。 属性 定义了变量的可见性。

方法中定义的变量仅在该方法中可见。所以你必须将你的按钮移动到 class 范围。

含义:

JButton button1 = new JButton("Dorito");

...

应该进入你的class体内!类似于你对所有这些人的看法:

boolean shipSelect1=false;

注意:您仍然可以在该方法中对这些按钮执行所有初始化调用;您只需要声明移出该方法体。

除此之外:真正的答案是:不要试图通过编写 Swing UI 应用程序来学习 Java。从真正的基础知识开始;像 here - 其他任何事情都会导致沮丧和浪费时间。连爬都不会,还想跨栏。