2017-04-24 68 views
0

我正在嘗試使用帶有一些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)); 
     } 
    } 
    ); 

} 

} 
+0

將創建BorderLayout的,但似乎並沒有被添加到任何 –

回答

1

我不知道你爲什麼這樣做layout.addLayoutComponent(labels, BorderLayout.CENTER);,這不是你應該如何與佈局管理器進行交互

由於JFrame使用BorderLayout默認情況下,有沒有必要建立一個新的,而不是,只是你用滑塊做同樣的事情,面板添加到容器

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

我將如何去排隊a中的標籤垂直行與水平? –

+0

查看[佈局管理器視覺指南](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html)和[佈置容器內的組件](http:// docs.oracle.com/javase/tutorial/uiswing/layout/index.html) – MadProgrammer