Example usage for javax.swing JTextArea append

List of usage examples for javax.swing JTextArea append

Introduction

In this page you can find the example usage for javax.swing JTextArea append.

Prototype

public void append(String str) 

Source Link

Document

Appends the given text to the end of the document.

Usage

From source file:TextComponentTest.java

public TextComponentFrame() {
    setTitle("TextComponentTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    final JTextField textField = new JTextField();
    final JPasswordField passwordField = new JPasswordField();

    JPanel northPanel = new JPanel();
    northPanel.setLayout(new GridLayout(2, 2));
    northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
    northPanel.add(textField);/*  www. ja v a  2  s  .co  m*/
    northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
    northPanel.add(passwordField);

    add(northPanel, BorderLayout.NORTH);

    final JTextArea textArea = new JTextArea(8, 40);
    JScrollPane scrollPane = new JScrollPane(textArea);

    add(scrollPane, BorderLayout.CENTER);

    // add button to append text into the text area

    JPanel southPanel = new JPanel();

    JButton insertButton = new JButton("Insert");
    southPanel.add(insertButton);
    insertButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            textArea.append("User name: " + textField.getText() + " Password: "
                    + new String(passwordField.getPassword()) + "\n");
        }
    });

    add(southPanel, BorderLayout.SOUTH);

    // add a text area with scroll bars

}

From source file:testFileHandler.java

