Example usage for javax.swing JTextField JTextField

List of usage examples for javax.swing JTextField JTextField

Introduction

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

Prototype

public JTextField(int columns) 

Source Link

Document

Constructs a new empty TextField with the specified number of columns.

Usage

From source file:FocusTraversalDemo.java

public FocusTraversalDemo() {
    super(new BorderLayout());

    JTextField tf1 = new JTextField("Field 1");
    JTextField tf2 = new JTextField("A Bigger Field 2");
    JTextField tf3 = new JTextField("Field 3");
    JTextField tf4 = new JTextField("A Bigger Field 4");
    JTextField tf5 = new JTextField("Field 5");
    JTextField tf6 = new JTextField("A Bigger Field 6");
    JTable table = new JTable(4, 3);
    togglePolicy = new JCheckBox("Custom FocusTraversalPolicy");
    togglePolicy.setActionCommand("toggle");
    togglePolicy.addActionListener(this);
    togglePolicy.setFocusable(false); // Remove it from the focus cycle.
    // Note that HTML is allowed and will break this run of text
    // across two lines.
    label = new JLabel(
            "<html>Use Tab (or Shift-Tab) to navigate from component to component.Control-Tab (or Control-Shift-Tab) allows you to break out of the JTable.</html>");

    JPanel leftTextPanel = new JPanel(new GridLayout(3, 2));
    leftTextPanel.add(tf1, BorderLayout.PAGE_START);
    leftTextPanel.add(tf3, BorderLayout.CENTER);
    leftTextPanel.add(tf5, BorderLayout.PAGE_END);
    leftTextPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));
    JPanel rightTextPanel = new JPanel(new GridLayout(3, 2));
    rightTextPanel.add(tf2, BorderLayout.PAGE_START);
    rightTextPanel.add(tf4, BorderLayout.CENTER);
    rightTextPanel.add(tf6, BorderLayout.PAGE_END);
    rightTextPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));
    JPanel tablePanel = new JPanel(new GridLayout(0, 1));
    tablePanel.add(table, BorderLayout.CENTER);
    tablePanel.setBorder(BorderFactory.createEtchedBorder());
    JPanel bottomPanel = new JPanel(new GridLayout(2, 1));
    bottomPanel.add(togglePolicy, BorderLayout.PAGE_START);
    bottomPanel.add(label, BorderLayout.PAGE_END);

    add(leftTextPanel, BorderLayout.LINE_START);
    add(rightTextPanel, BorderLayout.CENTER);
    add(tablePanel, BorderLayout.LINE_END);
    add(bottomPanel, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    Vector<Component> order = new Vector<Component>(7);
    order.add(tf1);/*from  w ww.j a  v  a 2  s.  com*/
    order.add(tf2);
    order.add(tf3);
    order.add(tf4);
    order.add(tf5);
    order.add(tf6);
    order.add(table);
    newPolicy = new MyOwnFocusTraversalPolicy(order);
}

From source file:RSAccounts.java

