Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.awt.Component;

import javax.swing.JDialog;

import javax.swing.JOptionPane;

public class Main {
    /** Show a confirmation message box with line wrapped message.
     *
     * 'optionType' is one of the JOptionPane.XXX_OPTION combination
     * constants, and the return value is one of the single-value
     * constants. */
    public static int confirmationBox(Component parent, String message, String title, int optionType) {
        JOptionPane pane = makeWordWrapJOptionPane();
        pane.setMessage(message);
        pane.setMessageType(JOptionPane.QUESTION_MESSAGE);
        pane.setOptionType(optionType);

        JDialog dialog = pane.createDialog(parent, title);
        dialog.setVisible(true);

        Object result = pane.getValue();
        if (result == null || !(result instanceof Integer)) {
            return JOptionPane.CLOSED_OPTION;
        } else {
            return ((Integer) result).intValue();
        }
    }

    /** Create a JOptionPane instance that word-wraps its message. */
    public static JOptionPane makeWordWrapJOptionPane() {
        // The basic problem is described in this bug report:
        //
        //   http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4104906
        //
        // The workaround there requires adding a scrollbar to the
        // message, which I do not want to do.

        // I tried these solutions, but they do not work (anymore?):
        //
        //   http://stackoverflow.com/questions/4330076/joptionpane-showmessagedialog-truncates-jtextarea-message
        //   http://www.coderanch.com/t/339970/GUI/java/wrap-large-message-JOptionPane-showConfirmDialog
        //
        // Most other solutions involve manually inserting newlines.

        // Thankfully, this one actually does work:
        //
        //   http://www.jroller.com/Fester/entry/joptionpane_with_word_wrapping

        @SuppressWarnings("serial")
        JOptionPane pane = new JOptionPane() {
            @Override
            public int getMaxCharactersPerLineCount() {
                return 80;
            }
        };
        return pane;
    }
}