Java GUI, organizing a dialog box to get data from the user
I am designing a GUI for my research project. I want to create a dialog box that gets information from the user. Here is the screenshot:
Here is the code for the screenshot above:
JTextField projnameField = new JTextField(10); JTextField nField = new JTextField(5); JTextField mField = new JTextField(5); JTextField alphaField = new JTextField(5); JTextField kField = new JTextField(5); JFileChooser inputfile = new JFileChooser(); inputfile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); File file = inputfile.getSelectedFile(); String fullpath = file.getAbsolutePath(); JPanel myPanel = new JPanel(); myPanel.add(new JLabel("Project Name:")); myPanel.add(projnameField); myPanel.add(new JLabel("Number of instances:")); myPanel.add(nField); myPanel.add(new JLabel("Number of attributes:")); myPanel.add(mField); myPanel.add(new JLabel("Alpha:")); myPanel.add(alphaField); myPanel.add(new JLabel("Number of patterns:")); myPanel.add(kField); myPanel.add(new JLabel("Please select your datset:")); myPanel.add(inputfile); myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS)); int result = JOptionPane.showConfirmDialog( null, myPanel, "CPM Program", JOptionPane.OK_CANCEL_OPTION); double alpha = Double.parseDouble(alphaField.getText()); int numpat = Integer.parseInt(kField.getText()); int num_inst = Integer.parseInt(nField.getText()); int num_attr = Integer.parseInt(mField.getText()); String projname = (projnameField.getText());
In reference to the above image I have two questions:
Notice the labels are centered. How can I put those in the left side like this:
Project name: --textbox-- Number of instances: --textbox--
In the label, "Please select you dataset", I want to browse the file, select it and copy the full path in a blank box in the front of "Please select you dataset" label, but I do not know how I should do it.
1- The first problem is that all of the labels such as project name or number of instances are centered (it seems!). How can I put those in the left side?
JLabel has a constructor that takes an int as one of the parameters, and you can use it to position your text held in the JLabel.
2- The second problem is that text fields are not in the front of labels and are below of them. I want to have each text field in the front of the label such as:
Layouts are the key here. Consider using GridBagLayout (which can be somewhat difficult to use initially) or MigLayout (easier to use but you have to download it first) to allow use of a more tabular structure for your GUI.
For example, please have a look at my code in this answer for an example of tabular structure using GridBagLayout.