Destiny
Destiny

Reputation: 91

Making a Java GUI: Center Button Is Not Extending Into Space As It Should

The button is supposed to extend from the top textfield to the bottom button and to each side of the number pad. For some reason the center panel is not taking up this space. Here is my code:

package activeLearningAssignment5;

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

public class FrameExample extends JFrame {
  public FrameExample() {
    //create font
    Font font1 = new Font("Times New Roman", Font.ITALIC, 20);

    //Create Panel for right side letters
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(4, 3));

    //Add buttons to panel
    for (char ch = 'a'; ch <= 'l'; ch++) {
      p1.add(new JButton("" + ch));
    }

    //Create panel/add button for center
    JPanel p2 = new JPanel();
    p2.add(new JButton("This is the center"));

    //Create Panel/add button for west. Simple way to make buttons but won't actually be usable
    JPanel p3 = new JPanel();

    for (char ch = 'l'; ch <= 'o'; ch++) {
      p3.add(new JButton("" + ch));
    }

    //Creates the textfield and sets the font
    JTextField JText = new JTextField("This is my First GUI Program");
    JText.setFont(font1);

    //Click me or else button
    JButton JClick = new JButton("Click me or else!");

    // add stuff to frame
    add(p1, BorderLayout.EAST);
    add(p2, BorderLayout.CENTER);
    add(p3, BorderLayout.WEST);
    add(JClick, BorderLayout.SOUTH);
    add(JText, BorderLayout.NORTH);

  }


  public static void main(String[] args) {
    JFrame frame = new FrameExample();
    frame.setTitle("Learning Assignment 5");
    frame.setSize(700, 250);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);


  }

}

Sorry the spacing got messed up a bit.

Thanks!

Upvotes: 0

Views: 150

Answers (1)

Oliver Watkins
Oliver Watkins

Reputation: 13499

Your p2 JPanel is being stretched out fine! But that is not being reflected in the button that is inside it. Either get rid of p2 and add the button directly, or set the layout for JPanel to BorderLayout like so :

// Create panel/add button for center
JPanel p2 = new JPanel(new BorderLayout());

Upvotes: 4

Related Questions