JFrame的边框布局

时间:2017-04-24 23:22:40

标签: java swing jframe border-layout

我试图使用带有一些JLabel的滑块来制作一个简单的程序,该程序从滑块获取半径并输出到标签的圆周和直径。我的问题是我似乎无法弄清楚如何使用边框布局布局标签。滑块将显示正常,但我希望能够在一行标签的左侧排成一行标签。

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));
        }
    }
    );

}

}

1 个答案:

答案 0 :(得分:1)

我不确定您为什么要这样做layout.addLayoutComponent(labels, BorderLayout.CENTER);,这不是您应该如何与布局管理器进行交互

由于JFrame默认使用BorderLayout,因此无需创建新的,只需执行与滑块相同的操作,将面板添加到容器

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