这是我的代码。问题出现在动作监听器的最底层。您可以告诉我已经实例化了所有按钮对象。我已经尝试在方法之外创建按钮对象。我真的找不到解决方案。请帮忙
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{
}
}
}
答案 0 :(得分:1)