-1

So I was doing a small Java Punnett Square Project ( asked a question that gives more details as to what it does exactly). After asking the last question, I decided to start rewriting the program since it was very confusing and jumbled. Here is the formatting that I want:

https://snag.gy/IsfbNQ.jpg

Here is a screenshot of my output:

https://snag.gy/bcxykV.jpg

The text fields are not to the right of the Labels, and my calculate button is not displaying my table.

Here is the code:

//imports

public class GeneticsGUI
{
   public static void main(String[] args) 
   {
       JFrame window = new JFrame("Genetics");
       JPanel panel = new JPanel(new GridLayout(25,2));

       JLabel o = new JLabel("Options:");
       panel.add(o);
       String[] options = new String[] {"2x2 Punnett Square", "4x4 Punnett Square"};
       JComboBox<String> list = new JComboBox<>(options);
       panel.add(list);


       String selected = (String) list.getSelectedItem();


       JLabel p1 = new JLabel("Parent 1:");
       JTextField par1 = new JTextField();
       JLabel p2 = new JLabel("Parent 1:");
       JTextField par2 = new JTextField();

       panel.add(p1,BorderLayout.WEST);
       panel.add(par1,BorderLayout.CENTER);
       panel.add(p2,BorderLayout.WEST);
       panel.add(par2,BorderLayout.CENTER);

       JButton submit = new JButton("Calculate");
       submit.addActionListener( new ActionListener() 
       {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                if(e.getSource()==submit)
                {
                      String p1 = par1.getText();
                      String p2 = par2.getText();
                      if(selected == "2x2 Punnett Square")
                      {

                          String[][] mono = Genetics.monohybridPunett(p1, p2);
                          for(int row = 0; row<2 ; row++)
                          {
                              for(int col = 0; col<2; col++)
                              {
                                  mono[row][col] = "         "+ mono[row][col];
                              }
                          }
                          JTable table = new JTable(mono.length,mono.length);

                          table.setShowGrid(true);

                          for(int i = 0; i<mono.length; i++)
                              for(int j = 0; j<mono.length; j++)
                                  table.setValueAt(mono[i][j], i, j);

                          DefaultTableCellRenderer t = new DefaultTableCellRenderer();
                          t.setHorizontalTextPosition(DefaultTableCellRenderer.CENTER);
                          t.setVerticalTextPosition(DefaultTableCellRenderer.CENTER);

                          table.setSize(300, 300);
                          table.isCellEditable(0,0);
                          table.setRowHeight(100);
                          panel.add(table,BorderLayout.EAST);;
                          panel.revalidate();
                      }
                      else if(selected == "4x4 Punnett Square")
                      {


                          String[][] di = Genetics.dihybridPunett(p1, p2);
                          JTable table = new JTable(di.length,di.length);
                          table.setShowGrid(true);

                          DefaultTableModel model = new DefaultTableModel(di,new Object[]{"AaBb","AaBb","",""});
                          table.isCellEditable(0, 0);
                          table.setModel(model);
                          table.setRowHeight(100);

                          table.getColumnModel().getColumn(0).setPreferredWidth(100);
                          table.getColumnModel().getColumn(1).setPreferredWidth(100);
                          table.getColumnModel().getColumn(2).setPreferredWidth(100);
                          table.getColumnModel().getColumn(3).setPreferredWidth(100);
                          panel.add(table,BorderLayout.CENTER);
                          panel.revalidate();
                      }
                }
            }
          });

       panel.add(submit);

       window.add(panel);
       window.setSize(800, 800);
       window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
       window.setVisible(true);
   }
}

Again, I am not really an expert in GUI or Swing, so was wondering what I would need to do to fix this formatting problem.

EDIT:

Here is my current code for my GridBagLayout implementation.

   JFrame window = new JFrame("Genetics");
   JPanel panel = new JPanel();

   panel.setLayout(new GridBagLayout());
   GridBagConstraints c = new GridBagConstraints();

   JLabel o = new JLabel("Options:");

   c.fill = GridBagConstraints.HORIZONTAL;
   c.gridx = 0;
   c.gridy = 0;
   c.weightx = 0;
   panel.add(o, c);

   String[] options = new String[] {"2x2 Punnett Square", "4x4 Punnett Square"};
   JComboBox<String> list = new JComboBox<>(options);
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 1;
   c.gridx = 1;
   c.gridy = 0;
   panel.add(list, c);
   String selected = (String) list.getSelectedItem();

   JLabel p1 = new JLabel("Parent 1:");
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 0.5;
   c.weighty = 1;
   c.insets = new Insets(40,0,0,0);
   c.gridx = 0;
   c.gridy = 1;
   panel.add(p1, c);

   JTextField par1 = new JTextField();
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 0.5;
   c.gridx = 1;
   c.gridy = 1;
   panel.add(par1, c);

   JLabel p2 = new JLabel("Parent 2:");
   c.fill = GridBagConstraints.HORIZONTAL;
   c.insets = new Insets(0,0,0,0);
   c.weightx = 0.5;
   c.gridx = 0;
   c.gridy = 2;
   panel.add(p2, c);

   JTextField par2 = new JTextField();
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 0.5;
   c.gridx = 1;
   c.gridy = 2;
   panel.add(par2, c);



   JButton submit = new JButton("Calculate");
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 0.5;
   c.gridx = 0;
   c.gridy = 3;
   c.anchor = GridBagConstraints.LINE_START;
   panel.add(submit, c);
