Accessing local variable within actionPerformed Java eclipse - java

i am trying to reach the value within an int variable from within the actionPerformed class, the integer comes from another class where its passed as an argument "asd" and holds the value "1". I obviously deleted some lines from the code i posted below to make it easier to read but what i ve deleted has nothing to do with the problem im having.
So here, the output i see is;
asd
1
1
0
0
the last two outputs are from the actionPerformed class, they appear when i click the related button. How can i make it so those 2 outputs are also shown as 1?
public class customerAppointmentScreen extends JFrame implements ActionListener{
private JButton massB,indiB;
public int asd,id;
public customerAppointmentScreen(int asd) {
System.out.println("asd ");
System.out.println(asd);
id=asd;
System.out.println(id);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==massB) {
int id=asd;
System.out.println(asd);
System.out.println(id);
//this.setVisible(false);
}
else if(e.getSource()==indiB) {
this.setVisible(false);
}
}
}

Starting with...
public int asd,id;
public customerAppointmentScreen(int asd) {
System.out.println("asd ");
System.out.println(asd);
id=asd;
System.out.println(id);
}
The parameter asd is never assigned to the instance field asd, so the instance field remains 0 (id on the other hand is equal to the parameter asd)
When the ActionListener is triggered...
public void actionPerformed(ActionEvent e) {
if (e.getSource() == massB) {
int id = asd;
System.out.println(asd);
System.out.println(id);
//this.setVisible(false);
} else if (e.getSource() == indiB) {
this.setVisible(false);
}
}
You assign the instance field asd value to the local variable id, since asd is still zero, so is id.
The "simple" solution would be to assign the parameter from the constructor to the appropriate instance field OR use the correct instance field in the ActionListener, depending on your intentions.

Related

What is the best practice for the scope of variables in a class

My teachers source code was published and i was confused when i saw this:
New local variables where instantiated from a static variable, the variable was then used in a method and passed as an argument to another method, to then set its new value to the same static variable that the copy was based on. Since the scope of a static variable will be accessible throughout the class, why not access the static variable directly from every method within that class?
Why do this:
public class Calculator {
private JTextField displayText;
public void actionPerformed(ActionEvent e) {
String input = displayText.getText();
if (something == right) {
for (int i = 0; i < 10; i++) {
enterNumber(input);
}
}
}
public void enterNumber(String input) {
displayText.setText(input);
}
}
If you can just:
public class Calculator {
private JTextField displayText;
public void actionPerformed(ActionEvent e) {
if (something == right) {
for (int i = 0; i < 10; i++) {
enterNumber();
}
}
}
public void enterNumber() {
String localVar = "Kitten";
displayText.setText(localVar);
}
}
In this exact example you are right, there is no point in having a parameter in your enter number method.
but when you begin to work on more complex programs you start to notice that you end up using the same functionality over and over again, in which you can have a method with parameters, such that you can perform the same action with slight variation.
also it is easier to read for other people if you have a method with parameters, since all you have to do is say, "ok i call the method and send it blank, it sets the value to whatever i sent it.", instead of saying "ok i call the method, now lets see what the method does."
if your code works then it is not bad code. but if it works and is easy to read then it is good code.

Go through Array of object in java

I've created this class:
class Remote
{
private static string name;
private Button[] button;
public void delRemote()
{
Remote.name = null;
}
public boolean checkAvailable()
{
return ((Remote.name) == null);
}
}
and I want to change checkAvailable so it can check a whole array after I initialize it like so:
Remote remote1[];
Is this possible without having to call checkAvailable n number of times?
#user2665581 - See... name is a static field.. which means it exists at class level and all other "instances" of the class share the same field (name).
Now, you don't have a custom constructor. So, by default name will be initialized to null.
If you do,
Remote remote1[] = new Remote[4];
Since name is private you cannot access it from outside the class... And you don't have any method to change the value of name inside the class.. So, basically, with the code which you have given, you cannot change the value of name.. name will always be null... And check availabile will always return true
JButton b[]=new JButton[10];
for(int i=0;i<10;i++)
{
b[i]=new JButton(""+i);
}
int size=0;
for(int j=0;j<10;j++)
{
b[j].setBounds(size,10,10,10);
size +=10;
add(b[j]);
}

