2

I've been trying to setup this border layout for hours. I've looked up How to Use BorderLayout on the Java website but I still haven't gotten it.

I've included my code below for review and to make it easier to see how I am trying to use the BorderLayout function.

How do I setup a border layout on JL3?

class GameStructure {
    private String []wordList = {"computer","java","activity","alaska","appearance","article",
            "automobile","basket","birthday","canada","central","character","chicken","chosen",
            "cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
            "establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
            "hurried","identity","importance","impossible","invented","italian","journey","lincoln",
            "london","massage","minerals","outer","paint","particles","personal","physical","progress",
            "quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
            "strike","successful","sudden","terrible","traffic","unusual","volume","yesterday"};
   private JTextField tf;
   private JLabel jl2;

   public void window() {
      ImageIcon ic = new ImageIcon("hangman.png");
      JFrame gameFrame = new JFrame();
      JPanel jp = new JPanel();
      JPanel jpLets = new JPanel();
      JPanel jpBlank = new JPanel();
      JPanel imgPane = new JPanel();
      JPanel panel1 = new JPanel();
      JPanel panel2 = new JPanel();
      panel2.setLayout(new BorderLayout());
      jpLets.setLayout(new BoxLayout(jpLets, BoxLayout.Y_AXIS));
      panel1.setLayout(new BorderLayout());
      panel1.setOpaque(false);//!!
      //jp.setBorder(BorderFactory.createTitledBorder(""));
      tf = new JTextField(1);
      JLabel img = new JLabel(ic, JLabel.CENTER);
      JLabel jl = new JLabel("Enter a letter", JLabel.CENTER);
      jl2 = new JLabel("Letters used:  ", JLabel.CENTER);
      JLabel jl3 = new JLabel("__ ", JLabel.CENTER);
      jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
      tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
      jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
      imgPane.add(img, BorderLayout.CENTER);
      jp.add(jl);
      jp.add(tf);
      jpLets.add(jl2);
      jpBlank.add(jl3);
      //jpMain.add(imgPane, BorderLayout.CENTER);
      panel1.add(jp, BorderLayout.NORTH);
      panel1.add(jpLets, BorderLayout.SOUTH);
      panel1.add(imgPane);
      panel2.add(panel1, BorderLayout.CENTER);
      panel2.add(jpBlank, BorderLayout.PAGE_END);
      gameFrame.setTitle("Hangman");
      gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      gameFrame.setIconImage(
      new ImageIcon("Hangman-Game-grey.png").getImage());
      gameFrame.setResizable(false);
      gameFrame.add(panel2);
      gameFrame.setSize(600, 600);
      gameFrame.setLocationRelativeTo(null);
      gameFrame.setVisible(true);

          int j = 0;
          int []length = new int[64];
          for(j = 0; j<64; j++) {
             length[j] = wordList[j].length();//gets length of words in wordList
          }//end for
          int l = 0;
          String line = "";
          //create line first then put into .setText
          for(int m = 0; m<length[l]; m++) {
              line += "__ ";
              l++;
          }//end for
          jl3.setText(line);

          tf.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {//when enter key pressed
              JTextField tf = (JTextField)e.getSource();
              String letter = tf.getText();
              jl2.setText(jl2.getText() + letter + " ");//sets jlabel text to users entered letter
              }//end actionPerformed method
          });
      }//end userInput method
   }

public class GameMain {
   public static void main(String[] args) {
      GameStructure game = new GameStructure();
      game.window();
   }
}
Rafa Viotti
  • 9,998
  • 4
  • 42
  • 62
Anon
  • 141
  • 1
  • 11

2 Answers2

2

First of all, let me commend you on actually looking at that tutorial I linked you yesterday and putting effort into learning :)

Here's a couple things I see.

Here, you're trying to use a BorderLayout for a JLabel. Generally you want to use the LayoutManagers with containers, (JPanels, JFrames, JDialogs, JApplets). Get rid of the code below.

JLabel img = new JLabel(ic, JLabel.CENTER);
img.setLayout( new BorderLayout() );

Also here, With all your jp.add()'s.

jp.add(img, BorderLayout.CENTER);
jp.add(jl);
jp.add(tf);
jp.add(jl2);
....

I'm assuming you want to use a BorderLayout, but there was no BorderLayout specified for the jp Panel. By default, if you don't specify a LayoutManager, JPanel will give you a FlowLayout

JPanel jp = new JPanel();

Keep in mind, when you assign a BorderLayout to a container, you want to make sure every component you add to it, has a Layout position specified. No position should be used more than once. Also, a BorderLayout.CENTER generally should always be used. (e.g. if you only have two components in the panel, use BorderLayout.SOUTH, BorderLayout.CENTER).

Also, you should learn to nest Layout with multiple Panels to get your desired result. Here's a simple example. Say you have two buttons and a Image Label

JLabel label = new JLabel(new ImageIcon(filePath));
JButton jbt1 = new JButton("jbt1");
JButton jbt2 = new JButton("jbt2");