Akhil Murthy
  • 47
  • 1
  • 8
  • 2
    By the way ... `selected == "2x2 Punnett Square"` is not [how to compare strings](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – OneCricketeer Dec 20 '16 at 20:54
  • 2
    Setting a JPanel's layout to GridLayout and then using BorderLayout constants when adding components to the JPanel makes no sense and suggests that you've neglected to check the tutorials first. Key points 1) check the tutorials, and 2) nest JPanels, each using its own layout manager, in order to achieve your goal. – Hovercraft Full Of Eels Dec 20 '16 at 20:59
  • Use GridBagLayout for the top JPanel, one that holds labels and JTextFields, use BorderLayout for the entire GUI, add the top JPanel BorderLayout.PAGE_START. Add the diagram or JTable, or whatever (possibly within a JScrollPane) in the main JPanel, BorderLayout.CENTER\ – Hovercraft Full Of Eels Dec 20 '16 at 21:04
  • [This link](http://stackoverflow.com/a/9852059/522444) shows how I handle GridBagLayout GUI's. – Hovercraft Full Of Eels Dec 21 '16 at 01:34

1 Answers1

2

You are creating your JPanel with a 50 cell (25x2) GridLayout then later adding components to that JPanel using the BorderLayout constants.

GridLayout doesn't use constants the same way BorderLayout does, rather it just adds the components, one per cell in the order they're added. Take a look at How to Use GridLayout for a quick rundown on how to use GridLayout properly.

For the UI layout you desire, you'll probably need to use something like GridBagLayout (How to Use GridBagLayout) or SpringLayout (How to Use SpringLayout). Both are powerful/flexible layout managers, but they're also arguably the most complex layout managers available in Swing.

Unless you intend to become versed in the fine points of Swing GUI layout, I'd strongly recommend using something like NetBeans to generate the layout (see: Designing a Swing GUI in NetBeans IDE)

EDIT

Below is an example of the layout using GridBagLayout. I've added extra panels optionsPanel, parent1Panel and parent2Panel to help group and align the components.

I've also added a resultsPanel to house the resulting Punnett square. Since that doesn't currently have any content, I added a red line border to make the panel visible.

This doesn't exactly replicate the layout on your sketch, but it's close and I think you should be able to mess around with the constraints from here to refine the layout to be exactly as you desire.

GeneticsGUI

import javax.swing.*;
import java.awt.*;

public class GeneticsGUI {
    public static void main(String[] args) {

        boolean debug = true;
        JFrame window = new JFrame("Genetics");
        JPanel panel = new JPanel();

        panel.setLayout(new GridBagLayout());

        JPanel optionsPanel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 0, 0, 0);
        panel.add(optionsPanel, c);

        JLabel optionsLabel = new JLabel("Options:");

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(0, 5, 0, 5);
        optionsPanel.add(optionsLabel, c);

        String[] options = new String[]{"2x2 Punnett Square", "4x4 Punnett Square"};
        JComboBox<String> optionsCombo = new JComboBox<>(options);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        optionsPanel.add(optionsCombo, c);

        String selected = (String) optionsCombo.getSelectedItem();

        JPanel parent1Panel = new JPanel(new GridBagLayout());
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 1;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 0, 5, 0);
        panel.add(parent1Panel, c);

        JLabel p1 = new JLabel("Parent 1:");
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(0, 5, 0, 5);
        parent1Panel.add(p1, c);

        JTextField par1 = new JTextField();
        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        parent1Panel.add(par1, c);

        JPanel parent2Panel = new JPanel(new GridBagLayout());
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 2;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 0, 5, 0);
        panel.add(parent2Panel, c);

        JLabel p2 = new JLabel("Parent 2:");
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(0, 5, 0, 5);
        parent2Panel.add(p2, c);

        JTextField par2 = new JTextField();
        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        parent2Panel.add(par2, c);

        JButton submit = new JButton("Calculate");
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 3;
        c.weightx = 1;
        //           c.weighty = .1;
        c.insets = new Insets(0, 5, 0, 0);
        c.anchor = GridBagConstraints.LINE_START;
        panel.add(submit, c);

        JPanel resultsPanel = new JPanel();
        resultsPanel.setBorder(BorderFactory.createLineBorder(Color.red));
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 4;
        c.weightx = 1;
        c.weighty = 1;
        c.insets = new Insets(5, 5, 5, 5);
        c.anchor = GridBagConstraints.LINE_START;
        c.fill = GridBagConstraints.BOTH;
        panel.add(resultsPanel, c);

        window.add(panel);
        window.setSize(800, 800);
        window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        window.setVisible(true);
    }
}

