1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Updating a JLabel with an integer array

  1. Aug 6, 2012 #1
    halfway through my code so its a bit of mess but this is simple what i need to do.

    I have a JLabel array of 6 labels.

    a random number is generated, its then split into its digits into a 6 element array of integers. now i need to update the Jlabels with the integer array of digits.

    my JLabel declaration is

    odometer = new JLabel[ 6 ]; // create array for odometer digits
    odometerJPanel = new JPanel();
    for ( int count = 0; count < odometer.length; count ++)
    {
    odometer[ count ] = new JLabel( " 0 " );
    odometerJPanel.add( odometer[ count ] ); // add odometer to JPanel
    }

    so initially the labels are all 0.
    i have another array filled with the digits i want to put onto the JLabels.
    How?

    Thanks in advance
     
  2. jcsd
  3. Aug 6, 2012 #2

    Mark44

    Staff: Mentor

    Convert the random number to a string, then peel of the digits one by one and put each one in the appropriate JLabel. Am I correct in assuming you are writing Java code?
     
  4. Aug 7, 2012 #3

    Filip Larsen

    User Avatar
    Gold Member

    Use the JLabel.setText method perhaps?
     
  5. Aug 9, 2012 #4
    That's what I ended up doing. But to use the set text method it needs to be applied individually to each index of the array. So I have like 30 lines of code to set the number, colour and font size. Just means its a lot of repetitive code. I was looking for a way to do it using the array directly but seems most methods can't be applied to arrays, only Ints and strings. And yeah writing java. Thanks guys (:
     
  6. Aug 9, 2012 #5

    Filip Larsen

    User Avatar
    Gold Member

    Sound like you could benefit from moving the code that sets the properties of each JLabel into a loop (if the "source" data is also stored in arrays) or at least method, like the setMyLabel example method below.

    Code (Text):

    public void setMyLabel(JLabel label, String text, Color color, float pt) {
      label.setText(text);
      label.setForeground(color);
      label.setFont(label.getFont().deriveFont(pt));
    }


    JLabel[] labels = ...
    ...
    setMyLabel(labels[0], "first", Color.RED, 12);
    setMyLabel(labels[1], "second", Color.GREEN, 10);
    ...
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Updating a JLabel with an integer array
  1. JLabel java question. (Replies: 1)

  2. Array C++ (Replies: 2)

  3. C - array (Replies: 2)

  4. Function and array (Replies: 26)

Loading...