Rephidim
Rephidim

Reputation: 1

How to set variables from multiple text fields in single jPanel

Brand new coder here. I've been searching around, but cannot seem to find topics on how to set multiple variables from a line of textboxes in jPanel to use later for algorithmic functions. In this case, I need 5 unique variables for later use. Any help setting up these variables would be highly appreciated. Here's the code I have for setting up text fields and gathering user input:

 import java.util.Scanner;
 import javax.swing.*; //Used to create JPanel

 public class SimpleMath {
     public static void main(String[] args) { //Setup text boxes
         JTextField aField = new JTextField(5);
         JTextField bField = new JTextField(5);
         JTextField cField = new JTextField(5);
         JTextField dField = new JTextField(5);
         JTextField eField = new JTextField(5);

         //Creating JPanel
         JPanel myPanel = new JPanel();
         myPanel.add(new JLabel("1:"));
         myPanel.add(aField);
         myPanel.add(Box.createHorizontalStrut(15)); //a spacer
         myPanel.add(new JLabel("2:"));
         myPanel.add(bField);
         myPanel.add(Box.createHorizontalStrut(15));
         myPanel.add(new JLabel("3:"));
         myPanel.add(cField);
         myPanel.add(Box.createHorizontalStrut(15));
         myPanel.add(new JLabel("4:"));
         myPanel.add(dField);
         myPanel.add(Box.createHorizontalStrut(15));
         myPanel.add(new JLabel("5:"));
         myPanel.add(eField);

         //Gathering data
         int result = JOptionPane.showConfirmDialog(null, myPanel, "Please enter 5 integers", JOptionPane.OK_CANCEL_OPTION);
         if (result == JOptionPane.OK_OPTION) {
             System.out.println("value 1: " + aField.getText());
             System.out.println("value 2: " + bField.getText());
             System.out.println("value 3: " + cField.getText());
             System.out.println("value 4: " + dField.getText());
             System.out.println("value 5: " + eField.getText());

             Scanner input = new Scanner(System.in);
         }
     }
 }

Upvotes: 0

Views: 209

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You're putting everything into the static main method, and trying to create an organic viable and complex Java program, and this simply won't work. You need to stop what you're doing and first learn Java basics including how to create and use instance fields and non-static methods. It's these fields that will be available for mutation in other parts of your program if created correctly. Get a decent book or tutorial and start learning first principles before doing GUI programming -- you won't regret doing this.

Upvotes: 2

Related Questions