enter image description here

Jason Braucht
  • 2,358
  • 19
  • 31
  • Thanks, did not know about that the NetBeans IDE had that built in. I was now trying to use the GridBagLayout and I'm slowly getting the hang of it. I might use the NetBeans IDE to help me at some point though since I'm sure I'll hit a roadblock at some point. Thanks for the tips! – Akhil Murthy Dec 20 '16 at 21:42
  • @user3238399: while this answer may suggest that you learn and use NetBeans drag-and-drop to create your complex GUI's, and while this will work, you will not understand the underlying layouts that NetBeans and Swing are using, and thus will eventually run up into a wall when you need to go beyond the abilities of NetBeans, such as if you want to change layout or add components in the midst of program run. For that reason you're far better off learning about and using the layout managers. – Hovercraft Full Of Eels Dec 20 '16 at 22:15
  • 1
    @user3238399: You can find the layout manager tutorial here: [Layout Manager Tutorial](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html), and you can find links to the Swing tutorials and to other Swing resources here: [Swing Info](http://stackoverflow.com/questions/tagged/swing). – Hovercraft Full Of Eels Dec 20 '16 at 22:16
  • @HovercraftFullOfEels I agree 100% about the limitations of drag-and-drop layout editors. However, I also tend to think GridBagLayout is complex enough that it's not advisable to learn for a one-off use. Based on the question, I surmised that OP wasn't necessarily looking to master the use of swing layout managers. Thus my suggestion to use a drag-and-drop editor instead. :) – Jason Braucht Dec 20 '16 at 22:44
  • @HovercraftFullOfEels Yeah, after trying the NetBeans, I decided it was completely pointless for me to use. the code became very difficult to read and was very counter intuitive ( obviously as it was done by the program). I am using the GridBagLayout and am having some success with it so far. I am struggling to make the first collumn grid spaces smaller, and wanted to know how I could align the Textfield to be next to the Label. Here is what it looks like now: https://snag.gy/lZwiSH.jpg – Akhil Murthy Dec 20 '16 at 23:20
  • @user3238399 post your current code and we'll help you get the layout fixed up - based on the screenshot, it looks like you don't have your `GridBagConstraints` quite right yet. – Jason Braucht Dec 20 '16 at 23:24
  • @AkhilMurthy I've added some edits to your code as an example in my answer. You were on the right path, I made some adjustments to get closer to the layout you wanted. Take a look at it and let us know if you still need more help. – Jason Braucht Dec 21 '16 at 05:54
  • I think it's looking good, I added some space between the options label and the parents labels to give space for the drop down menu. The only thing I would maybe want to change is to add the parent's strings to the side of the table. Here's an example I drew in paint: – Akhil Murthy Dec 21 '16 at 17:50
  • @AkhilMurthy I think you could achieve that layout by using `GridBagLayout` inside the `resultsPanel`. Try a 7x7 grid, where the labels occupy the first row/column, and the Punnett square fills the remaining 6x6 By using the `gridwidth` and `gridheight` attributes on `GridBagConstraints`, you can make the Punnett square span multiple rows/columns and then you should be able to put each label in a single row/column, to center them relative to the square. (I'll try to code an example of this later today.) – Jason Braucht Dec 22 '16 at 15:00
  • What I currently was attempting to place two other tables, one vertical and to the left of the square, and one horizontal to the top of the square. I was able to position the vertical one fine, because the default location was where I needed it anyway, but the horizontal one did not work. Here is how my vertical one looks: https://snag.gy/NJOZry.jpg; but this is what happens when i try to put a horizontal table in: https://snag.gy/fWkHNA.jpg. Is there any easier way to move that second table north of the original square? – Akhil Murthy Dec 22 '16 at 17:47
  • I'm pretty sure I could accomplish this with the GridBagLayout, but I felt like my code was getting very confusing and wondered if there was an easier way. – Akhil Murthy Dec 22 '16 at 17:48