4

I am learning programming with Java through a textbook. A programming exercise asks you to:

(Swing common features) Display a frame that contains six labels. Set the background of the labels to white. Set the foreground of the labels to black, blue, cyan, green, magenta, and orange, respectively, as shown in Figure 12.28a. Set the border of each label to a line border with the color yellow. Set the font of each label to Times Roman, bold, and 20 pixels. Set the text and tool tip text of each label to the name of its foreground color.

I have two answers to the problem. My answer and the books answer. Both answers work fine.

I use an Array and populate it with anonymous objects by using a loop (as shown in class Sixlabels extends JFrame{}):

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;


public class TWELVE_point_8 {

public static void main(String[] args) {

    JFrame frame = new SixLabels();
    frame.setTitle("Six Labels");
    frame.setSize(300, 200);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}

}

class SixLabels extends JFrame {

public SixLabels() {
    setLayout(new GridLayout(2, 3));

    JLabel[] list = {
        new JLabel("Black"),
        new JLabel("Blue"),
        new JLabel("Cyan"),
        new JLabel("Green"),
        new JLabel("Magenta"),
        new JLabel("Orange")};

     // set foreground colors
    list[0].setForeground(Color.black);
    list[1].setForeground(Color.blue);
    list[2].setForeground(Color.cyan);
    list[3].setForeground(Color.green);
    list[4].setForeground(Color.magenta);
    list[5].setForeground(Color.orange);

    // set background colors
    for (int i = 0; i < list.length; i++)
        list[i].setBackground(Color.white);

    // set fonts
    Font font = new Font("TimesRoman", Font.BOLD, 20);

    for (int i = 0; i < list.length; i++)
        list[i].setFont(font);

    // set borders
    Border lineBorder = new LineBorder(Color.yellow, 1);

    for (int i = 0; i < list.length; i++)
         list[i].setBorder(lineBorder);

    // set tooltip
    for (int i = 0; i < list.length; i++)
            list[i].setToolTipText(list[i].getText());

    // add all labels to container
    for (int i = 0; i < list.length; i++)
        add(list[i]);

}
}

And the book answer does not use an array list (as shown in public Exercise12_8 extends JFrame{});:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class Exercise12_8 extends JFrame {
      private JLabel jlblBlack = new JLabel("black");
      private JLabel jlblBlue = new JLabel("blue");
      private JLabel jlblCyan = new JLabel("cyan");
      private JLabel jlblGreen = new JLabel("green");
      private JLabel jlblMagenta = new JLabel("magenta");
      private JLabel jlblOrange = new JLabel("orange");

      public Exercise12_8() {
          setLayout(new GridLayout(2, 3));
          this.add(jlblBlack);
          this.add(jlblBlue);
          this.add(jlblCyan);
          this.add(jlblGreen);
          this.add(jlblMagenta);
          this.add(jlblOrange);

          jlblBlack.setBackground(Color.WHITE);
          jlblBlue.setBackground(Color.WHITE);
          jlblCyan.setBackground(Color.WHITE);
          jlblGreen.setBackground(Color.WHITE);
          jlblMagenta.setBackground(Color.WHITE);
          jlblOrange.setBackground(Color.WHITE);

          jlblBlack.setForeground(Color.BLACK);
          jlblBlue.setForeground(Color.BLUE);
          jlblCyan.setForeground(Color.CYAN);
          jlblGreen.setForeground(Color.GREEN);
          jlblMagenta.setForeground(Color.MAGENTA);
          jlblOrange.setForeground(Color.ORANGE);

          Font font = new Font("TImesRoman", Font.BOLD, 20);
          jlblBlack.setFont(font);
          jlblBlue.setFont(font);
          jlblCyan.setFont(font);
          jlblGreen.setFont(font);
          jlblMagenta.setFont(font);
          jlblOrange.setFont(font);

          Border border = new LineBorder(Color.YELLOW);
          jlblBlack.setBorder(border);
          jlblBlue.setBorder(border);
          jlblCyan.setBorder(border);
          jlblGreen.setBorder(border);
          jlblMagenta.setBorder(border);
          jlblOrange.setBorder(border);

          jlblBlack.setToolTipText("black");
          jlblBlue.setToolTipText("blue");
          jlblCyan.setToolTipText("cyan");
          jlblGreen.setToolTipText("green");
          jlblMagenta.setToolTipText("magenta");
          jlblOrange.setToolTipText("orange");
      }

      public static void main(String[] args) {
          Exercise12_8 frame = new Exercise12_8();
          frame.setTitle("Exercise12_8");
          frame.setSize(400, 400);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setLocationRelativeTo(null); // Center the frame
          frame.setVisible(true);
     }
}

My question is: is it better practice to declare the JLabel object individually (as the book has) or to populate the Array (or ArrayList) anonymously as I have? The only benefit I see in doing it the book's way is readability and having a variable name (which may be used in future programs, but not in this particular one).

Cœur
  • 37,241
  • 25
  • 195
  • 267
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720

5 Answers5

3

I can provide you a third answer. Create a method that takes a JLabel and configures it. That way you could use either of the other two and reduce your code complexity.

The answer is, it depends. It depends on what it is you want to achieve.

If you are making lots of changes, repeatedly to the same serious of components, such as you are here, I might be tempted to use a simple List or array. This is particularly useful if the number of elements is dynamic and or only accessiable internally to the class.

If, on the other hand you want to change or update the state of the components externally, it's normally easier to provide named access to the components. Yes, you could provide a method that uses a int parameter, but then you start running into issues with always having to validate the parameter :P

So I guess, the question is, what is it you need to achieve?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2

I would suggest that if you are learning to program for professional reasons then you should follow as it given in the book. Because in bigger projects (if you might be working on one in future), this practice is very common and as you said, readability and a variable name. Say it is like a convention.

Nitesh Verma
  • 1,795
  • 4
  • 27
  • 46
0

Collections or arrays would be my preference. Making changes or adding additional fields would be easy. In your first example, you could do everything in one loop. You don't need a separate loop per attribute. Your code would be tiny after removing the extra loops.

Tony Ennis
  • 12,000
  • 7
  • 52
  • 73
0

in my opinion better practice would be create method Jlabel createLabel(String text, Color foregroundColor) and use it in loop to create labels

wedens
  • 1,782
  • 14
  • 18
0

It seems that you have answered the question yourself. Yes you would need references (what you call a variable name) if you there is a requirement to manipulate the labels (change attributes) on event generations. But yes if there is no such requirement, in that case your method of using an Array or List is clean and requires less code writing effort.

Rishi
  • 220
  • 1
  • 9