Example usage for javax.swing JTextArea getPreferredSize

List of usage examples for javax.swing JTextArea getPreferredSize

Introduction

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

Prototype

public Dimension getPreferredSize() 

Source Link

Document

Returns the preferred size of the 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);/*from  w w  w  .  jav  a 2s. c o m*/
    textArea.setLineWrap(true);
    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;//from  w w w.ja va 2s.  c  o m
        }
    }

    // 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:CubaHSQLDBServer.java

private void setTextPreserveSize(JTextArea target, String text) {
    Dimension size = target.getPreferredSize();
    target.setText(text);// www  .java2s .c  o  m
    target.setPreferredSize(size);
}

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//w  ww.jav  a  2s.  c  o 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:uk.ac.ebi.demo.picr.swing.PICRBLASTDemo.java

public PICRBLASTDemo() {

    //set general layout
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

    add(Box.createVerticalStrut(5));

    //create components
    JPanel row1 = new JPanel();
    row1.setLayout(new BoxLayout(row1, BoxLayout.X_AXIS));
    row1.add(Box.createHorizontalStrut(5));
    row1.setBorder(BorderFactory.createTitledBorder(""));
    row1.add(new JLabel("Fragment:"));
    row1.add(Box.createHorizontalStrut(10));
    final JTextArea sequenceArea = new JTextArea(5, 40);
    sequenceArea.setMaximumSize(sequenceArea.getPreferredSize());
    row1.add(Box.createHorizontalStrut(10));

    row1.add(sequenceArea);//  w  w  w . j  a v  a 2s.  c  o m
    row1.add(Box.createHorizontalGlue());

    JPanel row2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
    row2.setBorder(BorderFactory.createTitledBorder("Target Databases"));
    final JList databaseList = new JList();
    JScrollPane listScroller = new JScrollPane(databaseList);
    listScroller.setMaximumSize(new Dimension(100, 10));
    JButton loadDBButton = new JButton("Load Databases");
    row2.add(listScroller);
    row2.add(loadDBButton);

    JPanel row3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
    JCheckBox onlyActiveCheckBox = new JCheckBox("Only Active");
    onlyActiveCheckBox.setSelected(true);
    row3.add(new JLabel("Options:  "));
    row3.add(onlyActiveCheckBox);

    add(row1);
    add(row2);
    add(row3);

    final String[] columns = new String[] { "Database", "Accession", "Version", "Taxon ID" };
    final JTable dataTable = new JTable(new Object[0][0], columns);
    dataTable.setShowGrid(true);
    add(new JScrollPane(dataTable));

    JPanel buttonPanel = new JPanel();
    JButton mapAccessionButton = new JButton("Generate Mapping!");
    buttonPanel.add(mapAccessionButton);
    add(buttonPanel);

    //create listeners!

    //update boolean flag in communication class
    onlyActiveCheckBox.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            client.setOnlyActive(((JCheckBox) e.getSource()).isSelected());
        }
    });

    //performs mapping call and updates interface with results
    mapAccessionButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            try {

                if (!"".equals(sequenceArea.getText())) {
                    //TODO filters and database are hardcoded here.  They should be added to the input panel at a later revision.
                    java.util.List<UPEntry> entries = client.performBlastMapping(sequenceArea.getText(),
                            databaseList.getSelectedValues(), "90", "", "IDENTITY", "UniprotKB", "", false,
                            new BlastParameter());

                    //compute size of array
                    if (entries != null) {
                        int size = 0;
                        for (UPEntry entry : entries) {
                            for (CrossReference xref : entry.getIdenticalCrossReferences()) {
                                size++;
                            }
                            for (CrossReference xref : entry.getLogicalCrossReferences()) {
                                size++;
                            }
                        }

                        if (size > 0) {

                            final Object[][] data = new Object[size][4];
                            int i = 0;
                            for (UPEntry entry : entries) {
                                for (CrossReference xref : entry.getIdenticalCrossReferences()) {
                                    data[i][0] = xref.getDatabaseName();
                                    data[i][1] = xref.getAccession();
                                    data[i][2] = xref.getAccessionVersion();
                                    data[i][3] = xref.getTaxonId();
                                    i++;
                                }
                                for (CrossReference xref : entry.getLogicalCrossReferences()) {
                                    data[i][0] = xref.getDatabaseName();
                                    data[i][1] = xref.getAccession();
                                    data[i][2] = xref.getAccessionVersion();
                                    data[i][3] = xref.getTaxonId();
                                    i++;
                                }
                            }

                            //refresh
                            DefaultTableModel dataModel = new DefaultTableModel();
                            dataModel.setDataVector(data, columns);
                            dataTable.setModel(dataModel);

                            System.out.println("update done");

                        } else {
                            JOptionPane.showMessageDialog(null, "No Mappind data found.");
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "No Mappind data found.");
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "You must enter a valid FASTA sequence to map.");
                }
            } catch (SOAPFaultException soapEx) {
                JOptionPane.showMessageDialog(null, "A SOAP Error occurred.");
                soapEx.printStackTrace();
            }
        }
    });

    //loads list of mapping databases from communication class
    loadDBButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            try {

                java.util.List<String> databases = client.loadDatabases();
                if (databases != null && databases.size() > 0) {

                    databaseList.setListData(databases.toArray());
                    System.out.println("database refresh done");

                } else {
                    JOptionPane.showMessageDialog(null, "No Databases Loaded!.");
                }

            } catch (SOAPFaultException soapEx) {
                JOptionPane.showMessageDialog(null, "A SOAP Error occurred.");
                soapEx.printStackTrace();
            }
        }
    });

}