2017-05-16 14 views
1

这是我的代码。问题在于动作监听器的最底层。你可以告诉我所有的按钮对象都被实例化了。我试着在方法之外制作按钮对象。我真的找不到解决方案。请帮助在动作事件方法中,它无法找到我的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

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

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

含义:

JButton button1 = new JButton("Dorito"); 

...

应该进入你的身体类的!类似于你对所有这些人有的东西:

boolean shipSelect1=false; 

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

除此之外:真实答案是:不要试图通过编写Swing UI应用程序学习Java。从真实基本知识开始;像here - 其他任何事情都会导致挫折和浪费时间。你几乎不能爬行 - 但你想做障碍赛。

相关问题