public void readFile(String path, javax.swing.JTextArea textField) {

    Scanner sc = new Scanner(System.in);
    BufferedReader br = null; //used BufferedReader to set Data to the textField line by line that passed as a parameter.
    String line;/* ww w  .  j a va2s .co  m*/

    try {
        br = new BufferedReader(new FileReader(path)); //FileReader read the content of the file from that given path,and return value pass to the BufferedReader.
        while ((line = br.readLine()) != null) { // reading line by line untill end of the lines
            textField.append(line + '\n'); //append that line get at a time and move the cursor to the next line
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:de.whiledo.iliasdownloader2.swing.service.MainController.java

public static void showError(final Component parent, String description, final Throwable e) {
    String s = "";
    if (e instanceof IliasHTTPSException) {
        s = "<br><br>Die SSL Verbindung konnte nicht aufgebaut werden." + "<br>Sie benutzen Java Version "
                + System.getProperty("java.version") + "."
                + "<br>Fr einige SSL Verbindungen bentigen Sie <b>Java 1.8 oder hher.</b>"
                + "<br>Sie knnen Java hier herunterladen: http://java.com"
                + "<br><br>Alternativ knnen Sie in den Einstellungen beim Serverpfad https:// durch http:// ersetzen."
                + "<br><b>Das wird aber NICHT empfohlen, da Ihr Loginname und Ihr Passwort ungeschtzt bertragen werden.</b>";
    }/*from  www  .  j  a v a2 s.c  o m*/

    description = description + s;

    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    panel.add(new JLabel("<html>" + description + "</html>"));

    JButton b = new JButton("Details");
    b.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ev) {
            final JTextArea textarea = new JTextArea();
            val c = new CircularStream();

            Thread t = new Thread(new Runnable() {

                @Override
                public void run() {
                    e.printStackTrace(new PrintStream(c.getOutputStream()));
                    IOUtils.closeQuietly(c.getOutputStream());
                }
            });
            t.start();

            try {
                textarea.append(IOUtils.toString(c.getInputStream()));
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            try {
                t.join();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            JPanel p = new JPanel(new BorderLayout());
            p.add(new JLabel(e.getMessage()), BorderLayout.NORTH);

            JScrollPane scrollpane = new JScrollPane(textarea);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            p.add(scrollpane, BorderLayout.CENTER);
            p.setMaximumSize(new Dimension(screenSize.width / 2, screenSize.height / 2));
            p.setPreferredSize(new Dimension(screenSize.width / 2, screenSize.height / 2));
            p.setSize(new Dimension(screenSize.width / 2, screenSize.height / 2));

            JOptionPane.showMessageDialog(parent, p, "Fehlerdetails", JOptionPane.ERROR_MESSAGE);

        }
    });
    panel.add(b);

    JOptionPane.showMessageDialog(parent, panel, "Fehler", JOptionPane.ERROR_MESSAGE);
}

From source file:hermes.renderers.DefaultMessageRenderer.java

/**
 * Show the TextMessage in a JTextArea./*from w  w  w. j  a  v a2  s . co m*/
 * 
 * @param textMessage
 * @return
 * @throws JMSException
 */
protected JComponent handleTextMessage(final TextMessage textMessage) throws JMSException {
    //
    // Show the text in a JTextArea, you can edit the message in place and
    // then drop it onto another queue/topic.

    final String text = textMessage.getText();
    final JTextArea textPane = new JTextArea();

    // final CharBuffer bytes = CharBuffer.wrap(text.subSequence(0,
    // text.length())) ;
    // final JTextArea textPane = new MyTextArea(new PlainDocument(new
    // MappedStringContent(bytes))) ;

    textPane.setEditable(false);
    textPane.setFont(Font.decode("Monospaced-PLAIN-12"));
    textPane.setLineWrap(true);
    textPane.setWrapStyleWord(true);

    textPane.append(text);

    textPane.getDocument().addDocumentListener(new DocumentListener() {
        public void doChange() {
            try {
                textMessage.setText(textPane.getText());
            } catch (JMSException e) {
                JOptionPane.showMessageDialog(textPane, "Unable to update the TextMessage: " + e.getMessage(),
                        "Error modifying message content", JOptionPane.ERROR_MESSAGE);

                try {
                    textPane.setText(textMessage.getText());
                } catch (JMSException e1) {
                    log.error(e1.getMessage(), e1);
                }

                textPane.setEditable(false);
                textPane.getDocument().removeDocumentListener(this);
            }
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
            doChange();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            doChange();
        }

        @Override
        public void removeUpdate(DocumentEvent arg0) {
            doChange();
        }
    });

    textPane.setCaretPosition(0);

    return textPane;
}

From source file:com.jamfsoftware.jss.healthcheck.ui.HealthReport.java

/**
 * Creates a new Health Report JPanel window from the Health Check JSON string.
 * Will throw errors if the JSON is not formatted correctly.
 *///ww  w . ja  va2 s  .co m
public HealthReport(final String JSON) throws Exception {
    LOGGER.debug("[DEBUG] - JSON String (Copy entire below line)");
    LOGGER.debug(JSON.replace("\n", ""));
    LOGGER.debug("Attempting to parse Health Report JSON");

    JsonElement report = new JsonParser().parse(JSON);
    JsonObject healthcheck = ((JsonObject) report).get("healthcheck").getAsJsonObject();
    Boolean show_system_info = true;
    JsonObject system = null;
    //Check if the check JSON contains system information and show/hide panels accordingly later.
    system = ((JsonObject) report).get("system").getAsJsonObject();

    final JsonObject data = ((JsonObject) report).get("checkdata").getAsJsonObject();

    this.JSSURL = extractData(healthcheck, "jss_url");

    if (extractData(system, "iscloudjss").contains("true")) {
        show_system_info = false;
        isCloudJSS = true;
    }

    PanelIconGenerator iconGen = new PanelIconGenerator();
    PanelGenerator panelGen = new PanelGenerator();

    //Top Level Frame
    final JFrame frame = new JFrame("JSS Health Check Report");

    //Top Level Content
    JPanel outer = new JPanel(new BorderLayout());

    //Two Blank Panels for the Sides
    JPanel blankLeft = new JPanel();
    blankLeft.add(new JLabel("        "));
    JPanel blankRight = new JPanel();
    blankRight.add(new JLabel("        "));
    blankLeft.setMinimumSize(new Dimension(100, 100));
    blankRight.setMinimumSize(new Dimension(100, 100));
    //Header
    JPanel header = new JPanel();
    header.add(new JLabel("Total Computers: " + extractData(healthcheck, "totalcomputers")));
    header.add(new JLabel("Total Mobile Devices: " + extractData(healthcheck, "totalmobile")));
    header.add(new JLabel("Total Users: " + extractData(healthcheck, "totalusers")));
    int total_devices = Integer.parseInt(extractData(healthcheck, "totalcomputers"))
            + Integer.parseInt(extractData(healthcheck, "totalmobile"));
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
    Date dateobj = new Date();
    header.add(new JLabel("JSS Health Check Report Performed On " + df.format(dateobj)));
    //Foooter
    JPanel footer = new JPanel();
    JButton view_report_json = new JButton("View Report JSON");
    footer.add(view_report_json);
    JButton view_activation_code = new JButton("View Activation Code");
    footer.add(view_activation_code);
    JButton test_again = new JButton("Run Test Again");
    footer.add(test_again);
    JButton view_text_report = new JButton("View Text Report");
    footer.add(view_text_report);
    JButton about_and_terms = new JButton("About and Terms");
    footer.add(about_and_terms);
    //Middle Content, set the background white and give it a border
    JPanel content = new JPanel(new GridLayout(2, 3));
    content.setBackground(Color.WHITE);
    content.setBorder(BorderFactory.createLineBorder(Color.BLACK));

    //Setup Outer Placement
    outer.add(header, BorderLayout.NORTH);
    outer.add(footer, BorderLayout.SOUTH);
    outer.add(blankLeft, BorderLayout.WEST);
    outer.add(blankRight, BorderLayout.EAST);
    outer.add(content, BorderLayout.CENTER);

    //Don't show system info if it is hosted.
    JPanel system_info = null;
    JPanel database_health = null;
    if (show_system_info) {
        //Read all of the System information variables from the JSON and perform number conversions.
        String[][] sys_info = { { "Operating System", extractData(system, "os") },
                { "Java Version", extractData(system, "javaversion") },
                { "Java Vendor", extractData(system, "javavendor") },
                { "Processor Cores", extractData(system, "proc_cores") },
                { "Is Clustered?", extractData(system, "clustering") },
                { "Web App Directory", extractData(system, "webapp_dir") },
                { "Free Memory",
                        Double.toString(
                                round((Double.parseDouble(extractData(system, "free_memory")) / 1000000000), 2))
                                + " GB" },
                { "Max Memory",
                        Double.toString(
                                round((Double.parseDouble(extractData(system, "max_memory")) / 1000000000), 2))
                                + " GB" },
                { "Memory currently in use", Double.toString(round(
                        (Double.parseDouble(extractData(system, "memory_currently_in_use")) / 1000000000), 2))
                        + " GB" },
                { "Total space",
                        Double.toString(
                                round((Double.parseDouble(extractData(system, "total_space")) / 1000000000), 2))
                                + " GB" },
                { "Free Space",
                        Double.toString(round(
                                (Double.parseDouble(extractData(system, "usable_space")) / 1000000000), 2))
                                + " GB" } };
        //Generate the system info panel.
        String systemInfoIcon = iconGen.getSystemInfoIconType(
                Integer.parseInt(extractData(healthcheck, "totalcomputers"))
                        + Integer.parseInt(extractData(healthcheck, "totalmobile")),
                extractData(system, "javaversion"), Double.parseDouble(extractData(system, "max_memory")));
        system_info = panelGen.generateContentPanelSystem("System Info", sys_info, "JSS Minimum Requirements",
                "http://www.jamfsoftware.com/resources/casper-suite-system-requirements/", systemInfoIcon);

        //Get all of the DB information.
        String[][] db_health = { { "Database Size", extractData(system, "database_size") + " MB" } };
        if (extractData(system, "database_size").equals("0")) {
            db_health[0][0] = "Unable to connect to database.";
        }

        String[][] large_sql_tables = extractArrayData(system, "largeSQLtables", "table_name", "table_size");
        String[][] db_health_for_display = ArrayUtils.addAll(db_health, large_sql_tables);
        //Generate the DB Health panel.
        String databaseIconType = iconGen.getDatabaseInfoIconType(total_devices,
                Double.parseDouble(extractData(system, "database_size")),
                extractArrayData(system, "largeSQLtables", "table_name", "table_size").length);
        database_health = panelGen.generateContentPanelSystem("Database Health", db_health_for_display,
                "Too Large SQL Tables", "https://google.com", databaseIconType);
        if (!databaseIconType.equals("green")) {
            this.showLargeDatabase = true;
        }
    }

    int password_strenth = 0;
    if (extractData(data, "password_strength", "uppercase?").contains("true")) {
        password_strenth++;
    }
    if (extractData(data, "password_strength", "lowercase?").contains("true")) {
        password_strenth++;
    }
    if (extractData(data, "password_strength", "number?").contains("true")) {
        password_strenth++;
    }
    if (extractData(data, "password_strength", "spec_chars?").contains("true")) {
        password_strenth++;
    }
    String password_strength_desc = "";
    if (password_strenth == 4) {
        password_strength_desc = "Excellent";
    } else if (password_strenth == 3 || password_strenth == 2) {
        password_strength_desc = "Good";
    } else if (password_strenth == 1) {
        this.strongerPassword = true;
        password_strength_desc = "Poor";
    } else {
        this.strongerPassword = true;
        password_strength_desc = "Needs Updating";
    }

    if (extractData(data, "loginlogouthooks", "is_configured").contains("false")) {
        this.loginInOutHooks = true;
    }

    try {
        if (Integer.parseInt(extractData(data, "device_row_counts", "computers").trim()) != Integer
                .parseInt(extractData(data, "device_row_counts", "computers_denormalized").trim())) {
            this.computerDeviceTableCountMismatch = true;
        }

        if (Integer.parseInt(extractData(data, "device_row_counts", "mobile_devices").trim()) != Integer
                .parseInt(extractData(data, "device_row_counts", "mobile_devices_denormalized").trim())) {
            this.mobileDeviceTableCountMismatch = true;
        }
    } catch (Exception e) {
        System.out.println("Unable to parse device row counts.");
    }

    if ((extractData(system, "mysql_version").contains("5.6.16")
            || extractData(system, "mysql_version").contains("5.6.20"))
            && (extractData(system, "os").contains("OS X") || extractData(system, "os").contains("Mac")
                    || extractData(system, "os").contains("OSX"))) {
        this.mysql_osx_version_bug = true;
    }

    //Get all of the information for the JSS ENV and generate the panel.
    String[][] env_info = {
            { "Checkin Frequency", extractData(data, "computercheckin", "frequency") + " Minutes" },
            { "Log Flushing", extractData(data, "logflushing", "log_flush_time") },
            { "Log In/Out Hooks", extractData(data, "loginlogouthooks", "is_configured") },
            { "Computer EA", extractData(data, "computerextensionattributes", "count") },
            { "Mobile Deivce EA", extractData(data, "mobiledeviceextensionattributes", "count") },
            { "Password Strength", password_strength_desc },
            { "SMTP Server", extractData(data, "smtpserver", "server") },
            { "Sender Email", extractData(data, "smtpserver", "sender_email") },
            { "GSX Connection", extractData(data, "gsxconnection", "status") } };
    String[][] vpp_accounts = extractArrayData(data, "vppaccounts", "name", "days_until_expire");
    String[][] ldap_servers = extractArrayData(data, "ldapservers", "name", "type", "address", "id");
    String envIconType = iconGen.getJSSEnvIconType(Integer.parseInt(extractData(healthcheck, "totalcomputers")),
            Integer.parseInt(extractData(data, "computercheckin", "frequency")),
            Integer.parseInt(extractData(data, "computerextensionattributes", "count")),
            Integer.parseInt(extractData(data, "mobiledeviceextensionattributes", "count")));
    JPanel env = panelGen.generateContentPanelEnv("JSS Environment", env_info, vpp_accounts, ldap_servers, "",
            "", envIconType);

    //Get all of the group information from the JSON, merge the arrays, and then generate the groups JPanel.
    String[][] groups_1 = ArrayUtils.addAll(
            extractArrayData(data, "computergroups", "name", "nested_groups_count", "criteria_count", "id"),
            extractArrayData(data, "mobiledevicegroups", "name", "nested_groups_count", "criteria_count",
                    "id"));
    String[][] groups_2 = ArrayUtils.addAll(groups_1,
            extractArrayData(data, "usergroups", "name", "nested_groups_count", "criteria_count", "id"));
    String groupIconType = iconGen.getGroupIconType("groups", countJSONObjectSize(data, "computergroups")
            + countJSONObjectSize(data, "mobiledevicegroups") + countJSONObjectSize(data, "usergroups"));
    JPanel groups = panelGen.generateContentPanelGroups("Groups", groups_2, "", "", groupIconType);
    if (groupIconType.equals("yellow") || groupIconType.equals("red")) {
        this.showGroupsHelp = true;
    }

    //Get all of the information for the printers, policies and scripts, then generate the panel.
    String[][] printers = extractArrayData(data, "printer_warnings", "model");
    String[][] policies = extractArrayData(data, "policies_with_issues", "name", "ongoing", "checkin_trigger");
    String[][] scripts = extractArrayData(data, "scripts_needing_update", "name");
    String[][] certs = { { "SSL Cert Issuer", extractData(data, "tomcat", "ssl_cert_issuer") },
            { "SLL Cert Expires", extractData(data, "tomcat", "cert_expires") },
            { "MDM Push Cert Expires", extractData(data, "push_cert_expirations", "mdm_push_cert") },
            { "Push Proxy Expires", extractData(data, "push_cert_expirations", "push_proxy") },
            { "Change Management Enabled?", extractData(data, "changemanagment", "isusinglogfile") },
            { "Log File Path:", extractData(data, "changemanagment", "logpath") } };
    String policiesScriptsIconType = iconGen.getPoliciesAndScriptsIconType(
            extractArrayData(data, "policies_with_issues", "name", "ongoing", "checkin_trigger").length,
            extractArrayData(data, "scripts_needing_update", "name").length);
    JPanel policies_scripts = panelGen.generateContentPanelPoliciesScripts(
            "Policies, Scripts, Certs and Change", policies, scripts, printers, certs, "", "",
            policiesScriptsIconType);
    if (extractArrayData(data, "policies_with_issues", "name", "ongoing", "checkin_trigger").length > 0) {
        this.showPolicies = true;
    }
    if (extractArrayData(data, "scripts_needing_update", "name").length > 0) {
        this.showScripts = true;
    }
    if (extractData(data, "changemanagment", "isusinglogfile").contains("false")) {
        this.showChange = true;
    }
    this.showCheckinFreq = iconGen.showCheckinFreq;
    this.showExtensionAttributes = iconGen.showCheckinFreq;
    this.showSystemRequirements = iconGen.showSystemRequirements;
    this.showScalability = iconGen.showScalability;
    //Update Panel Gen Variables
    updatePanelGenVariables(panelGen);

    //Generate the Help Section.
    content.add(panelGen.generateContentPanelHelp("Modifications to Consider", "", "", "blank"));
    //If contains system information, add those panels, otherwise just continue adding the rest of the panels.
    if (show_system_info) {
        content.add(system_info);
        content.add(database_health);
    }
    content.add(env);
    content.add(groups);
    content.add(policies_scripts);

    //View report action listner.
    //Opens a window with the health report JSON listed
    view_report_json.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JPanel middlePanel = new JPanel();
            middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Health Report JSON"));
            // create the middle panel components
            JTextArea display = new JTextArea(16, 58);
            display.setEditable(false);
            //Make a new GSON object so the text can be Pretty Printed.
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String pp_json = gson.toJson(JSON.trim());
            display.append(JSON);
            JScrollPane scroll = new JScrollPane(display);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //Add Textarea in to middle panel
            middlePanel.add(scroll);

            JFrame frame = new JFrame();
            frame.add(middlePanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    //Action listener for the Terms, About and Licence button.
    //Opens a new window with the AS IS License, 3rd Party Libs used and a small about section
    about_and_terms.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JPanel middlePanel = new JPanel();
            middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "About, Licence and Terms"));
            // create the middle panel components
            JTextArea display = new JTextArea(16, 58);
            display.setEditable(false);
            display.append(StringConstants.ABOUT);
            display.append("\n\nThird Party Libraries Used:");
            display.append(
                    " Apache Commons Codec, Google JSON (gson), Java X JSON, JDOM, JSON-Simple, MySQL-connector");
            display.append(StringConstants.LICENSE);
            JScrollPane scroll = new JScrollPane(display);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //Add Textarea in to middle panel
            middlePanel.add(scroll);

            JFrame frame = new JFrame();
            frame.add(middlePanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });

    //Listener for a button click to open a window containing the activation code.
    view_activation_code.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(frame, extractData(data, "activationcode", "code") + "\nExpires: "
                    + extractData(data, "activationcode", "expires"));
        }
    });

    view_text_report.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JPanel middlePanel = new JPanel();
            middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Text Health Report"));
            // create the middle panel components
            JTextArea display = new JTextArea(16, 58);
            display.setEditable(false);
            //Make a new GSON object so the text can be Pretty Printed.
            display.append(new HealthReportHeadless(JSON).getReportString());
            JScrollPane scroll = new JScrollPane(display);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //Add Textarea in to middle panel
            middlePanel.add(scroll);

            JFrame frame = new JFrame();
            frame.add(middlePanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });

    //Listener for the Test Again button. Opens a new UserPrompt object and keeps the Health Report open in the background.
    test_again.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                new UserPrompt();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    });

    frame.add(outer);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);

    DetectVM vm_checker = new DetectVM();
    if (EnvironmentUtil.isMac()) {
        if (vm_checker.getIsVM()) {
            JOptionPane.showMessageDialog(new JFrame(),
                    "The tool has detected that it is running in a OSX Virtual Machine.\nThe opening of links is not supported on OSX VMs.\nPlease open the tool on a non-VM computer and run it again OR\nyou can also copy the JSON from the report to a non-VM OR view the text report.\nIf you are not running a VM, ignore this message.",
                    "VM Detected", JOptionPane.ERROR_MESSAGE);
        }
    }

}