private void buildGUI() {
    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    accountNumberList = new JList();
    loadAccounts();//from  ww w .jav a  2  s  .c  o m
    accountNumberList.setVisibleRowCount(2);
    JScrollPane accountNumberListScrollPane = new JScrollPane(accountNumberList);

    gotoText = new JTextField(3);
    freeQueryText = new JTextField(40);

    //Do Get Account Button
    getAccountButton = new JButton("Get Account");
    getAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                rs.first();
                while (rs.next()) {
                    if (rs.getString("acc_id").equals(accountNumberList.getSelectedValue()))
                        break;
                }
                if (!rs.isAfterLast()) {
                    accountIDText.setText(rs.getString("acc_id"));
                    usernameText.setText(rs.getString("username"));
                    passwordText.setText(rs.getString("password"));
                    tsText.setText(rs.getString("ts"));
                    activeTSText.setText(rs.getString("act_ts"));
                }
            } catch (SQLException selectException) {
                displaySQLErrors(selectException);
            }
        }
    });

    //Do Insert Account Button
    insertAccountButton = new JButton("Insert Account");
    insertAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Statement statement = connection.createStatement();
                int i = statement.executeUpdate("INSERT INTO acc_acc VALUES(" + accountIDText.getText() + ", "
                        + "'" + usernameText.getText() + "', " + "'" + passwordText.getText() + "', " + "0"
                        + ", " + "now())");
                errorText.append("Inserted " + i + " rows successfully");
                accountNumberList.removeAll();
                loadAccounts();
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    //Do Delete Account Button
    deleteAccountButton = new JButton("Delete Account");
    deleteAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Statement statement = connection.createStatement();
                int i = statement.executeUpdate(
                        "DELETE FROM acc_acc WHERE acc_id = " + accountNumberList.getSelectedValue());
                errorText.append("Deleted " + i + " rows successfully");
                accountNumberList.removeAll();
                loadAccounts();
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    //Do Update Account Button
    updateAccountButton = new JButton("Update Account");
    updateAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Statement statement = connection.createStatement();
                int i = statement.executeUpdate("UPDATE acc_acc " + "SET username='" + usernameText.getText()
                        + "', " + "password='" + passwordText.getText() + "', " + "act_ts = now() "
                        + "WHERE acc_id = " + accountNumberList.getSelectedValue());
                errorText.append("Updated " + i + " rows successfully");
                accountNumberList.removeAll();
                loadAccounts();
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    //Do Next Button
    nextButton = new JButton(">");
    nextButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                if (!rs.isLast()) {
                    rs.next();
                    accountIDText.setText(rs.getString("acc_id"));
                    usernameText.setText(rs.getString("username"));
                    passwordText.setText(rs.getString("password"));
                    tsText.setText(rs.getString("ts"));
                    activeTSText.setText(rs.getString("act_ts"));
                }
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    //Do Next Button
    previousButton = new JButton("<");
    previousButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                if (!rs.isFirst()) {
                    rs.previous();
                    accountIDText.setText(rs.getString("acc_id"));
                    usernameText.setText(rs.getString("username"));
                    passwordText.setText(rs.getString("password"));
                    tsText.setText(rs.getString("ts"));
                    activeTSText.setText(rs.getString("act_ts"));
                }
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    //Do last Button
    lastButton = new JButton(">|");
    lastButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                rs.last();
                accountIDText.setText(rs.getString("acc_id"));
                usernameText.setText(rs.getString("username"));
                passwordText.setText(rs.getString("password"));
                tsText.setText(rs.getString("ts"));
                activeTSText.setText(rs.getString("act_ts"));
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    //Do first Button
    firstButton = new JButton("|<");
    firstButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                rs.first();
                accountIDText.setText(rs.getString("acc_id"));
                usernameText.setText(rs.getString("username"));
                passwordText.setText(rs.getString("password"));
                tsText.setText(rs.getString("ts"));
                activeTSText.setText(rs.getString("act_ts"));
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    //Do gotoButton
    gotoButton = new JButton("Goto");
    gotoButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                rs.absolute(Integer.parseInt(gotoText.getText()));
                accountIDText.setText(rs.getString("acc_id"));
                usernameText.setText(rs.getString("username"));
                passwordText.setText(rs.getString("password"));
                tsText.setText(rs.getString("ts"));
                activeTSText.setText(rs.getString("act_ts"));
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    //Do freeQueryButton
    freeQueryButton = new JButton("Execute Query");
    freeQueryButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                if (freeQueryText.getText().toUpperCase().indexOf("SELECT") >= 0) {
                    rs = statement.executeQuery(freeQueryText.getText());
                    if (rs.next()) {
                        accountIDText.setText(rs.getString("acc_id"));
                        usernameText.setText(rs.getString("username"));
                        passwordText.setText(rs.getString("password"));
                        tsText.setText(rs.getString("ts"));
                        activeTSText.setText(rs.getString("act_ts"));
                    }
                } else {
                    int i = statement.executeUpdate(freeQueryText.getText());
                    errorText.append("Rows affected = " + i);
                    loadAccounts();
                }
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            }
        }
    });

    JPanel first = new JPanel(new GridLayout(5, 1));
    first.add(accountNumberListScrollPane);
    first.add(getAccountButton);
    first.add(insertAccountButton);
    first.add(deleteAccountButton);
    first.add(updateAccountButton);

    accountIDText = new JTextField(15);
    usernameText = new JTextField(15);
    passwordText = new JTextField(15);
    tsText = new JTextField(15);
    activeTSText = new JTextField(15);
    errorText = new JTextArea(5, 15);
    errorText.setEditable(false);

    JPanel second = new JPanel();
    second.setLayout(new GridLayout(6, 1));
    second.add(accountIDText);
    second.add(usernameText);
    second.add(passwordText);
    second.add(tsText);
    second.add(activeTSText);

    JPanel third = new JPanel();
    third.add(new JScrollPane(errorText));

    JPanel fourth = new JPanel();
    fourth.add(firstButton);
    fourth.add(previousButton);
    fourth.add(nextButton);
    fourth.add(lastButton);
    fourth.add(gotoText);
    fourth.add(gotoButton);

    JPanel fifth = new JPanel();
    fifth.add(freeQueryText);

    c.add(first);
    c.add(second);
    c.add(third);
    c.add(fourth);
    c.add(fifth);
    c.add(freeQueryButton);
    setSize(500, 500);
    show();
}

