我已编写此代码,但出于某种原因,代码无法正常工作。它似乎应该工作,但它有点让我认为“isBasic”布尔值的值并没有真正改变,总是导致错误。谁能告诉我什么错了?
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("basic")){
isBasic = true;
}
if (isBasic && e.getActionCommand().equals("basic")){
isBasic = false;
}
if (isBasic){
System.out.println("It works!!");
}
}
这是JButton的代码:
JButton basicTower = new JButton("Basic Tower");
JButton test = new JButton("Test");
public boolean isBasic = false;
public TurretPanel(JPanel panel,BorderLayout layout){
setLayout(layout);
panel.add(basicTower,BorderLayout.WEST);
add(panel);
basicTower.setActionCommand("basic");
basicTower.addActionListener(this);
}
答案 0 :(得分:3)
你需要使用else,而不仅仅是。试试这个:
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("basic")){
isBasic = true;
}
else if (isBasic && e.getActionCommand().equals("basic")){
isBasic = false;
}
if (isBasic){
System.out.println("It works!!");
}
}
而不是
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("basic")){
isBasic = true;
}
if (isBasic && e.getActionCommand().equals("basic")){
isBasic = false;
}
if (isBasic){
System.out.println("It works!!");
}
}
编写方法的更好方法是:
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("basic")){
isBasic = !isBasic;
}
if (isBasic){
System.out.println("It works!!");
}
}
答案 1 :(得分:3)
这两个if语句相互否定:
if (e.getActionCommand().equals("basic")){
isBasic = true;
}
if (isBasic && e.getActionCommand().equals("basic")){
isBasic = false;
}
当命令等于“basic”时,两者都执行,第一个将其设置为true,第二个将其恢复为false。使用if / else:
if (e.getActionCommand().equals("basic"))
{
isBasic = !isBasic;
}
答案 2 :(得分:2)
我认为您遇到问题是因为您应该使用if-else
语句......
想一想......我们假设e.getActionCommand()
设置为"basic"
if (e.getActionCommand().equals("basic")){
isBasic = true;
}
// isBasic is not true...
// This will now equate to true as well...
if (isBasic && e.getActionCommand().equals("basic")){
isBasic = false;
}
// Meaning isBasic will ALWAYS be false (so long as e.getActionCommand()
// is "basic"
if (isBasic){
System.out.println("It works!!");
}
尝试使用更像......
的内容if (isBasic && e.getActionCommand().equals("basic")){
isBasic = false;
} else if (e.getActionCommand().equals("basic")){
isBasic = true;
}
相反。
您可能需要更改订单以满足您的要求,但对我来说,这更有意义......
可能更容易<强>更新强>
实际上可能更简单......
if (isBasic && e.getActionCommand().equals("basic")){
isBasic = !isBasic;
}