Add numeric values to a variable in ActionListener, to show variable result

扶醉桌前 提交于 2019-12-11 21:43:17

问题


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:

  1. Initiate a variable. int R=0;
  2. Inside ActionListener of a button, I use set.Visible(); to move to next question (JPanel), and R=R+numeric value.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!