Java 如何获取动态生成的组件的值?
我正在动态生成一个名称框、滑块和标签的列表,并试图找出如何访问滑块的值和更改标签。其他帖子建议使用数组,但我不知道从哪里开始 我的代码如下:Java 如何获取动态生成的组件的值?,java,swing,Java,Swing,我正在动态生成一个名称框、滑块和标签的列表,并试图找出如何访问滑块的值和更改标签。其他帖子建议使用数组,但我不知道从哪里开始 我的代码如下: public Tailoring(int n) { /*initComponents();*/ JPanel containerPanel = new JPanel(); containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS));
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);
}
}
公共剪裁(int n){
/*初始化组件()*/
JPanel containerPanel=新的JPanel();
containerPanel.setLayout(新的BoxLayout(containerPanel,BoxLayout.PAGE_轴));
添加(容器面板);
JLabel Title=新JLabel(“剪裁:”);
集装箱面板添加(标题);
对于(int i=0;i
您可以创建一个扩展JPanel的新类YourPanel
。
而不是声明
JPanel rowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
你可以用
YourPanel rowPanel = new YourPanel(new FlowLayout(FlowLayout.LEFT));
将textfield、slider和label定义为该YourPanel
类的属性。
为每个字段提供getter/setter。然后在应用程序中使用Panel对象的数组或ArrayList。您将能够通过以下呼叫到达第N个面板的标签:
panels.get(n).getJLabel();
似乎您希望在修改关联的JSlider时更改JLabel中显示的值,对吗?在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
}
注释
- 按照惯例,变量名应该以小写字母开头
- 我提到的事件侦听器也应该附加在循环中。看
JLabel updateLabel = sliderToLabel.get(targetedSlider);
updateLabel.setText("updated text");