Michael Fogarty
Michael Fogarty

Reputation: 301

Border Layout with JFrame

I'm trying to use a slider with some JLabels to make a simple program that takes the radius from the slider and outputs to labels the circumference and diameter. My problem is I can't seem to figure out how to layout the labels with border layout. The slider will show up just fine but I want to be able to layout the labels in a row on the left side in a row of labels.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class Slider extends JFrame {

private final JSlider radiusJSlider;
private final JLabel radius;
private final JLabel diameter;


public Slider() {
    super("Slider Demo");
    BorderLayout layout = new BorderLayout();
    radius = new JLabel("radius");
    diameter = new JLabel("diameter");

    radiusJSlider
            = new JSlider(SwingConstants.HORIZONTAL, 0, 200, 10);
    radiusJSlider.setMajorTickSpacing(10); // create tick every 10
    radiusJSlider.setPaintTicks(true);
    radiusJSlider.setPaintLabels(true);// paint ticks on slider

radiusJSlider.setLabelTable(radiusJSlider.createStandardLabels(10));
    //JPanel panel = new JPanel(new BorderLayout());

    //panel.add(diameter, BorderLayout.CENTER); 
    JPanel labels = new JPanel(new FlowLayout(FlowLayout.LEFT) );

    labels.add(radius);
    labels.add(diameter);

    add(radiusJSlider, BorderLayout.SOUTH);
    //add(radius, BorderLayout.CENTER);
    //add(diameter, BorderLayout.CENTER);
    layout.addLayoutComponent(labels, BorderLayout.CENTER);
    radiusJSlider.addChangeListener(
            new ChangeListener() // anonymous inner class
    {
        // handle change in slider value
        @Override
        public void stateChanged(ChangeEvent e) {
            int results;
            int diameterResults;

            results = radiusJSlider.getValue();
            diameterResults = results * 2;

            radius.setText(String.format("radius: %2d", radiusJSlider.getValue()));
            diameter.setText(String.format("diameter: %2d", diameterResults));
        }
    }
    );

}

}

Upvotes: 0

Views: 789

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

I'm not sure why you're doing this layout.addLayoutComponent(labels, BorderLayout.CENTER);, this isn't how you should interact with a layout manager

Since JFrame uses a BorderLayout by default, there's no need to create a new one, instead, just do the same thing you did with the slider, add the panel to the container

add(labels); // BorderLayout.CENTER is the default position

Upvotes: 1

Related Questions