0

i am not really familiar with JPanel and kinda stuck at one thing. I want to know how to make second JTextfield on the second row. They appear to be on the same row.

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
           "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      }
   }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Just Nick
  • 13
  • 5
  • 3
    First you should study about layout manager in java https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html – SatyaTNV Oct 13 '15 at 11:11
  • 1
    Provide ASCII art or a simple drawing of the *intended* layout of the GUI. It seems you want rows of label/value pairs. This can be achieved best using `GridBagLayout` or `GroupLayout` - here is an [example using `GroupLayout`](http://stackoverflow.com/a/21659516/418556). Though I've also create the effect using nested panels (two `GridLayout` panels in a `BorderLayout`) .. – Andrew Thompson Oct 13 '15 at 11:18
  • BTW - `JTextField xField = new JTextField(5);` consider using a `JSpinner` with a `SpinnerNumberModel` instead - the user would prefer that for selecting numbers. – Andrew Thompson Oct 13 '15 at 11:21

1 Answers1

3

It is the matter of layouts in java. In this case you should use GridLayout. Maybe it's better for you to study a little bit about layouts in java.

For now it's good to test GridLayout in your example:

public class JOptionPaneMultiInput {
    public static void main(String[] args) {
        JTextField xField = new JTextField(5);
        JTextField yField = new JTextField(5);

        JPanel myPanel = new JPanel(new GridLayout(2, 2));
        myPanel.add(new JLabel("x:"));
        myPanel.add(xField);
        myPanel.add(new JLabel("y:"));
        myPanel.add(yField);

        int result = JOptionPane.showConfirmDialog(null, myPanel,
                "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
    }
}

But for more complex GUI designs in swing please refer to GridBagLayout or GroupLayout. In real world applications, most of the times you may use more than one layout.

Good Luck.

STaefi
  • 4,297
  • 1
  • 25
  • 43