-1

I am working on a program that has a gui. the user enters a number which the action listener saves in a variable and then sends this variable to a class main in which it is stored in another variable. The problem is that the way i am currently doing this is not saving the value properly(sometimes the vaue saves and sometimes it doesn't. i want that when the user enters the value in gui and then presses the button this value be saved in a variable in main class. I am very new to java so please excuse my awful coding. This is my main class.

    public class Main {
public static boolean Click=false;
public static void main(String[] args) {
    int n=0, i;
    JFrame Frame = new JFrame();
    Input1 I1 = new Input1();
    Frame.setSize(600, 600);
    Frame.setLocationRelativeTo(null);
    Frame.setContentPane(I1.Input1Panel);
    Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Frame.pack();
    Frame.setVisible(true);
    while (Click==false) {
        n = I1.Setn();
        System.out.println(""+n);
    }

And This is my gui class.

    public class Input1 {
private JButton doneButton;
private JTextField textField1;
private JLabel Title;
private JLabel EnterNum;
public JPanel Input1Panel;

public int n;

Main M = new Main();

public Input1() {
    doneButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            n = Integer.parseInt(textField1.getText());
            while (M.Click==false) {
                if (n==0) {
                    n = Integer.parseInt(textField1.getText());
                }
                else {
                    M.Click=true;
                }
            }
        }
    });
}
public int Setn() {
    return n;
}

}

New code Main Class

    public class Main {
public static void main(String[] args) {
    int n=0, i;
    JFrame Frame = new JFrame();
    Input1 I1 = new Input1();
    Frame.setSize(600, 600);
    Frame.setLocationRelativeTo(null);
    Frame.setContentPane(I1.Input1Panel);
    Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Frame.pack();
    Frame.setVisible(true);
    while (n==0) {
        n = I1.Setn();
        //System.out.println(""+n);
    }
    System.out.println("Main:"+n);

GUI class

    public class Input1 {
private JButton doneButton;
private JTextField textField1;
private JLabel Title;
private JLabel EnterNum;
public JPanel Input1Panel;

public int n;

Main M = new Main();

public Input1() {
    doneButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            n = Integer.parseInt(textField1.getText());
            System.out.println("Action Listener:"+n);
        }
    });
}
public int Setn() {
    return n;
}

}

  • You should take a look at [ask] and [mcve]. The process of formulating the question clearly and reproducibly is often enough to answer it yourself but if not, others will have an easier time helping you. – pvg Apr 28 '18 at 16:18
  • You will want re-think your whole code. For one a `while (true)` will work in a linear console program but has no place in an event-driven GUI since code like this risks tying up the GUI's event thread, freezing the program, and even if it didn't do this, it simply doesn't work as you're thinking it will. Much better to respond to events. Also you're gaining nothing by creating an instance of Main, a class which is nothing but a static main method with static fields. Instead create decent classes with non-static fields (state) and methods (behaviors) and tie them together. – DontKnowMuchBut Getting Better Apr 28 '18 at 16:45

2 Answers2

0

It seems you overcomplicate things a bit. Also, read the comment @pvg did. You don't explain exactly the problem. In addition the way your code is, i can't understand what exactly you are trying to do.

In case you want to get an input from a textfield and do something with this:

package test;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Test {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        // Swing applications must run on EDT thread. Use this method to achieve that.
        EventQueue.invokeLater(() -> {
            try {
                Test window = new Test();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * Create the application.
     */
    public Test() {
        frame = new JFrame();
        frame.setPreferredSize(new Dimension(300, 300));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new FlowLayout());
        addComponents();
        frame.pack();
    }

    private void addComponents() {
        JTextField txtInput = new JTextField("Input: ");
        txtInput.setEditable(false);
        frame.getContentPane().add(txtInput);
        JTextField inputField = new JTextField();
        inputField.setColumns(10);
        frame.getContentPane().add(inputField);
        JButton getInputBtn = new JButton("Click me to give the input");
        getInputBtn.addActionListener(e -> {
            String input = inputField.getText(); 
            System.out.println("The input is: " + input); //Do something with the input.
        });
        frame.getContentPane().add(getInputBtn);
    }

}

I see that you parse an Integer from the input. This, the way you handle it, can give you a NumberFormatException. I suggest you to read How to use formatted text field in order to avoid that.

P.S: Add "swing" tag to your post.

George Z.
  • 6,643
  • 4
  • 27
  • 47
  • i have changed my my program a bit. let me rephrase my problem. i get the input from the action listener now i want to send this input to the main class which i do using Setn(). in main i make a while loop so that until the user inputs a number the program does not execute further. the problem is that my method Setn does not seem to set the value in the main class unless i put a print statement inside of my loop. if i do not put a print statement the value stays in my gui class and does hot get in the main class. i have added the new code. – Abdul Wasay Apr 29 '18 at 05:51
0

Upon further research i was able to find a solution all i needed to do was put "volatile" with n when declared.For clarification go to this site. Loop doesn't see changed value without a print statement. My code currently.

    volatile public static int n=0;
public static void main(String[] args) {

    int i=0;

    JFrame Frame = new JFrame();
    Input1 I1 = new Input1();
    Input2 I2 = new Input2();

    Frame.setSize(600, 600);
    Frame.setLocationRelativeTo(null);
    Frame.setContentPane(I1.Input1Panel);
    Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Frame.pack();
    Frame.setVisible(true);
    while (n==0) {
        n = I1.Setn();
    }