java 如果按下按钮,则重新启动我的 GUI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17263486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restart my GUI if button is pressed
提问by Louis B
I have a global variable frame, that is a JFrame.
我有一个全局变量框架,即 JFrame。
public static void setUp(final Wheel []player, final phraser p) throws IOException {
final JPanel scorePanel=new JPanel();
final JPanel namePanel=new JPanel();
panel=new JPanel(new GridLayout(1,player.length,1,1));
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel(new GridLayout(2,1,1,1));
panel3.add(new JLabel("Dead letters/phrases:"));
panel3.add(LettersOrPhGuessed);
JMenuBar menuBar=new JMenuBar();
frame.setJMenuBar(menuBar);
clock=new JMenu();
JMenu file=new JMenu("File");
JMenuItem exit=new JMenuItem("Exit");
JMenuItem reset=new JMenuItem("Reset");
file.add(exit);
file.add(reset);
menuBar.add(file);
menuBar.add(clock);
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
reset.addActionListener(new ActionListener(){//help me
public void actionPerformed(ActionEvent e){
frame.removeAll();
frame.validate();
frame.setVisible(false);
try {
startApp();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
//for spinner
spinQuote.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(!first){
String result="You have already spun: "+check;
JOptionPane.showMessageDialog(null,result);
}
else
check=player[whichPlayer].spin();
pause=false;
}
});
//to buy a vowel
buyVowel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
buyVow=true;
if(player[whichPlayer].getPotentialScore()>=250||player[whichPlayer].getTurnScore()>=250){
buyVowel(player,whichPlayer,p);
}
else
JOptionPane.showMessageDialog(null,"Sorry, you don't have enough money to buy a vowel");
pause=false;
}
});
//to solve baord
solv.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pause=false;
solvBoard=true;
boolean temp=false;
while(temp==false){
enterSolution();
if(cancelAnswer){
pause2=false;
go=true;
return;
}
else if(guess.equals("-1")){
JOptionPane.showMessageDialog(null,"Sorry, you took too long");
temp=true;
}
else if(guess.length()>1){
if(p.checkGuessedAnswer(guess))
JOptionPane.showMessageDialog(null,"Sorry, that phrase has already been guessed");
else if(player[whichPlayer].checkForWin(guess)){
newGame=true;
replaceCorrectLetter(underScores,guess);
player[whichPlayer].setFinalScore(player[whichPlayer].getFinalScore()+player[whichPlayer].getPotentialScore()+player[whichPlayer].getTurnScore());
JOptionPane.showMessageDialog(null,"Congrats you won the round!");
whichPlayer=0;
temp=true;
}
else{
JOptionPane.showMessageDialog(null,"Sorry, better luck next time!");
p.addGuessedAnswer(guess);
LettersOrPhGuessed.setText(p.getAlreadyGuessed()+"");
temp=true;
}
}
else
JOptionPane.showMessageDialog(null,"Sorry,That is an invalid guess!");
}
go=false;
pause2=false;
}
});
scorePanel.add(new JLabel("Score Board:"));
panel4 = test;
panel4.setSize(800, 600);//this does nothing in the program
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
namePanel.add(playerName,gbc);
frame.getContentPane().add(namePanel, gbc);
frame.getContentPane().add(scorePanel, gbc);
frame.getContentPane().add(panel, gbc);
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
frame.getContentPane().add(panel4, gbc);
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
frame.getContentPane().add(panel2, gbc);
frame.getContentPane().add(panel1, gbc);
frame.getContentPane().add(panel3, gbc);
frame.setVisible(true);
}
startApp method
启动应用程序方法
public static void startApp() throws IOException{
howManyPlayers();
Wheel[] player=new Wheel[numberOfPlayers];
fixScore(player);
phraser p=new phraser();
answer=p.pickPhrase();
for(int i = 0; i < player.length; i++) {
player[i] = new Wheel(answer);
}
setUp(player,p);
setName(player);
scoreBoard(player);
panel2.add(buyVowel);
panel2.add(spinQuote);
panel2.add(solv);
int gamesplayed=0;
while(gamesplayed<3){
if(gamesplayed!=0)
intializeAnswer(player,p);
underScores=drawSpaces();
check=0;
whichPlayer=0;
newGame=false;
test.intializeWheel();
p.setPositionStart(0);
while(newGame==false){
go=true;
intro(player);
nextTurn=false;
cancelGuess=false;
cancelAnswer=false;
first=true;
while(go){
int starter=p.getPositionStart();
playerName.setText("It is "+player[whichPlayer].getName()+"'s turn!");
pause=true;
pause2=true;
while(pause){//makes sure user hits spin or solve before it does anything
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (pause==false){
if(solvBoard==false&&buyVow==false&&cancelGuess==false)
test.spinner(starter,player[whichPlayer].getPosition());//wheel thing
break;
}
}
cancelGuess=false;
cancelAnswer=false;
if(buyVow){buyVow=false;}
else if(solvBoard){
while(pause2){//makes sure to pause for user
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (pause2==false)
break;
}
solvBoard=false;
}
else if(check==-1){
JOptionPane.showMessageDialog(null,"Bankrupt!" );
player[whichPlayer].setTurnScore(0);
player[whichPlayer].setPotentialScore(0);
go=false;
}
else if(check==-2){
JOptionPane.showMessageDialog(null,"Sorry, you lost your turn!");
player[whichPlayer].setTurnScore(0);
go=false;
}
else if(check==-3){
JOptionPane.showMessageDialog(null,"Spin again!");
}
else{
if(first)
JOptionPane.showMessageDialog(null,"You spun: "+check);
go=interpretAnswer(player,underScores,p);
}
if(newGame==false)
updateScoreBoardInTurn(player);
p.setPositionStart(player[whichPlayer].getPosition());
}
if(newGame==false){
player[whichPlayer].setPotentialScore((player[whichPlayer].getPotentialScore()+player[whichPlayer].getTurnScore()));
updateScoreBoard(player);
if(whichPlayer==player.length-1)
whichPlayer=0;
else
whichPlayer++;
}
player[whichPlayer].setTurnScore(0);
}
for(int i=0;i<player.length;i++){
player[i].setPotentialScore(0);
}
updateScoreBoardAfter(player);
clear(underScores);
reset(player,p);
LettersOrPhGuessed.setText(p.getAlreadyGuessed()+"");
gamesplayed++;
}
calcWinner(player);
results(player);
}
As you can see, i added an actionListener to my reset button and I'm not sure how to the frame completely restart itself by calling startApp(). My problem is that the frame when i reset it comes back very messed up and nothing works. Any suggestions??
如您所见,我向重置按钮添加了一个 actionListener,但我不确定如何通过调用 startApp() 使框架完全重新启动。我的问题是,当我重置框架时,框架非常混乱,没有任何效果。有什么建议??
回答by Hovercraft Full Of Eels
You need to give your class a reset()
method that goes through all the necessary fields and resets them to their initial state. There's no one-size fits all solution -- you're just going to have to write the code. This method can then be called by the ActionListener added to your reset JButton.
您需要为您的类提供一个reset()
方法,该方法遍历所有必需的字段并将它们重置为初始状态。没有一刀切的解决方案——您只需要编写代码即可。然后可以通过添加到重置 JButton 的 ActionListener 调用此方法。
To make this even possible, any field that needs to be reset must be a field of the class and not a field local to a method or constructor, else it won't be visible to your reset method.
为了使这成为可能,任何需要重置的字段都必须是类的字段,而不是方法或构造函数的本地字段,否则它对您的重置方法不可见。
Edit
You state in comment:
编辑
您在评论中声明:
my startApp() calls this method, setUp(), so theoretically, shouldnt there be new instances of every variable? and my main problem is that the gui itself is messed up, like it doesnt display fully or properly
我的 startApp() 调用了这个方法 setUp(),所以理论上,每个变量不应该有新的实例吗?我的主要问题是 gui 本身搞砸了,就像它没有完全或正确显示一样
I would avoid creating new instances of variables and instead try to re-set the state of class fields as this will be much easier to do, and much easier to maintain and upgrade. If you're doing a wheel of fortune type game though, you will have to re-create some fields, especially the JLabels that display the puzzle, but that's about it. The JPanel that holds this display should not be re-created.
我会避免创建变量的新实例,而是尝试重新设置类字段的状态,因为这会更容易做到,并且更容易维护和升级。但是,如果您正在制作命运之轮类型的游戏,则必须重新创建一些字段,尤其是显示拼图的 JLabel,但仅此而已。不应重新创建保存此显示的 JPanel。
Edit 2
Note that your setUp()
and startUp()
methods are little more than huge static "god" methods. I strongly advise that you not do this. Create and use non-static fields and methods for your class, and refactor any method that is that big or tries to do too much.
编辑 2
请注意,您的setUp()
和startUp()
方法只不过是巨大的静态“上帝”方法。我强烈建议你不要这样做。为您的类创建和使用非静态字段和方法,并重构任何大的或试图做太多的方法。
If I were your instructor, I'd advise you to scrap all of this and re-start the program using good OOP principles. You won't regret doing this.
如果我是你的导师,我会建议你放弃所有这些,并使用良好的 OOP 原则重新启动程序。你不会后悔这样做的。
Edit 3
In fact, I would recommend that you subdivide your GUI into separate classes, such as a Wheel class, an AnswerDisplay class, a WrongGuess class, a Player class, and a Game class to run them all, and I'd give each class its own reset()
method that is fully responsible for resetting itself. Then all the Game class has to do is call reset()
on its constituent parts whenever a reset is required.
编辑 3
实际上,我建议您将 GUI 细分为单独的类,例如 Wheel 类、AnswerDisplay 类、WrongGuess 类、Player 类和 Game 类来运行它们,我会给每个类class 自己的reset()
方法,该方法完全负责重置自身。然后 Game 类要做的就是reset()
在需要重置时调用其组成部分。
Edit 4
Replies to your latest comment:
编辑
对您最新评论的4 条回复:
I see what your saying but to my credit, i do reset all of my vairables as opposed to making new instances of them in all cases except for this last one: trying to restart the entire application - I've gotten a little lazy.
我明白你的意思,但值得称赞的是,我确实重置了我的所有变量,而不是在所有情况下都创建它们的新实例,除了最后一个:尝试重新启动整个应用程序 - 我有点懒惰。
It's not a matter of being lazy, but rather of creating a program that is easy to debug and easy to maintain. Also, I suspect that many of your variables are static, and again, this shouldn't be the case.
这不是懒惰的问题,而是创建一个易于调试和易于维护的程序。另外,我怀疑您的许多变量都是静态的,而且情况不应该如此。
I also see what your saying about having "god" methods, but in the case of the setUp(), i need that because a lot of the code is either actionListener's or layout code.
我也看到你所说的“上帝”方法,但在 setUp() 的情况下,我需要它,因为很多代码是 actionListener 或布局代码。
No, you're very wrong on this. Again, if you break down your program into separate classes, your reset button's ActionListener could be as simple as:
不,你在这一点上大错特错。同样,如果您将程序分解为单独的类,则重置按钮的 ActionListener 可能非常简单:
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
game.reset();
}
});
and that's it.
就是这样。
the startApp() could probably be broken down into separate methods but its really not worth it in this scenario.
startApp() 可能可以分解为单独的方法,但在这种情况下它真的不值得。
I'm not trying to be annoying but again you are very wrong. Trust me, I may not be a professional, but I've written manySwing applications, some quite complex, and if you refactor your program as I have suggested, it will be much easier to debug, adapt, enhance and maintain.
我不是想惹人烦,但你又大错特错了。相信我,我可能不是专业人士,但我已经编写了许多Swing 应用程序,其中一些非常复杂,如果您按照我的建议重构您的程序,调试、调整、增强和维护会容易得多。
回答by ExtraSmart
Here's an example of Reset method I've used to reset TicTacToe Game Interface GUI in Java
这是我用来在 Java 中重置井字游戏界面 GUI 的重置方法示例
Code for TicTacToe game
GameInterface contains the GUI
Decide class decides who wins.
l1,l2,l3 are the labels to the buttons pressed
p1,p2 are the player turns
import javax.swing.*;
public class Main1{
initValues();
public static gameinterface g;
public static Decide d;
public static int p1,p2,l1,l2,l3,l4,l5,l6,l7,l8,l9;
public static void main(String[] args){
JOptionPane.showMessageDialog(null,"Player1: Red \n Player 2: Green \n Start Playing");
g= new gameinterface();
d= new Decide();
}
//Restart Method initialize new GUI like it does in Main Method.
//Also reset the label values so the player turns to default and Buttons
//data is restored to default
public static void restart(){
g=new gameinterface();
initValues();
}
//Set Player turn and Labels to default like no button is pressed
public static void initValues(){
p2=0; p1=1; l1=0; l2=0; l3=0;l4=0;l5=0; l6=0; l7=0; l8=0; l9=0;
}
}
}