From source file:Main.java

private void addComponentsToPane() {

    JButton button = new JButton("Clear");
    button.addActionListener(this);

    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);

    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);

    displayArea = new JTextArea();
    displayArea.setEditable(false);//from   w  ww. j  a  v  a2 s  .c  o  m
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));

    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
}

From source file:DocumentEventDemo.java

public DocumentEventDemo() {
    super(new GridBagLayout());
    GridBagLayout gridbag = (GridBagLayout) getLayout();
    GridBagConstraints c = new GridBagConstraints();

    JButton button = new JButton("Clear");
    button.addActionListener(this);

    textField = new JTextField(20);
    textField.addActionListener(new MyTextActionListener());
    textField.getDocument().addDocumentListener(new MyDocumentListener());
    textField.getDocument().putProperty("name", "Text Field");

    textArea = new JTextArea();
    textArea.getDocument().addDocumentListener(new MyDocumentListener());
    textArea.getDocument().putProperty("name", "Text Area");

    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setPreferredSize(new Dimension(200, 75));

    displayArea = new JTextArea();
    displayArea.setEditable(false);//from   ww w . ja  v  a  2s. c  o m
    JScrollPane displayScrollPane = new JScrollPane(displayArea);
    displayScrollPane.setPreferredSize(new Dimension(200, 75));

    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 1.0;
    c.fill = GridBagConstraints.HORIZONTAL;
    gridbag.setConstraints(textField, c);
    add(textField);

    c.gridx = 0;
    c.gridy = 1;
    c.weightx = 0.0;
    c.gridheight = 2;
    c.fill = GridBagConstraints.BOTH;
    gridbag.setConstraints(scrollPane, c);
    add(scrollPane);

    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
    c.weighty = 1.0;
    gridbag.setConstraints(displayScrollPane, c);
    add(displayScrollPane);

    c.gridx = 1;
    c.gridy = 2;
    c.weightx = 0.0;
    c.gridheight = 1;
    c.weighty = 0.0;
    c.fill = GridBagConstraints.HORIZONTAL;
    gridbag.setConstraints(button, c);
    add(button);

    setPreferredSize(new Dimension(450, 250));
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}

From source file:KeyEventDemo.java

