我正在编写一些工作在游戏上,我一直在尝试使按钮设置变量“武器”时遇到了麻烦。如何使一个按钮设置变量
import static java.lang.System.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UntitledProject {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public UntitledProject() {
prepareGUI();
}
public static void main(String[] args) {
UntitledProject prepare = new UntitledProject();
String weapon = prepare.weapon();
}
private void prepareGUI() {
mainFrame = new JFrame("Untitled Project");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public String weapon() {
headerLabel.setText("Pick Weapon");
JButton button1 = new JButton("Sword");
JButton button2 = new JButton("Lance");
JButton button3 = new JButton("Axe");
JButton submitButton = new JButton("Submit");
String weapon = "";
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Sword selected.");
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
weapon = "Sword";
exit(0);
}
});
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Lance selected.");
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
weapon = "Lance";
exit(0);
}
});
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Axe selected.");
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
weapon = "Axe";
exit(0);
}
});
}
});
controlPanel.add(button1);
controlPanel.add(button2);
controlPanel.add(button3);
controlPanel.add(submitButton);
mainFrame.setVisible(true);
}
我需要时按下按钮,武器变量改为提交按钮之前按下了哪个按钮提交。