I want the layout to look like this

+--------------------------------+
|                                |
|                                |
|          Image Label           |
|                                |
+----------------+---------------+
|      jbt1      |      jbt2     |
+----------------+---------------+

First thing I want to do is add the buttons to a separate JPanel. Then wrap the label in a JPanel (not necessary, but I like using panels);

JPanel buttonsPanel = new JPanel();     <-- FlowLayout (none specified)
buttonsPanel.add(jbt1);
buttonsPanel.add(jbt2);

JPanel labelPanel = new JPanle();       <-- FlowLayout
labelPabel.add(label);

Then I'm going to wrap the two panels with another panel with a BorderLayout

JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(buttonPanel, BorderLayout.SOUTH);
panel1.add(labelPanel, BorderLayout.CENTER);

So my final panel would look like this

            panel1
+--------------------------------+
|                                |
|                                |   BorderLayout.CENTER
|          Image Label           |
|                                |
+----------------+---------------+
|      jbt1      |      jbt2     |   BorderLayout.SOUTH
+----------------+---------------+

Let's say you came up with another panel you wanted to add. You want to add this new panel to the left of the panel we just created. We only now need to use the panel1 panel we created and wrap that panel and new panel in another panel

JPanel newPanel = new JPanel();

JPanel panel2 new JPanel(new BorderLayout());
panel2.add(newPanel, BorderLayout.WEST);
panel2.add(panel1, BorderLayout.CENTER);

             panel2
+---------------+--------------------------------+
|               |                                |
|               |                                |  
|               |          Image Label           |
|    newPanel   |                                |
|               +----------------+---------------+
|               |      jbt1      |      jbt2     |   
+---------------+----------------+---------------+

See how the layout and panel have been. This is great way to handle laying out components

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Small addition: `BorderLayout.CENTER` is the big-boy container in the layout. AKA if you have a two objects in CENTER and SOUTH, the object in the center will expand to fill in any extra space instead of the other way around. A good exercise to see how layouts work is to create a basic frame and a whole bunch of panels with different background colors. (So you can see them distinguished from each other.) Then you can do things like re-arrange the panels with different kinds of layout managers and see what happens. – Andrew Gies Dec 23 '13 at 02:24
  • I tried setting it up like you said but no luck :( I updated the code above. – Anon Dec 23 '13 at 04:01
  • @Anon, it doesn't look like you've added `jpMain` to the `gameFrame` – Paul Samsotha Dec 23 '13 at 04:08
  • @Anon, try changing this `gameFrame.add(jp);` to `gameFrame.add(jpMain);` – Paul Samsotha Dec 23 '13 at 04:10
  • I've gotten everything to line up accordingly thanks to you, except the background image. Hopefully you can help me out with one last thing. The background image is not centred on screen but instead a bit to the left. Any idea why? I've updated my code. Thanks for everything. – Anon Dec 23 '13 at 05:32
  • @Anon Not sure. My guess is you haven't set a layout position to the `imgPane` – Paul Samsotha Dec 23 '13 at 05:53
0

You are not adding the jp to the gameFrame nor the jp2. Either way you add many components to the jp panel, which is not set as a BorderLayout (so, by default it is set to FlowLayout) and then you just add it to the jp2, which is set to BorderLayout, but has only two components.

So, try to add the following line between these two (existing) lines:

gameFrame.setResizable(false);
gameFrame.add(jp);
gameFrame.pack();
prmottajr
  • 1,816
  • 1
  • 13
  • 22
  • Can you please clarify. – Anon Dec 23 '13 at 00:42
  • @Anon by the code you showed (which is not the complete code) I was following with the info that you gave :) If you follow the code you see that you create a JFrame right in the begginig but you didn't add the panels to the Frame, only the img variable – prmottajr Dec 23 '13 at 00:45
  • When I added those lines, a blank JFrame is displayed – Anon Dec 23 '13 at 00:58
  • @Anon I am sorry, mistyped it, it is jp that needs to be added to the gameFrame – prmottajr Dec 23 '13 at 01:03
  • Now the image is not displaying but only the JTextField and JLabel. – Anon Dec 23 '13 at 01:14
  • @Anon Each component that needs to be displayed will has to be added to the gameFrame. One thing that is very common is to add everything to a panel and then add the panel. You should add the img to the jp in the center position like jp.add(img, BorderLayout.CENTER) instead of adding the img to the gameFrame – prmottajr Dec 23 '13 at 01:19
  • My image still hasn't been centred, I've updated my code above. – Anon Dec 23 '13 at 01:31
  • @Anon the code is a little confusing, your are using the BorderLayout on jp2, so I was wrong about one thing the img should be added to jp2 with jp2.add(img, BorderLayout.CENTER); although, by the code I cannot be sure it will be centrilized because the panel that is being added to the gameFrame is the jp – prmottajr Dec 23 '13 at 01:43