Dar*_*man 2 java swing jlabel jpanel actionlistener
我正在寻找一种方法让我的程序等到按下按钮继续该功能.在我的主要功能中,我调用的功能是使用JPanel,按钮和标签显示我的基本GUI.当然,它显示了GUI并结束了不允许我改变GUI的功能.
public static Player player = new Player();
public static Gui gui = new Gui();
public static boolean inMain = true;
public static boolean inBattle = false;
public static void main(String[] args){
showMainGui();
}
Run Code Online (Sandbox Code Playgroud)
我认为我正在寻找的是这样的东西:
public static void main(String[] args){
showMainGui();
while(inBattle == false){
// wait until inBattle changes
}
}
Run Code Online (Sandbox Code Playgroud)
while循环将循环并等待直到在showMainGui中创建的按钮将inBattle更改为true.我怎么能这样做呢?这让我很困惑.我的目标是单击一个JButton,按钮变为不同的按钮
我在showMainGui()上创建的按钮的动作监听器;
public class Hunt implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
MainClass.inBattle = true;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的showMainGui()方法
public static void showMainGui(){
gui.panel.add(gui.healthLabel);
gui.panel.add(gui.pbsLabel);
gui.panel.add(gui.staminaLabel);
gui.panel.add(gui.levelLabel);
//Adding initial buttons
gui.panel.add(gui.exploreButton);
gui.panel.add(gui.huntButton);
gui.panel.add(gui.newsLabel);
gui.panel.add(gui.effectLabel);
updateGui();
}
Run Code Online (Sandbox Code Playgroud)
您可以等待线程进入睡眠状态.
while(inBattle == false){
try {
Thread.sleep(200);
} catch(InterruptedException e) {
}
}
// perform operations when inBattle is true
Run Code Online (Sandbox Code Playgroud)
另外别忘了让inBattle变得不稳定
我想+1 Peters的答案,但是我觉得这需要一些阐述。
绝对不需要while循环或其他线程。只需将侦听器添加到您的UI组件即可。这是一个非常简单的示例:
JButton button = new JButton("This is a button!");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Perform function when button is pressed
System.out.println("You clicked the button");
}
});
Run Code Online (Sandbox Code Playgroud)
您已添加动作监听器,同时仍保持while循环,为什么?删除while循环并使用侦听器。
再次重复Peter,但是RTFM。只需阅读文档,其中提供了清晰的示例。没有充分的理由使用该循环。
您的应用程序没有崩溃,它正在执行您要告诉它的操作:
public static void main(String[] args){
showMainGui();
while(inBattle == false){
// wait until inBattle changes
}
}
Run Code Online (Sandbox Code Playgroud)
您的意思是,如果inBattle为false,则不执行任何操作,但是如果inBattle为true,则不执行任何操作,然后结束主要功能-如果您无所事事,单击按钮后您希望它做什么?