From source file:com.brainflow.application.toplevel.Brainflow.java

private void initExceptionHandler() {
    LookAndFeelFactory.UIDefaultsCustomizer uiDefaultsCustomizer = new LookAndFeelFactory.UIDefaultsCustomizer() {
        public void customize(UIDefaults defaults) {
            ThemePainter painter = (ThemePainter) UIDefaultsLookup.get("Theme.painter");
            defaults.put("OptionPaneUI", "com.jidesoft.plaf.basic.BasicJideOptionPaneUI");

            defaults.put("OptionPane.showBanner", Boolean.TRUE); // show banner or not. default is true
            //defaults.put("OptionPane.bannerIcon", JideIconsFactory.getImageIcon(JideIconsFactory.JIDE50));
            defaults.put("OptionPane.bannerFontSize", 13);
            defaults.put("OptionPane.bannerFontStyle", Font.BOLD);
            defaults.put("OptionPane.bannerMaxCharsPerLine", 60);
            defaults.put("OptionPane.bannerForeground",
                    painter != null ? painter.getOptionPaneBannerForeground() : null); // you should adjust this if banner background is not the default gradient paint
            defaults.put("OptionPane.bannerBorder", null); // use default border

            // set both bannerBackgroundDk and // set both bannerBackgroundLt to null if you don't want gradient
            defaults.put("OptionPane.bannerBackgroundDk",
                    painter != null ? painter.getOptionPaneBannerDk() : null);
            defaults.put("OptionPane.bannerBackgroundLt",
                    painter != null ? painter.getOptionPaneBannerLt() : null);
            defaults.put("OptionPane.bannerBackgroundDirection", Boolean.TRUE); // default is true

            // optionally, you can set a Paint object for BannerPanel. If so, the three UIDefaults related to banner background above will be ignored.
            defaults.put("OptionPane.bannerBackgroundPaint", null);

            defaults.put("OptionPane.buttonAreaBorder", BorderFactory.createEmptyBorder(6, 6, 6, 6));
            defaults.put("OptionPane.buttonOrientation", SwingConstants.RIGHT);
        }//  www .j  a v a  2 s.  c  om
    };
    uiDefaultsCustomizer.customize(UIManager.getDefaults());

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            JideOptionPane optionPane = new JideOptionPane(
                    "Click \"Details\" button to see more information ... ", JOptionPane.ERROR_MESSAGE,
                    JideOptionPane.CLOSE_OPTION);
            optionPane.setTitle("An " + e.getClass().getName() + " occurred in Brainflow : " + e.getMessage());

            JTextArea textArea = new JTextArea();
            StringWriter sw = new StringWriter();
            PrintWriter out = new PrintWriter(sw);
            e.printStackTrace(out);
            // Add string to end of text area
            textArea.append(sw.toString());
            textArea.setRows(10);
            optionPane.setDetails(new JScrollPane(textArea));
            JDialog dialog = optionPane.createDialog(brainFrame, "Warning");
            dialog.setResizable(true);
            dialog.pack();
            dialog.setVisible(true);
        }
    });

}

