nhouser9
nhouser9

Reputation: 6780

JOptionPane with text wrapping using custom Swing component

I have written many projects using JOptionPanes, and almost every time I am frustrated by the fact that I cannot wrap text inside them.

I know JOptionPane supports HTML, but that always seems to fall short of doing what I want. For one thing, JOptionPane doesn't fully support HTML - the max-width property would be awesome to have, for example. For another, neither <br /> nor <p> tags provide the functionality I'm really after - a JOptionPane that is small when the message is small, and can grow when the message is larger, but which does not get too large, and eventually breaks to a new line.

That brings me to my question. Is there some way to write a custom component of my own, maybe inheriting from a JFrame or something similar, which will allow me to simulate the effects of a JOptionPane, but which provides finer-grain control of the text displayed? This should include, at minimum, functionality to control max width and to wrap text.

I have not found an answer to this by searching other questions (maybe the answer is drowned out by all the answers saying "use HTML"). This is NOT a duplicate of those questions.

Upvotes: 0

Views: 638

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

Exmaple

import java.awt.Component;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class OptionPaneUtilities {

    public static void main(String[] args) {
        OptionPaneUtilities.showMessage(null, "I sometimes I think we forget just how flexible the JOptionPane API is and what it can do. A little effort could go a long way");
    }

    public static void showMessage(Component comp, String message) {
        JTextArea ta = new JTextArea(message, 1, 20);
        ta.setWrapStyleWord(true);
        ta.setLineWrap(true);
        ta.setOpaque(false);
        ta.setBorder(null);
        ta.setEditable(false);
        ta.setFocusable(false);
        JOptionPane.showMessageDialog(comp, ta);
    }

}

Now, obviously, this is just a really simple example, you're going to have to spend some time thinking about how best to apply this concept to your own API so it meets your needs and provides you with the greatest amount of flexibility.

You could make use of a JEditorPane instead and get both plain text and HTML to work with out to much more effort

Upvotes: 4

Ethan Moore
Ethan Moore

Reputation: 401

Are you talking about something such as just adding a line break so the option box doesn't show this long string of text? If so :

JOptionPane.showMessageDialog(null, "This "\nmessage "\nhas "\nlinebreaks.")

should suffice. Using \n(text) creates a line break. Hopefully this helps, have a good night. :)

Upvotes: 0

Related Questions