How do I access an outer variable within inner nested methods?

I am aware that this question may already exist, and this is my first question on the site, so please bear with me.I still have difficulty understanding this in my case.
So here is the thing: I have a method that I call , and I have a button that will change the value of x. Depending on the value of x, I want the program to do something. The program below is not very complete but you will get the idea:
public class foo{
private void do(){
int x=0;
JButton changeValue= new JButton("Change the value of x");
changeValue.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
x=10; //change the x value when the button is clicked
//Here the user may also change the value of x
//by inputting some other number
}
});
//Something happens depending on x
//But nothing happens here because when I get the value of x,
//it reverts back to 0.
}
}
However, no matter where I declare my x in do(), I keep getting an error telling me that inner class cannot access outer class variables and that they must be declared final. But I can't declare it final because I need to change it later. I have tried putting the values in a new class. I have also tried declaring x as a member of foo() but that results to x
being 0 or null because for some reason once it exits the button click method it takes x to back to its old value: 0 or null.
What I need : when the button is pressed, the value of x is changed (Assuming that the user can change the value of x to some other number) Thanks for any answers in advance.
You need to create a final reference to your x variable.
Since it is primitive type, create a class to wrap it:
private static class MyX {
int x;
// + getter and setter
}
And then:
final MyX myX = new MyX(x);
JButton changeValue= new JButton("Change the value of x");
changeValue.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
myX.setX(10);
});
// get the value of MyX back if necessary
The problem is: when you create that ActionListener you are declaring an actionPerformed that will be executed sometime later. You cannot change x from actionPerformed because x exists only inside that method call.
class Foo {
void doSomething() {
int x = 0; // x inside doSomething
JButton btn = new Button("Do Something");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
/*
* This does not happen now:
* it happens later.
*
* By the time this happens
* the method will have exited
* and x will be gone.
*
*/
}
});
/* That x disappears forever here.
* (Or a little bit later but basically here.)
*/
}
}
You can declare x as final and then the anonymous class is given the value of it but you are wanting to change it. Probably what you are wanting is to make it a field:
class Foo {
int x = 0; // x inside Foo
JButton btn = new Button("Do Something");
Foo() {
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
/* do something with x as needed */
}
});
}
}
Anonymous classes can also have fields:
btn.addActionListener(new ActionListener() {
int x = 0; // x inside anonymous ActionListener
#Override
public void actionPerformed(ActionEvent ae) {
/* use x only in actionPerformed */
}
});
"I have also tried declaring x as a member of foo() but that results to x being 0 or null because for some reason once it exits the button click method it takes x to back to its old value: 0 or null."
Unfortunately, this probably means you're doing something else wrong. I'm not sure what that might be from your description and code. For example, you're creating a new JButton locally inside a method which seems unusual. Unless it's one of those "createAndShowGUI" methods (as seen all over the Swing tutorials), you might be creating multiple buttons, multiple listeners, etc.

Java - variable value from one class to another class