From source file:edu.smc.mediacommons.panels.SecurityPanel.java

public SecurityPanel() {
    setLayout(null);//  w  w w  .  ja  v  a2s. c  om

    FILE_CHOOSER = new JFileChooser();

    JButton openFile = Utils.createButton("Open File", 10, 20, 100, 30, null);
    add(openFile);

    JButton saveFile = Utils.createButton("Save File", 110, 20, 100, 30, null);
    add(saveFile);

    JButton decrypt = Utils.createButton("Decrypt", 210, 20, 100, 30, null);
    add(decrypt);

    JButton encrypt = Utils.createButton("Encrypt", 310, 20, 100, 30, null);
    add(encrypt);

    JTextField path = Utils.createTextField(10, 30, 300, 20);
    path.setText("No file selected");

    final JTextArea viewer = new JTextArea();
    JScrollPane pastePane = new JScrollPane(viewer);
    pastePane.setBounds(15, 60, 400, 200);
    add(pastePane);

    openFile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (FILE_CHOOSER.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                File toRead = FILE_CHOOSER.getSelectedFile();

                if (toRead == null) {
                    JOptionPane.showMessageDialog(getParent(), "The input file does not exist!",
                            "Opening Failed...", JOptionPane.WARNING_MESSAGE);
                } else {
                    try {
                        List<String> lines = IOUtils.readLines(new FileInputStream(toRead), "UTF-8");

                        viewer.setText("");

                        for (String line : lines) {
                            viewer.append(line);
                        }
                    } catch (IOException ex) {

                    }
                }
            }
        }
    });

    saveFile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (FILE_CHOOSER.showSaveDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                File toWrite = FILE_CHOOSER.getSelectedFile();

                Utils.writeToFile(viewer.getText(), toWrite);
                JOptionPane.showMessageDialog(getParent(),
                        "The file has now been saved to\n" + toWrite.getPath());
            }
        }
    });

    encrypt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String password = Utils.getPasswordInput(getParent());

            if (password != null) {
                try {
                    BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
                    basicTextEncryptor.setPassword(password);

                    String text = basicTextEncryptor.encrypt(viewer.getText());
                    viewer.setText(text);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(getParent(),
                            "Could not encrypt the text, an unexpected error occurred.", "Encryption Failed...",
                            JOptionPane.WARNING_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(getParent(),
                        "Could not encrypt the text, as no\npassword has been specified.",
                        "Encryption Failed...", JOptionPane.WARNING_MESSAGE);
            }
        }
    });

    decrypt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String password = Utils.getPasswordInput(getParent());

            if (password != null) {
                try {
                    BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
                    basicTextEncryptor.setPassword(password);

                    String text = basicTextEncryptor.decrypt(viewer.getText());
                    viewer.setText(text);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(getParent(),
                            "Could not decrypt the text, an unexpected error occurred.", "Decryption Failed...",
                            JOptionPane.WARNING_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(getParent(),
                        "Could not decrypt the text, as no\npassword has been specified.",
                        "Decryption Failed...", JOptionPane.WARNING_MESSAGE);
            }
        }
    });
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopTextArea.java

@Override
protected JTextArea createTextComponentImpl() {
    final JTextArea impl = new TextAreaFlushableField();

    if (isTabTraversal()) {
        Set<KeyStroke> forwardFocusKey = Collections.singleton(getKeyStroke(KeyEvent.VK_TAB, 0));
        impl.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardFocusKey);

        Set<KeyStroke> backwardFocusKey = Collections
                .singleton(getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK));
        impl.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardFocusKey);

        impl.addKeyListener(new KeyAdapter() {
            @Override/*from  ww w. j  av  a 2  s  .  co m*/
            public void keyPressed(KeyEvent e) {
                if (isEnabled() && isEditable() && e.getKeyCode() == KeyEvent.VK_TAB
                        && e.getModifiers() == KeyEvent.CTRL_MASK) {

                    if (StringUtils.isEmpty(impl.getText())) {
                        impl.setText("\t");
                    } else {
                        impl.append("\t");
                    }
                }
            }
        });
    }

    impl.setLineWrap(true);
    impl.setWrapStyleWord(true);

    int height = (int) impl.getPreferredSize().getHeight();
    impl.setMinimumSize(new Dimension(0, height));

    composition = new JScrollPane(impl);
    composition.setPreferredSize(new Dimension(150, height));
    composition.setMinimumSize(new Dimension(0, height));

    doc.putProperty("filterNewlines", false);

    return impl;
}

