How to remove empty lines from Jlabel if the label text is not used

Viewed 50

"If user input YES for flag1, then the message History is recommended... will display in the first line of JLabel.If user input NO for flag1, then it will not display anything in the first line. My question is how to enable the flag2 message,English core is recommended... to be displayed in the first line of JLabel if the user input NO for flag1 and YES for flag2 "

        if (flag1 == 1) {
            JLabel label1 = new JLabel("History is recommended because you have not taken the core subject");
            label1.setBounds(10, 10, 800, 25);
            add(label1);
        }
        if (flag2 == 2) {
            JLabel label2 = new JLabel("English core is recommended because you have not taken the language core");
            label2.setBounds(10, 30, 800, 25);
            add(label2);
1 Answers
  1. Build an ArrayList of messages.
  2. Then iterate through the ArrayList and create a JLabel for each message and add the label to the panel.

Also, don't use a null layout and setBounds(). Swing was designed to be used with layout managers. You could for example use a Box Layout.

This approach is more dynamic as it will support any number of messages.

Or instead of using individual labels, you could use other Swing components for multi-line display, like:

  1. a non editable JTextArea and just append(...) a message as required.
  2. a JList
Related