public KeyEventDemo() {
    super(new BorderLayout());

    JButton button = new JButton("Clear");
    button.addActionListener(this);

    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);

    //Uncomment this if you wish to turn off focus
    //traversal. The focus subsystem consumes
    //focus traversal keys, such as Tab and Shift Tab.
    //If you uncomment the following line of code, this
    //disables focus traversal and the Tab events will
    //become available to the key event listener.
    //typingArea.setFocusTraversalKeysEnabled(false);

    displayArea = new JTextArea();
    displayArea.setEditable(false);/*from   w  ww.  j a v  a2  s. c o m*/
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));

    add(typingArea, BorderLayout.PAGE_START);
    add(scrollPane, BorderLayout.CENTER);
    add(button, BorderLayout.PAGE_END);
}

From source file:components.CustomDialog.java

/** Creates the reusable dialog. */
public CustomDialog(Frame aFrame, String aWord, DialogDemo parent) {
    super(aFrame, true);
    dd = parent;//  ww w . ja va2s.  c o  m

    magicWord = aWord.toUpperCase();
    setTitle("Quiz");

    textField = new JTextField(10);

    //Create an array of the text and components to be displayed.
    String msgString1 = "What was Dr. SEUSS's real last name?";
    String msgString2 = "(The answer is \"" + magicWord + "\".)";
    Object[] array = { msgString1, msgString2, textField };

    //Create an array specifying the number of dialog buttons
    //and their text.
    Object[] options = { btnString1, btnString2 };

    //Create the JOptionPane.
    optionPane = new JOptionPane(array, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options,
            options[0]);

    //Make this dialog display it.
    setContentPane(optionPane);

    //Handle window closing correctly.
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            /*
             * Instead of directly closing the window,
             * we're going to change the JOptionPane's
             * value property.
             */
            optionPane.setValue(new Integer(JOptionPane.CLOSED_OPTION));
        }
    });

    //Ensure the text field always gets the first focus.
    addComponentListener(new ComponentAdapter() {
        public void componentShown(ComponentEvent ce) {
            textField.requestFocusInWindow();
        }
    });

    //Register an event handler that puts the text into the option pane.
    textField.addActionListener(this);

    //Register an event handler that reacts to option pane state changes.
    optionPane.addPropertyChangeListener(this);
}

From source file:br.usp.poli.lta.cereda.wsn2spa.Editor.java

