我目前正在用 Java 制作一个自定义的 Minecraft 服务器启动器,并且已经进入了一个早期阶段,我实际上想要按钮来做一些事情。我设法让一个按钮响应(开始按钮),但是一旦我输入第二个 if 语句使停止按钮响应,以前工作的开始按钮现在就没有了。我无法测试停止按钮,因为默认情况下它是禁用的。 当我切换 if 语句(首先放置 stopBtn Action 监听器)时,开始按钮再次起作用,但停止按钮不起作用。 请问有人可以看看代码并提供帮助吗?
package custommcserver;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
class Window extends JFrame implements ActionListener
{
JPanel mainPnl = new JPanel(new GridLayout(2,1));
JPanel propPnl = new JPanel();
JButton startBtn = new JButton("Start");
JButton stopBtn = new JButton("Stop");
JButton propBtn = new JButton("Properties");
public Window()
{
super("Custom Minecraft Server Launcher") ;
setSize(500,200) ;
setDefaultCloseOperation(EXIT_ON_CLOSE) ;
add(mainPnl) ;
mainPnl.add(startBtn);
mainPnl.add(stopBtn);
mainPnl.add(propBtn);
stopBtn.setEnabled(false);
startBtn.addActionListener(this);
stopBtn.addActionListener(this);
propBtn.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == stopBtn);
{
stopBtn.setEnabled(false);
startBtn.setEnabled(true);
}
if (event.getSource() == startBtn);
{
stopBtn.setEnabled(true);
startBtn.setEnabled(false);
}
}
}
最佳答案
您在 if 语句之后放置了分号。把它们拿走:
if (event.getSource() == stopBtn)
{
stopBtn.setEnabled(false);
startBtn.setEnabled(true);
}
if (event.getSource() == startBtn)
{
stopBtn.setEnabled(true);
startBtn.setEnabled(false);
}
关于Java - Action 监听器只响应一个 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495266/