在动作事件方法中,它无法找到我的Jbutton对象。我正在尝试制作一个字符选择类型的东西,我找不到一个有效的解决方案

时间:2017-05-16 18:03:26

标签: java swing awt jbutton

这是我的代码。问题出现在动作监听器的最底层。您可以告诉我已经实例化了所有按钮对象。我已经尝试在方法之外创建按钮对象。我真的找不到解决方案。请帮忙

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{

    }
  }
}

1 个答案:

答案 0 :(得分:1)

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

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

含义:

JButton button1 = new JButton("Dorito");

...

应该进入的正文!与你对所有这些人的相似:

boolean shipSelect1=false;

注意:您仍然可以对该方法中的那些按钮执行所有init调用;您只需移动声明该方法体。

除此之外:真正的答案是:不要尝试通过编写Swing UI应用程序来学习Java。从真正的基础开始;像here一样 - 任何其他事情都会导致沮丧和浪费时间。你几乎无法爬行 - 但你想要进行跨栏比赛。