public Editor() {
    super("WSN2SPA");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setResizable(false);/*from  w  w  w . j a va 2s  .co m*/
    setLayout(new MigLayout());

    txtDotOutput = new JTextField(15);
    txtYamlOutput = new JTextField(15);
    txtFile = new JTextField(10);
    txtFile.setEditable(false);

    checkDFAConvert = new JCheckBox("Convert submachines to DFA's");
    checkMinimize = new JCheckBox("Apply state minimization");
    checkMinimize.setEnabled(false);
    btnOpen = new JButton(
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/wsn2spa/images/open.png")));
    btnRun = new JButton("Convert WSN to SPA",
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/wsn2spa/images/play.png")));

    chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text files", "txt", "text");
    chooser.setFileFilter(filter);

    btnOpen.addActionListener((ActionEvent ae) -> {
        int value = chooser.showOpenDialog(Editor.this);
        if (value == JFileChooser.APPROVE_OPTION) {
            file = chooser.getSelectedFile();
            txtFile.setText(file.getName());
        }
    });

    checkDFAConvert.addChangeListener((ChangeEvent ce) -> {
        checkMinimize.setEnabled(checkDFAConvert.isSelected());
        if (!checkDFAConvert.isSelected()) {
            checkMinimize.setSelected(false);
        }
    });

    btnRun.addActionListener((ActionEvent ae) -> {
        boolean restore = checkMinimize.isEnabled();
        state(false, txtDotOutput, txtYamlOutput, btnOpen, btnRun, checkDFAConvert, checkMinimize);
        try {
            if (!filled(txtDotOutput, txtYamlOutput, txtFile)) {
                throw new Exception(
                        "The fields could not be empty. Make " + "sure to select the grammar file and provide "
                                + "both DOT and YAML patterns in their respective " + "fields.");
            }
            if (!valid(txtDotOutput, txtYamlOutput)) {
                throw new Exception(
                        "The DOT and YAML fields lack the " + "replacement pattern '%s' in order to generate "
                                + "files corresponding to each submachine in the "
                                + "automaton model. Make sure to include the " + "pattern.");
            }
            if (!file.exists()) {
                throw new Exception("The provided grammar file '" + "' does"
                        + " not exist. Make sure the location is correct and" + " try again.");
            }

            String text = FileUtils.readFileToString(file, "UTF-8").trim();
            WirthLexer wl = new WirthLexer(text);
            Generator g = new Generator(wl);
            g.generateAutomaton();

            Writer writer = new Writer(g.getTransitions());
            Map<String, String> map = writer.generateYAMLMap(txtYamlOutput.getText().trim());

            if (Utils.neither(checkDFAConvert, checkMinimize)) {
                br.usp.poli.lta.cereda.wirth2ape.dot.Dot dot = new br.usp.poli.lta.cereda.wirth2ape.dot.Dot(
                        g.getTransitions());
                dot.generate(txtDotOutput.getText().trim());
                for (String key : map.keySet()) {
                    FileUtils.write(new File(key), map.get(key), "UTF-8");
                }
            } else {
                for (String key : map.keySet()) {
                    Triple<Integer, Set<Integer>, List<SimpleTransition>> spec = Reader.read(map.get(key));
                    br.usp.poli.lta.cereda.nfa2dfa.dot.Dot dot = new br.usp.poli.lta.cereda.nfa2dfa.dot.Dot();
                    dot.append(Reader.getName(), "original", spec);

                    Conversion c;

                    if (checkDFAConvert.isSelected()) {
                        c = new Conversion(spec.getThird(), spec.getFirst(), spec.getSecond());
                        spec = c.convert();
                        dot.append(Reader.getName().concat("'"), "converted", spec);
                    }

                    if (checkMinimize.isSelected()) {
                        c = new Conversion(spec.getThird(), spec.getFirst(), spec.getSecond());
                        spec = c.minimize();
                        dot.append(Reader.getName().concat("''"), "minimized", spec);
                    }

                    Yaml yaml = new Yaml();
                    Spec result = Utils.toFormat(spec);
                    result.setName(Reader.getName());
                    map.put(key, yaml.dump(result));

                    String dotname = String.format(txtDotOutput.getText().trim(), Reader.getName());
                    dot.dump(dotname);

                }

                for (String key : map.keySet()) {
                    FileUtils.write(new File(key), map.get(key), "UTF-8");
                }
            }

            showMessage("Success!", "The structured pushdown automaton "
                    + "spec was successfully generated from the provided " + "grammar file.");

        } catch (Exception exception) {
            showException("An exception was thrown", exception);
        }
        state(true, txtDotOutput, txtYamlOutput, btnOpen, btnRun, checkDFAConvert, checkMinimize);
        checkMinimize.setEnabled(restore);
    });

    add(new JLabel("Grammar file:"));
    add(txtFile);
    add(btnOpen, "growx, wrap");
    add(new JLabel("DOT pattern:"));
    add(txtDotOutput, "growx, span 2, wrap");
    add(new JLabel("YAML pattern:"));
    add(txtYamlOutput, "growx, span 2, wrap");
    add(checkDFAConvert, "span 3, wrap");
    add(checkMinimize, "span 3, wrap");
    add(btnRun, "growx, span 3");

    pack();
    setLocationRelativeTo(null);

}

From source file:components.TextSamplerDemo.java

public TextSamplerDemo() {
    setLayout(new BorderLayout());

    //Create a regular text field.
    JTextField textField = new JTextField(10);
    textField.setActionCommand(textFieldString);
    textField.addActionListener(this);

    //Create a password field.
    JPasswordField passwordField = new JPasswordField(10);
    passwordField.setActionCommand(passwordFieldString);
    passwordField.addActionListener(this);

    //Create a formatted text field.
    JFormattedTextField ftf = new JFormattedTextField(java.util.Calendar.getInstance().getTime());
    ftf.setActionCommand(textFieldString);
    ftf.addActionListener(this);

    //Create some labels for the fields.
    JLabel textFieldLabel = new JLabel(textFieldString + ": ");
    textFieldLabel.setLabelFor(textField);
    JLabel passwordFieldLabel = new JLabel(passwordFieldString + ": ");
    passwordFieldLabel.setLabelFor(passwordField);
    JLabel ftfLabel = new JLabel(ftfString + ": ");
    ftfLabel.setLabelFor(ftf);//ww  w .j  ava 2 s.com

    //Create a label to put messages during an action event.
    actionLabel = new JLabel("Type text in a field and press Enter.");
    actionLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

    //Lay out the text controls and the labels.
    JPanel textControlsPane = new JPanel();
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();

    textControlsPane.setLayout(gridbag);

    JLabel[] labels = { textFieldLabel, passwordFieldLabel, ftfLabel };
    JTextField[] textFields = { textField, passwordField, ftf };
    addLabelTextRows(labels, textFields, gridbag, textControlsPane);

    c.gridwidth = GridBagConstraints.REMAINDER; //last
    c.anchor = GridBagConstraints.WEST;
    c.weightx = 1.0;
    textControlsPane.add(actionLabel, c);
    textControlsPane.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Text Fields"), BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    //Create a text area.
    JTextArea textArea = new JTextArea("This is an editable JTextArea. "
            + "A text area is a \"plain\" text component, " + "which means that although it can display text "
            + "in any font, all of the text is in the same font.");
    textArea.setFont(new Font("Serif", Font.ITALIC, 16));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    JScrollPane areaScrollPane = new JScrollPane(textArea);
    areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    areaScrollPane.setPreferredSize(new Dimension(250, 250));
    areaScrollPane.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Plain Text"),
                    BorderFactory.createEmptyBorder(5, 5, 5, 5)),
            areaScrollPane.getBorder()));

    //Create an editor pane.
    JEditorPane editorPane = createEditorPane();
    JScrollPane editorScrollPane = new JScrollPane(editorPane);
    editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    editorScrollPane.setPreferredSize(new Dimension(250, 145));
    editorScrollPane.setMinimumSize(new Dimension(10, 10));

    //Create a text pane.
    JTextPane textPane = createTextPane();
    JScrollPane paneScrollPane = new JScrollPane(textPane);
    paneScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    paneScrollPane.setPreferredSize(new Dimension(250, 155));
    paneScrollPane.setMinimumSize(new Dimension(10, 10));

    //Put the editor pane and the text pane in a split pane.
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, editorScrollPane, paneScrollPane);
    splitPane.setOneTouchExpandable(true);
    splitPane.setResizeWeight(0.5);
    JPanel rightPane = new JPanel(new GridLayout(1, 0));
    rightPane.add(splitPane);
    rightPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Styled Text"),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    //Put everything together.
    JPanel leftPane = new JPanel(new BorderLayout());
    leftPane.add(textControlsPane, BorderLayout.PAGE_START);
    leftPane.add(areaScrollPane, BorderLayout.CENTER);

    add(leftPane, BorderLayout.LINE_START);
    add(rightPane, BorderLayout.LINE_END);
}

