Make a Text Field two columns wide in Java

Description

The following code shows how to make a Text Field two columns wide.

Example


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/* ww w.  j  a  v a 2 s  . c  om*/
public class Main {
  public static void main(String[] args) {
    JTextField tf = new JTextField("mm");
    tf.setPreferredSize(tf.getPreferredSize());
    tf.setText("");

    JPanel pHacked = new JPanel();
    pHacked.add(tf);

    JPanel pStock = new JPanel();
    pStock.add(new JTextField(2));

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new java.awt.GridLayout(0, 1));
    frame.add(pHacked);
    frame.add(pStock);
    frame.setSize(150, 150);
    frame.setVisible(true);
    tf.requestFocus();
  }
}

The code above generates the following result.

Make a Text Field two columns wide in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer