Example usage for javax.swing JTextArea setColumns

List of usage examples for javax.swing JTextArea setColumns

Introduction

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

Prototype

@BeanProperty(bound = false, description = "the number of columns preferred for display")
public void setColumns(int columns) 

Source Link

Document

Sets the number of columns for this TextArea.

Usage

From source file:Main.java

public static void main(String[] args) {
    String text = "one two three four five six seven eight nine ten ";
    JTextArea textArea = new JTextArea(text);
    textArea.setColumns(30);
    textArea.setLineWrap(true);// w w w.  j  a  v a 2s . co m
    textArea.setWrapStyleWord(true);
    textArea.append(text);
    textArea.append(text);
    textArea.append(text);
    textArea.append(text);
    textArea.append(text);
    textArea.setSize(textArea.getPreferredSize().width, 1);
    JOptionPane.showMessageDialog(null, new JScrollPane(textArea), "Not Truncated!",
            JOptionPane.WARNING_MESSAGE);
}

From source file:com.edduarte.protbox.Protbox.java

public static void main(String... args) {

    // activate debug / verbose mode
    if (args.length != 0) {
        List<String> argsList = Arrays.asList(args);
        if (argsList.contains("-v")) {
            Constants.verbose = true;/*  w w  w .ja v  a 2s.  c  om*/
        }
    }

    // use System's look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        // If the System's look and feel is not obtainable, continue execution with JRE look and feel
    }

    // check this is a single instance
    try {
        new ServerSocket(1882);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Another instance of Protbox is already running.\n" + "Please close the other instance first.",
                "Protbox already running", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // check if System Tray is supported by this operative system
    if (!SystemTray.isSupported()) {
        JOptionPane.showMessageDialog(null,
                "Your operative system does not support system tray functionality.\n"
                        + "Please try running Protbox on another operative system.",
                "System tray not supported", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // add PKCS11 providers
    FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")),
            HiddenFileFilter.VISIBLE);

    File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter);

    if (providersConfigFiles != null) {
        for (File f : providersConfigFiles) {
            try {
                List<String> lines = FileUtils.readLines(f);
                String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get();
                lines.remove(aliasLine);
                String alias = aliasLine.split("=")[1].trim();

                StringBuilder sb = new StringBuilder();
                for (String s : lines) {
                    sb.append(s);
                    sb.append("\n");
                }

                Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString())));
                Security.addProvider(p);

                pkcs11Providers.put(p.getName(), alias);

            } catch (IOException | ProviderException ex) {
                if (ex.getMessage().equals("Initialization failed")) {
                    ex.printStackTrace();

                    String s = "The following error occurred:\n" + ex.getCause().getMessage()
                            + "\n\nIn addition, make sure you have "
                            + "an available smart card reader connected before opening the application.";
                    JTextArea textArea = new JTextArea(s);
                    textArea.setColumns(60);
                    textArea.setLineWrap(true);
                    textArea.setWrapStyleWord(true);
                    textArea.setSize(textArea.getPreferredSize().width, 1);

                    JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider",
                            JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Error while setting up PKCS11 provider from configuration file " + f.getName()
                                    + ".\n" + ex.getMessage(),
                            "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // adds a shutdown hook to save instantiated directories into files when the application is being closed
    Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit));

    // get system tray and run tray applet
    tray = SystemTray.getSystemTray();
    SwingUtilities.invokeLater(() -> {

        if (Constants.verbose) {
            logger.info("Starting application");
        }

        //Start a new TrayApplet object
        trayApplet = TrayApplet.getInstance();
    });

    // prompts the user to choose which provider to use
    ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> {

        // loads eID token
        eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> {
            user = returnedUser;
            certificateData = returnedCertificateData;

            // gets a password to use on the saved registry files (for loading and saving)
            final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null);
            consumerHolder.set(password -> {
                registriesPasswordKey = password;
                try {
                    // if there are serialized files, load them if they can be decoded by this user's private key
                    final List<SavedRegistry> serializedDirectories = new ArrayList<>();
                    if (Constants.verbose) {
                        logger.info("Reading serialized registry files...");
                    }

                    File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles();
                    if (registryFileList != null) {
                        for (File f : registryFileList) {
                            if (f.isFile()) {
                                byte[] data = FileUtils.readFileToByteArray(f);
                                try {
                                    Cipher cipher = Cipher.getInstance("AES");
                                    cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey);
                                    byte[] registryDecryptedData = cipher.doFinal(data);
                                    serializedDirectories.add(new SavedRegistry(f, registryDecryptedData));
                                } catch (GeneralSecurityException ex) {
                                    if (Constants.verbose) {
                                        logger.info("Inserted Password does not correspond to " + f.getName());
                                    }
                                }
                            }
                        }
                    }

                    // if there were no serialized directories, show NewDirectory window to configure the first folder
                    if (serializedDirectories.isEmpty() || registryFileList == null) {
                        if (Constants.verbose) {
                            logger.info("No registry files were found: running app as first time!");
                        }
                        NewRegistryWindow.start(true);

                    } else { // there were serialized directories
                        loadRegistry(serializedDirectories);
                        trayApplet.repaint();
                        showTrayApplet();
                    }

                } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException
                        | ProtboxException ex) {

                    JOptionPane.showMessageDialog(null,
                            "The inserted password was invalid! Please try another one!", "Invalid password!",
                            JOptionPane.ERROR_MESSAGE);
                    insertPassword(consumerHolder.get());
                }
            });
            insertPassword(consumerHolder.get());
        });
    });
}

From source file:au.org.ala.delta.ui.MessageDialogHelper.java

/**
 * Creates a text area that looks like a JLabel that has a preferredSize calculated to fit
 * all of the supplied text wrapped at the supplied column. 
 * @param text the text to display in the JTextArea.
 * @param numColumns the column number to wrap text at.
 * @return a new JTextArea configured for the supplied text.
 *///from  ww w .j a va2  s. co m
private static JTextArea createMessageDisplay(String text, int numColumns) {
    JTextArea textArea = new JTextArea();
    textArea.setEditable(false);

    textArea.setBackground(UIManager.getColor("Label.background"));
    textArea.setFont(UIManager.getFont("Label.font"));

    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    textArea.setColumns(numColumns);

    String wrapped = WordUtils.wrap(text, numColumns);
    textArea.setRows(wrapped.split("\n").length - 1);

    textArea.setText(text);

    // Need to set a preferred size so that under OpenJDK-6 on Linux the JOptionPanes get reasonable bounds 
    textArea.setPreferredSize(new Dimension(0, 0));

    return textArea;

}

From source file:com.smart.aqimonitor.client.AqiMonitor.java

/**
 * Create the frame./*from   w w  w  .ja  v a 2 s  . co m*/
 */
public AqiMonitor() {
    refSelf = this;
    setPreferredSize(new Dimension(640, 480));
    setTitle("\u7A7A\u6C14\u8D28\u91CF\u76D1\u6D4B");
    setIconImage(Toolkit.getDefaultToolkit()
            .getImage(AqiMonitor.class.getResource("/lombok/installer/eclipse/STS.png")));
    setMinimumSize(new Dimension(640, 480));
    setMaximumSize(new Dimension(1024, 768));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 636, 412);
    contentPane = new JPanel();
    contentPane.setPreferredSize(new Dimension(640, 480));
    contentPane.setMinimumSize(new Dimension(640, 480));
    contentPane.setMaximumSize(new Dimension(1024, 768));
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    JPanel mainPanel = new JPanel();
    contentPane.add(mainPanel, BorderLayout.CENTER);
    mainPanel.setLayout(new BorderLayout(0, 0));

    JPanel contentPanel = new JPanel();
    mainPanel.add(contentPanel, BorderLayout.CENTER);
    contentPanel.setLayout(new BorderLayout(0, 0));

    JScrollPane scrollPane = new JScrollPane();
    scrollPane
            .setViewportBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    contentPanel.add(scrollPane, BorderLayout.CENTER);

    textPane = new AqiTextPane();
    textPane.addInputMethodListener(new InputMethodListener() {

        public void caretPositionChanged(InputMethodEvent event) {

        }

        public void inputMethodTextChanged(InputMethodEvent event) {
            textPane.setCaretPosition(document.getLength() + 1);
        }
    });
    textPane.setEditable(false);
    textPane.setOpaque(false);
    textPane.setForeground(Color.BLACK);
    scrollPane.setViewportView(textPane);
    document = textPane.getStyledDocument();

    document.addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            if (e.getDocument() == document) {
                textPane.setCaretPosition(document.getLength());
            }
        }
    });

    JPanel buttonPanel = new JPanel();
    contentPane.add(buttonPanel, BorderLayout.SOUTH);
    buttonPanel.setLayout(new BorderLayout(0, 0));

    JLabel lblTipsLabel = new JLabel(
            "Tips\uFF1A\u6587\u4EF6\u4FDD\u5B58\u683C\u5F0Fcsv\u53EF\u7528Excel\u6253\u5F00");
    lblTipsLabel.setForeground(Color.BLUE);
    buttonPanel.add(lblTipsLabel, BorderLayout.WEST);

    JPanel panel = new JPanel();
    buttonPanel.add(panel, BorderLayout.CENTER);
    panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

    JButton btnRetrieve = new JButton("\u624B\u52A8\u83B7\u53D6\u6570\u636E");
    panel.add(btnRetrieve);
    btnRetrieve.setVerticalAlignment(SwingConstants.BOTTOM);

    JButton btnNewButton = new JButton("\u5173\u4E8E");
    btnNewButton.setToolTipText("\u5173\u4E8E");
    btnNewButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JTextArea textArea = new JTextArea(
                    "\n        csv\n\n        smartstudio@foxmail.com");
            textArea.setColumns(35);
            textArea.setRows(6);
            textArea.setLineWrap(true);// 
            textArea.setEditable(false);// 
            textArea.setOpaque(false);
            JOptionPane.showMessageDialog(contentPane, textArea, "", JOptionPane.PLAIN_MESSAGE);
        }
    });

    JButton btnSetting = new JButton("\u8BBE\u7F6E");
    btnSetting.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            Point parentPos = refSelf.getLocation();

            AqiSettingDialog settingDialog = new AqiSettingDialog(refSelf, pm25InDetailJob.getAqiParser());
            settingDialog.setModal(true);
            settingDialog.setLocation(parentPos.x + 100, parentPos.y + 150);
            settingDialog.init();
            settingDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            settingDialog.setVisible(true);
        }
    });

    JButton btnExportDir = new JButton("\u67E5\u770B\u6570\u636E");
    btnExportDir.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {

                String[] cmd = new String[5];

                String filePath = pm25InDetailJob.getAqiParser().getFilePath();
                File file = new File(filePath);
                if (!file.exists()) {
                    FileUtil.makeDir(file);
                }
                if (!file.isDirectory()) {
                    JOptionPane.showMessageDialog(contentPane, "", "",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                cmd[0] = "cmd";
                cmd[1] = "/c";
                cmd[2] = "start";
                cmd[3] = " ";
                cmd[4] = pm25InDetailJob.getAqiParser().getFilePath();

                Runtime.getRuntime().exec(cmd);

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
    panel.add(btnExportDir);
    panel.add(btnSetting);
    panel.add(btnNewButton);
    btnRetrieve.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (!isRetrieving) {
                isRetrieving = true;
                Thread firstRun = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        pm25InDetailJob.refresh();
                        isRetrieving = false;
                    }
                });

                firstRun.start();
            }
        }
    });

    init();
}

From source file:com.eviware.soapui.support.components.SimpleForm.java

public JTextArea appendTextArea(String label, String tooltip) {
    JTextArea textArea = new JUndoableTextArea();
    textArea.setColumns(defaultTextAreaColumns);
    textArea.setRows(defaultTextAreaRows);
    textArea.setAutoscrolls(true);//from   ww  w.  j  a  v  a2  s . c o m
    textArea.add(new JScrollPane());
    setToolTip(textArea, tooltip);
    textArea.getAccessibleContext().setAccessibleDescription(tooltip);
    JTextComponentPopupMenu.add(textArea);
    append(label, new JScrollPane(textArea));
    return textArea;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java

/**
* Takes the list of data import errors and displays then to the user
* 
* void/*from  w ww  .jav  a  2  s.c o m*/
*/
protected void showErrors() {
    JList listOfErrors = genListOfErrorWhereTableDataDefiesSizeConstraints(model.getColumnNames(),
            model.getData());

    if ((model.getColumnNames() == null) || (model.getData() == null) || (listOfErrors == null)
            || (listOfErrors.getModel().getSize() == 0)) {
        JTextArea textArea = new JTextArea();
        textArea.setRows(25);
        textArea.setColumns(60);
        //String newline = "\n";
        //for (int i = 0; i < listOfErrors.getModel().getSize(); i++)
        //{
        textArea.append(getResourceString("WB_PARSE_FILE_ERROR2"));
        //}
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(false);
        textArea.setCaretPosition(0);
        JScrollPane pane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), pane, getResourceString("DATA_IMPORT_ISSUES"),
                JOptionPane.WARNING_MESSAGE);
        okBtn.setEnabled(false);
    } else if (listOfErrors.getModel().getSize() > 0) {
        JTextArea textArea = new JTextArea();
        textArea.setRows(25);
        textArea.setColumns(60);
        String newline = "\n";
        for (int i = 0; i < listOfErrors.getModel().getSize(); i++) {
            textArea.append((String) listOfErrors.getModel().getElementAt(i) + newline + newline);
        }
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(false);
        textArea.setCaretPosition(0);
        JScrollPane pane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), pane, getResourceString("DATA_IMPORT_ISSUES"),
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:org.ecoinformatics.seek.datasource.eml.eml2.Eml200DataSource.java

public void preview() {

    String displayText = "PREVIEW NOT IMPLEMENTED FOR THIS ACTOR";
    JFrame frame = new JFrame(this.getName() + " Preview");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JScrollPane scrollPane = null;
    JTable jtable = null;//ww w  .  jav a 2s .c o m

    try {

        // set everything up (datawise)
        this.initialize();

        // check the entity - different displays for different formats
        // Compressed file
        if (this._selectedTableEntity.getHasGZipDataFile() || this._selectedTableEntity.getHasTarDataFile()
                || this._selectedTableEntity.getHasZipDataFile()) {
            displayText = "Selected entity is a compressed file.  \n"
                    + "Preview not implemented for output format: " + this.dataOutputFormat.getExpression();
            if (this._dataOutputFormat instanceof Eml200DataOutputFormatUnzippedFileName) {
                Eml200DataOutputFormatUnzippedFileName temp = (Eml200DataOutputFormatUnzippedFileName) this._dataOutputFormat;
                displayText = "Files: \n";
                for (int i = 0; i < temp.getTargetFilePathInZip().length; i++) {
                    displayText += temp.getTargetFilePathInZip()[i] + "\n";
                }
            }

        }
        // SPATIALRASTERENTITY or SPATIALVECTORENTITY are "image entities"
        // as far as the parser is concerned
        else if (this._selectedTableEntity.getIsImageEntity()) {
            // use the content of the cache file
            displayText = new String(this.getSelectedCachedDataItem().getData());
        }
        // TABLEENTITY
        else {
            // holds the rows for the table on disk with some in memory
            String vectorTempDir = DotKeplerManager.getInstance().getCacheDirString();
            // + "vector"
            // + File.separator;
            PersistentVector rowData = new PersistentVector(vectorTempDir);

            // go through the rows and add them to the persistent vector
            // model
            Vector row = this.gotRowVectorFromSource();
            while (!row.isEmpty()) {
                rowData.addElement(row);
                row = this.gotRowVectorFromSource();
            }
            // the column headers for the table
            Vector columns = this.getColumns();

            /*
             * with java 6, there is a more built-in sorting mechanism that
             * does not require the custom table sorter class
             */
            TableModel tableModel = new PersistentTableModel(rowData, columns);
            TableSorter tableSorter = new TableSorter(tableModel);
            jtable = new JTable(tableSorter) {
                // make this table read-only by overriding the default
                // implementation
                public boolean isCellEditable(int row, int col) {
                    return false;
                }
            };
            // sets up the listeners for sorting and such
            tableSorter.setTableHeader(jtable.getTableHeader());
            // set up the listener to trash persisted data when done
            frame.addWindowListener(new PersistentTableModelWindowListener((PersistentTableModel) tableModel));
        }
    } catch (Exception e) {
        displayText = "Problem encountered while generating preview: \n" + e.getMessage();
        log.error(displayText);
        e.printStackTrace();
    }

    // make sure there is a jtable, otherwise show just a text version of
    // the data
    if (jtable != null) {
        jtable.setVisible(true);
        // jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        scrollPane = new JScrollPane(jtable);
    } else {
        JTextArea textArea = new JTextArea();
        textArea.setColumns(80);
        textArea.setText(displayText);
        textArea.setVisible(true);
        scrollPane = new JScrollPane(textArea);
    }
    scrollPane.setVisible(true);
    panel.setOpaque(true);
    panel.add(scrollPane, BorderLayout.CENTER);
    frame.setContentPane(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

From source file:org.springframework.richclient.factory.DefaultComponentFactory.java

public JTextArea createTextArea(int rows, int columns) {
    JTextArea textArea = createTextArea();
    textArea.setRows(rows);// w ww  .java 2s . c o  m
    textArea.setColumns(columns);
    return textArea;
}