From source file:com.hexidec.ekit.component.PropertiesDialog.java

public PropertiesDialog(Window parent, String[] fields, String[] types, String[] values, String title,
        boolean bModal) {
    super(parent, title);
    setModal(bModal);/*from   ww  w. java  2s .co m*/
    htInputFields = new Hashtable<String, JComponent>();
    final Object[] buttonLabels = { Translatrix.getTranslationString("DialogAccept"),
            Translatrix.getTranslationString("DialogCancel") };
    List<Object> panelContents = new ArrayList<Object>();
    for (int iter = 0; iter < fields.length; iter++) {
        String fieldName = fields[iter];
        String fieldType = types[iter];
        JComponent fieldComponent;
        JComponent panelComponent = null;
        if (fieldType.equals("text") || fieldType.equals("integer")) {
            fieldComponent = new JTextField(3);
            if (values[iter] != null && values[iter].length() > 0) {
                ((JTextField) (fieldComponent)).setText(values[iter]);
            }

            if (fieldType.equals("integer")) {
                ((AbstractDocument) ((JTextField) (fieldComponent)).getDocument())
                        .setDocumentFilter(new DocumentFilter() {

                            @Override
                            public void insertString(FilterBypass fb, int offset, String text,
                                    AttributeSet attrs) throws BadLocationException {
                                replace(fb, offset, 0, text, attrs);
                            }

                            @Override
                            public void replace(FilterBypass fb, int offset, int length, String text,
                                    AttributeSet attrs) throws BadLocationException {

                                if (StringUtils.isNumeric(text)) {
                                    super.replace(fb, offset, length, text, attrs);
                                }

                            }

                        });
            }
        } else if (fieldType.equals("bool")) {
            fieldComponent = new JCheckBox(fieldName);
            if (values[iter] != null) {
                ((JCheckBox) (fieldComponent)).setSelected(values[iter] == "true");
            }
            panelComponent = fieldComponent;
        } else if (fieldType.equals("combo")) {
            fieldComponent = new JComboBox();
            if (values[iter] != null) {
                StringTokenizer stParse = new StringTokenizer(values[iter], ",", false);
                while (stParse.hasMoreTokens()) {
                    ((JComboBox) (fieldComponent)).addItem(stParse.nextToken());
                }
            }
        } else {
            fieldComponent = new JTextField(3);
        }
        htInputFields.put(fieldName, fieldComponent);
        if (panelComponent == null) {
            panelContents.add(fieldName);
            panelContents.add(fieldComponent);
        } else {
            panelContents.add(panelComponent);
        }
    }
    jOptionPane = new JOptionPane(panelContents.toArray(), JOptionPane.QUESTION_MESSAGE,
            JOptionPane.OK_CANCEL_OPTION, null, buttonLabels, buttonLabels[0]);

    setContentPane(jOptionPane);
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

    jOptionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();
            if (isVisible() && (e.getSource() == jOptionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY)
                    || prop.equals(JOptionPane.INPUT_VALUE_PROPERTY))) {
                Object value = jOptionPane.getValue();
                if (value == JOptionPane.UNINITIALIZED_VALUE) {
                    return;
                }
                if (value.equals(buttonLabels[0])) {
                    setVisible(false);
                } else {
                    setVisible(false);
                }
            }
        }
    });
    this.pack();
    setLocation(SwingUtilities.getPointForCentering(this, parent));
}

From source file:SwingDnDTest.java

public SwingDnDFrame() {
    setTitle("SwingDnDTest");
    JTabbedPane tabbedPane = new JTabbedPane();

    JList list = SampleComponents.list();
    tabbedPane.addTab("List", list);
    JTable table = SampleComponents.table();
    tabbedPane.addTab("Table", table);
    JTree tree = SampleComponents.tree();
    tabbedPane.addTab("Tree", tree);
    JFileChooser fileChooser = new JFileChooser();
    tabbedPane.addTab("File Chooser", fileChooser);
    JColorChooser colorChooser = new JColorChooser();
    tabbedPane.addTab("Color Chooser", colorChooser);

    final JTextArea textArea = new JTextArea(4, 40);
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBorder(new TitledBorder(new EtchedBorder(), "Drag text here"));

    JTextField textField = new JTextField("Drag color here");
    textField.setTransferHandler(new TransferHandler("background"));

    tabbedPane.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            textArea.setText("");
        }//from  w w w .  java  2  s.  c o m
    });

    tree.setDragEnabled(true);
    table.setDragEnabled(true);
    list.setDragEnabled(true);
    fileChooser.setDragEnabled(true);
    colorChooser.setDragEnabled(true);
    textField.setDragEnabled(true);

    add(tabbedPane, BorderLayout.NORTH);
    add(scrollPane, BorderLayout.CENTER);
    add(textField, BorderLayout.SOUTH);
    pack();
}