我正在嘗試使用帶有一些JLabel的滑塊來製作一個簡單的程序,該程序將滑塊的半徑和輸出標記爲圓周和直徑。我的問題是我似乎無法弄清楚如何佈局帶邊框佈局的標籤。滑塊將顯示出來很好,但我希望能夠在一行標籤中左側排列標籤。帶有JFrame的邊框佈局
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));
}
}
);
}
}
將創建BorderLayout的,但似乎並沒有被添加到任何 –