I want to transfer a variable value of type List (variable name is seznamRacunov) from one class to another.
Class 1
public class UvoziRacun
{
private String potRacuna;
private List<String> seznamRacunov = new ArrayList();
public void setRacun(List<String> seznamRacunov)
{
this.seznamRacunov = seznamRacunov;
}
public List<String> getRacun()
{
return seznamRacunov;
}
public String getPotRacuna()
{
return potRacuna;
}
public void showDailog()
{
try
{
JFileChooser racun = new JFileChooser();
racun.setCurrentDirectory(new File(""));
racun.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
}
public String getDescription()
{
return "XML Datoteka";
}
});
//racun.setMultiSelectionEnabled(true);
int r = racun.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION)
{
potRacuna = racun.getSelectedFile().getPath();
seznamRacunov.add(potRacuna); //value is stored
}
//System.out.print("Racuni: " + seznamRacunov);
}
catch(Exception ex){}
}
}
Class 2
public class PrikaziRacune extends javax.swing.JFrame
{
UvoziRacun rac = new UvoziRacun();
public PrikaziRacune()
{
initComponents();
try
{
System.out.print(rac.getRacun()); // value is null, why?
//jLabel2.setText();
}
catch(Exception ex){}
}
Method seznamRacunov.add(potRacuna); store a value into seznamRacunov in Class 1, but the value of list does not pass in class 2 where I called getter. What is wrong?
Method seznamRacunov.add(potRacuna); store a value into seznamRacunov
in Class 1, but the value of list does not pass in class 2 where I
called getter.
Thats because, you are trying to get() your List without even calling the method - showDailog() which in turn invokes your add() method to populate list.
Make sure, you invoke this method - showDailog() to populate the list, before you actually fetch the List with get method
Or, it would be better, if you add a constructor to your class, which does the task of initializing your List. Then you can create an instance using that constructor and thus you won't have any problem.
PS: - You should always have at least a 0-arg constructor to initialize your fields, rather than letting compiler handle this task for you.
And one more thing, you should never, ever engulp your exception by having an empty catch block. Else there is no point in catching them. Add a printStackTrace() call instead.
public PrikaziRacune() {
initComponents();
try
{
rac.showDailog(); // Will populate the list
System.out.print(rac.getRacun()); // You can get the value here.
//jLabel2.setText();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
Also, check your ArrayList declaration in your first class. You are using generic type List on LHS, and a Raw type ArrayList on the RHS. Its something that you should avoid.
Have Generic type on both the sides: -
private List<String> seznamRacunov = new ArrayList<String>();

Calculator program getting user input

For practice, I am trying to create a fully functional calculator. I copied the ActionListener class of my code below. I feel like my this method for getting the users input, storing it as an integer/double does not work well as it is too basic and does not work in all cases. I was wondering if anyone can help me figure out a way to structure my code, get user input for two numbers and a symbol, and basically create a fully function GUI calculator. My problem is getting user input from my JButton, storing as a number that in way like a calculator does, (press 1 twice == 11) and using it for later calculation.
I appreciate any advice in this regard.
private class TheHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
while(equals!=event.getSource())
if(one==event.getSource()){
result.setText("1");
num1=1;
}
else if(two==event.getSource()){
result.setText("2");
}
else if(three==event.getSource()){
result.setText("3");
}
else if(four==event.getSource()){
result.setText("4");
}
else if(five==event.getSource()){
result.setText("5");
}
else if(six==event.getSource()){
result.setText("6");
}
else if(seven==event.getSource()){
result.setText("7");
}
else if(eight==event.getSource()){
result.setText("8");
}
else if(nine==event.getSource()){
result.setText("9");
}
else if(zero==event.getSource()){
result.setText("0");
}
}
}
You should remove the while at all.
I would suggest to use numeric vars like
long num = 0;
int digit;
Each event should just set digit
...
else if(nine==event.getSource()){
digit = 9;
} else if(zero==event.getSource()){
digit = 0;
}
...
num = num * 10 + digit;
...
result.setText(Long.toString(num));
How about a class member variable to store the current state of the display and use that for set text?
private class TheHandler implements ActionListener{
String display = "";
public void actionPerformed(ActionEvent event){
while(equals!=event.getSource()){
if(one==event.getSource()){
display=display+"1";
}
.....
}
result.setText(display);
}
}
You could more cleanly associate each button with a number like so:
private class TheHandler implements ActionListener{
private Map<Object, String> numbers = new HashMap<Object, String>();
{
numbers.put(zero, "0");
numbers.put(one, "1");
...
}
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
while(equals != source){
String number = numbers.get(source);
if (number != null){
result.setText(number);
}
}
}
}

Categories