Carl Davis
Carl Davis

Reputation: 63

How to get values of dynamically generated components?

I am dynamically generating a list of name boxes, sliders and labels, and am trying to figure out how to access the values of the sliders and change the labels. Other posts suggest using an array, but I have no idea where to begin with that.

My code is as such:

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

Upvotes: 2

Views: 361

Answers (2)

Juvanis
Juvanis

Reputation: 25950

You can create a new class YourPanel which extends JPanel. Instead of the statement

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

you can use

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

Define textfield, slider and label as the properties of this YourPanel class. Provide getters/setters for each field. Then use an array or ArrayList of YourPanel objects in your application. You will be able to reach the nth panel's label with a call like:

panels.get(n).getJLabel();

Upvotes: 1

calebds
calebds

Reputation: 26228

It appears that you'd like to change the value displayed in the JLabel when the associated JSlider is modified, right? The best way to associate pairs of objects in Java is with a Map structure:

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
}

You will be able to get a reference to the JSlider in the code that listens for changes on that component.

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

Notes

  • As a matter of convention, variable names should begin with lower case letters
  • The event listener I alluded to should also be attached in the loop. See Writing Event ListenersOracle

Upvotes: 0

Related Questions