2012-02-15 96 views
2

我在动态生成名称框,滑块和标签的列表,并试图找出如何访问滑块的值并更改标签。其他帖子建议使用数组,但我不知道从哪里开始。如何获取动态生成的组件的值?

我的代码,例如:

public Tailoring(int n) { 
    /*initComponents();*/ 
    JPanel containerPanel = new JPanel(); 
    containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS)); 
    this.add(containerPanel); 
    JLabel Title = new JLabel("Tailoring:"); 
    containerPanel.add(Title); 
    for(int i = 0; i < n; i++){ 
     JPanel rowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); 
     JTextField NameBox = new JTextField("Guest " + (i+1)); 
     JSlider TipSlider = new JSlider(); 
     JLabel TipCost = new JLabel(); 
     rowPanel.add(NameBox); 
     rowPanel.add(TipSlider); 
     rowPanel.add(TipCost); 
     containerPanel.add(rowPanel); 
    } 
} 

回答

1

您可以创建一个新的类YourPanel其扩展JPanel。 相反的声明

JPanel rowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); 

,你可以使用

YourPanel rowPanel = new YourPanel(new FlowLayout(FlowLayout.LEFT)); 

定义文本框,滑块和标签,因为这YourPanel类的属性。 为每个字段提供获取者/设置者。然后在应用程序中使用YourPanel对象的数组或ArrayList。您将能够与像呼叫到达ñ面板的标签:

panels.get(n).getJLabel(); 
+0

您也可以向父节点_forward_事件,如[此处](http://stackoverflow.com/q/2159803/230513)中所述。 – trashgod 2012-02-15 21:08:20

0

看样子,你想更改的JLabel显示的值时,相关JSlider的修改,对吧?要对在Java对象关联的最好方法是用地图结构:

Map<Component, JSlider> sliderToLabel = new HashMap<Component, JSlider>(); 

for (int i = 0; i < n; i++) { 

    // after your loop code 

    sliderToLabel.put(TipSlider, TipCost); // map the slider to its label 
} 

您将能够在侦听该组件上的更改代码即可获得到JSlider的一个参考。

JLabel updateLabel = sliderToLabel.get(targetedSlider); 
updateLabel.setText("updated text"); 

注意

  • 由于习惯问题,变量名称应以小写字母
  • 事件监听我提到应该也可以在回路连接的开始。请参阅Writing Event ListenersOracle