Search code examples
javaswingjlabel

Creating a JLabel with multiple lines from other text


I was creating a program to take text from a JTextArea and put it into a JLabel, but a JLabel is only one lie and the only way I know of to add multiple lines to a JLabel is to use html functions which you have to place into the text. How would I create new lines,is there maybe a way to find where the JTextArea version of new line or is it something completely different?


Solution

  • Simplest solution: don't use a JLabel. Place your text into a JTextArea that looks like a JLabel -- that is not opaque, focusable nor editable.

    e.g.,

    import java.awt.event.ActionEvent;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class AreaAsLabel extends JPanel {
        private JTextArea textEntry = new JTextArea(5, 20);
        private JTextArea labelLikeDisplay = new JTextArea(5, 20);
    
        public AreaAsLabel() {
            textEntry.setLineWrap(true);
            textEntry.setWrapStyleWord(true);
    
            labelLikeDisplay.setLineWrap(true);
            labelLikeDisplay.setWrapStyleWord(true);
            labelLikeDisplay.setEditable(false);
            labelLikeDisplay.setFocusable(false);
            labelLikeDisplay.setOpaque(false);
    
            add(new JScrollPane(textEntry));
            add(new JButton(new TransferTextAction("Transfer Text")));
            add(labelLikeDisplay);
        }
    
        class TransferTextAction extends AbstractAction {
            public TransferTextAction(String name) {
                super(name);
                int mnemonic = (int) name.charAt(0);
                putValue(MNEMONIC_KEY, mnemonic);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = textEntry.getText();
                labelLikeDisplay.setText(text);
    
                textEntry.selectAll();
                textEntry.requestFocusInWindow();
            }
        }
    
        private static void createAndShowGui() {
            JFrame frame = new JFrame("AreaAsLabel");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new AreaAsLabel());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    }