opike
opike

Reputation: 7585

Java: Text not wrapping in JFrame dialog

I'm using a JFrame to present a message box with some text and 2 buttons. How do I get the text to wrap automatically based on the size of the box?

Here's my current code:

        dialogFrame = new JFrame();

        JButton newButton = new JButton("New");
        newButton.addActionListener(new newUploadAction());

        JButton resumeButton = new JButton("Resume");
        resumeButton.addActionListener(new resumeUploadAction());

        //dialogFrame.setUndecorated(true);

        JPanel addPanel = new JPanel();

        JPanel addPanel2 = new JPanel();

        addPanel.add(newButton);
        addPanel.add(resumeButton);

        String text = "<html><p>A previous control file exists for this file. ";
        text += "Would you like to initiate a new transfer or resume the previous one?</p></html>";

        JLabel testLabel = new JLabel(text);

        //testLabel.setPreferredSize(new Dimension(1, 1)); 

        addPanel2.add(testLabel);


        Container content = dialogFrame.getContentPane();


        //content.setBackground(Color.white);
        content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS)); 

        content.add(addPanel2);
        content.add(addPanel);


        dialogFrame.setSize(200,200);
        dialogFrame.setVisible(true);
        dialogFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

I read somewhere that calling

  testLabel.setPreferredSize(new Dimension(1, 1)); 

would cause the wrapping behavior I want, but that just resulted in the text not showing up at all.

Upvotes: 0

Views: 3036

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You could place the text in a JTextArea and call setLineWrap(true) and setWrapStyleWord(true) on the JTextArea. If you want it to look more JLabel-ish, then just change the color settings of the JTextArea to your liking.

EDIT 1

Also another thing that could work: consider having the holding JPanel use a BorderLayout:

JPanel addPanel2 = new JPanel(new BorderLayout()); //!! added BorderLayout

So that the JLabel added will fill the addPanel2.

Upvotes: 3

Related Questions