From source file:jcan2.SimpleSerial.java

public int importDataFromDevice(JProgressBar progressBar, JTextArea status)
        throws InterruptedException, JSONException {
    if ("Error - no Port found".equals(serialPortName))
        return -1;
    else {// w  ww  . ja v  a  2s  .co  m
        SerialPort serialPort = new SerialPort(serialPortName);

        try {
            serialPort.openPort();//Open serial port
            serialPort.setParams(SerialPort.BAUDRATE_115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

            serialPort.writeBytes("$ORUSR*11\n".getBytes());//Write data to port
            Thread.sleep(WAIT_MS);
            String userString = serialPort.readString();
            int usr = decodeUserID(userString);
            if (usr > 0) {
                BeMapEditor.mainWindow.setUsr(usr);
                status.append("\nUser ID: " + usr);
            } else if (usr == -1) {
                //code for getting usr id from server
                //$ORUSR,25*11\n
                status.append("\nError: Getting user ID from server not yet supported!");
                BeMapEditor.mainWindow.setUsr(-1);
            } else {
                status.append("\nError: No User ID found! Import aborted.");
                return -1;
            }

            serialPort.writeBytes("$ORNUM*11\n".getBytes());
            Thread.sleep(WAIT_MS);
            String numberString = serialPort.readString();
            int totalNumber = decodeNbPoints(numberString);
            if (totalNumber > 0)
                status.append("\nNumber of points to import: " + totalNumber);
            else if (totalNumber == 0) {
                status.append("\nNo points stored to import! ");
                return 0;
            } else {
                status.append("\nError: Number of Points");
                return -1;
            }

            //prepare track to import
            BeMapEditor.trackOrganiser.createNewTrack("Import");

            int nbRequests = (totalNumber / (MAX_DATA_PER_IMPORT)) + 1;
            int rest = totalNumber - (nbRequests - 1) * MAX_DATA_PER_IMPORT; //nb of points for the last request
            if (SERIAL_DEBUG)
                BeMapEditor.mainWindow.append("\nNumber of requests necessary: " + nbRequests);
            if (SERIAL_DEBUG)
                BeMapEditor.mainWindow.append("\nPoints resting for last request: " + rest);

            //init progress bar
            progressBar.setMaximum(nbRequests);

            for (int i = 0; i < (nbRequests - 1); i++) {
                //import serie of points
                int offset = i * MAX_DATA_PER_IMPORT;
                if (importSerieOfPoints(serialPort, MAX_DATA_PER_IMPORT, offset) < 0)
                    return 0;
                //actualize progress bar
                progressBar.setValue(i + 1);
            }
            int final_offset = (nbRequests - 1) * MAX_DATA_PER_IMPORT;
            if (importSerieOfPoints(serialPort, rest, final_offset) < 0)
                return 0; //import the rest of the points
            progressBar.setValue(nbRequests);

            status.append("\n" + totalNumber + " Points successfully imported");

            serialPort.writeString("$ORMEM*11\n");
            Thread.sleep(WAIT_MS);
            decodeMemoryState(serialPort.readString());

            serialPort.closePort();//Close serial port

            BeMapEditor.trackOrganiser.postImportTreatment(progressBar);
            return 1;
        } catch (SerialPortException ex) {
            return 0;//do not print error
        }
    }

}

From source file:bemap.SimpleSerial.java

public int importDataFromDevice(JProgressBar progressBar, JTextArea status)
        throws InterruptedException, JSONException {
    if ("Error - no Port found".equals(serialPortName))
        return -1;
    else {/*w w w.  j  ava 2s.c om*/
        SerialPort serialPort = new SerialPort(serialPortName);

        try {
            serialPort.openPort();//Open serial port
            serialPort.setParams(SerialPort.BAUDRATE_115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

            serialPort.writeBytes("$ORUSR*11\n".getBytes());//Write data to port
            Thread.sleep(WAIT_MS);
            String userString = serialPort.readString();
            int usr = decodeUserID(userString);
            if (usr > 0) {
                BeMapEditor.mainWindow.setUsr(usr);
                status.append("\nUser ID: " + usr);
            } else if (usr == -1) {
                //code for getting usr id from server
                //$ORUSR,25*11\n
                status.append("\nError: No user ID set!");
                BeMapEditor.mainWindow.setUsr(-1);
            } else {
                status.append("\nError: No User ID found! Import aborted.");
                return -1;
            }

            //import settings
            serialPort.writeBytes("$ORCFG*11\n".getBytes());//Write data to port
            Thread.sleep(WAIT_MS);
            String configString = serialPort.readString();
            if (decodeSettings(configString) == 1 && SERIAL_DEBUG) {
                BeMapEditor.mainWindow.append("\nSettings decoded");
            } else
                BeMapEditor.mainWindow.append("\nError decoding settings");

            //Start importing points
            serialPort.writeBytes("$ORNUM*11\n".getBytes());
            Thread.sleep(WAIT_MS);
            String numberString = serialPort.readString();
            int totalNumber = decodeNbPoints(numberString);
            if (totalNumber > 0)
                status.append("\nNumber of points to import: " + totalNumber);
            else if (totalNumber == 0) {
                status.append("\nNo points stored to import! ");
                return 0;
            } else {
                status.append("\nError: Number of Points");
                return -1;
            }

            //prepare track to import
            BeMapEditor.trackOrganiser.createNewTrack("Import");

            int nbRequests = (totalNumber / (MAX_DATA_PER_IMPORT)) + 1;
            int rest = totalNumber - (nbRequests - 1) * MAX_DATA_PER_IMPORT; //nb of points for the last request
            if (SERIAL_DEBUG)
                BeMapEditor.mainWindow.append("\nNumber of requests necessary: " + nbRequests);
            if (SERIAL_DEBUG)
                BeMapEditor.mainWindow.append("\nPoints resting for last request: " + rest);

            //init progress bar
            progressBar.setMaximum(nbRequests);

            for (int i = 0; i < (nbRequests - 1); i++) {
                //import serie of points
                int offset = i * MAX_DATA_PER_IMPORT;
                if (importSerieOfPoints(serialPort, MAX_DATA_PER_IMPORT, offset) < 0)
                    return 0;
                //actualize progress bar
                progressBar.setValue(i + 1);
            }
            int final_offset = (nbRequests - 1) * MAX_DATA_PER_IMPORT;
            if (importSerieOfPoints(serialPort, rest, final_offset) < 0)
                return 0; //import the rest of the points
            progressBar.setValue(nbRequests);

            status.append("\n" + totalNumber + " Points successfully imported");

            serialPort.writeString("$ORMEM*11\n");
            Thread.sleep(WAIT_MS);
            decodeMemoryState(serialPort.readString());

            serialPort.closePort();//Close serial port

            BeMapEditor.trackOrganiser.postImportTreatment(progressBar);
            return 1;
        } catch (SerialPortException ex) {
            return 0;//do not print error
        }
    }

}