问题
What I need to make:
Its a basic, ask user questions and then supply result in the end application. I've made questions on different JPanels, when user clicks on a choice, I want to record his choice and also move to the next question. A final JPanel will display result as per user choices.
How I'm doing it:
- Initiate a variable. int R=0;
- Inside ActionListener of a button, I use set.Visible(); to move to next question (JPanel), and R=R+numeric value.
- After selecting different choices, different numeric values would be added to variable R. And use the total ie final value of R, to display the appropriate result.
if(R=150)
{
Show this or that result;
}
What wrong:
In main I've a System.out.println(R); line to check the result for myself. And it demands that I make the variable R static. Hence as of now, I can't even see if the value of R is updated at each actionlistener, let alone display the result.
Also advice if I using the right approach toward this kind of thing. I'm a beginner so I'm unaware of how people usually do this. If not then please show me the right approach.
回答1:
In Java, main is a static method, which is why you're getting the error about R needing to be static to be accessed. Try putting R in a class instance, and you should be able to print it handily. Creating a Bean or Model class to retain R and handle the switching gives you a clean separation of logic from GUI, and gets you away from nasty static issues as a side effect.
回答2:
The correct approach would be to create a non static variable in the class that extends JFrame. Now each of your button would have access to it. So now increment accordingly. To access this variable in main method you must access is using obj.R where obj is the object of the class that extended JFrame (I believe that is how you begin your application).
来源:https://stackoverflow.com/questions/19507611/add-numeric-values-to-a-variable-in-actionlistener-to-show-variable-result