Top-level Containers (JFrame) |
| w = | new JFrame(); |
Constructor |
| w.setTitle(t); |
Sets titlebar text to t |
| w.setDefaultCloseOperation(opt); |
Use opt JFrame.EXIT_ON_CLOSE to terminate program when close box clicked. |
| w.setResizable(false); |
Prevent user from resizing window. |
| w.show(); |
Use w.setVisible(true) instead. |
| w.hide(); |
Use w.setVisible(false) instead. |
| w.setVisible(true/false); |
Same as w.show() or w.hide() |
| w.setContentPane(cont); |
Sets the content pane - common to pass a JPanel here. |
| cont = | w.getContentPane(); |
Returns the window's content pane. |
| w.setJMenuBar(mb); |
Adds JMenuBar (contains Jmenus, which contain JMenuItems) to window. |
Low-level Containers (JPanel) |
| p = | new JPanel(); |
Creates new JPanel |
| p.setLayout(layout); |
Sets the panel's layout. |
| p.add(widget); |
Adds the widget to next position in Layout (eg, Flow, Grid, or Box layouts). |
| p.add(widget, constraint); |
Adds the widget to position defined by constraint (eg, Border or Gridbag layouts). |
Components (JLabel, JTextField, JButton) and their common methods |
| cmp.requestFocus(); |
Puts focus (eg, blinking cursor) in the field, selection of a button, etc. |
| tf.setFont(f); |
Sets font. |
| lbl = | new JLabel(t); |
Creates JLabel with text (can be HTML). Typically created in add() call. |
| tf = | new JTextField(n); |
Creates textfield about n columns wide. |
| s = | tf.getText(); |
Returns string in textfield. |
| tf.setText(s); |
Sets text to s. |
| tf.addActionListener(lst); |
Action listener lst will be called if enter typed. |
| tf.setEditable(true/false); |
Don't allow user to edit text field used for output. |
| tf.setHorizontalAlignment(align); |
JTextField.LEFT (default), JTextField.CENTER, or JTextField.RIGHT |
| btn = | new JButton(t); |
Creates button with text t. |
| btn = | new JButton(act); |
Creates button from Action act for text, icon, listener, etc. |
| btn = | new JButton(img); |
Creates button with icon img. |
| btn = | new JButton(t, img); |
Creates button with both text and icon. |
| btn.addActionListener(lst); |
Action listener lst called when button clicked. |
| btn.setEnabled(true/false); |
Used to enable/disable button. |
Layouts (FlowLayout, BorderLayout, GridLayout, BoxLayout) |
| p.setLayout(new FlowLayout()); |
Sets layout of the panel to FlowLayout. |
| p.setLayout(new BorderLayout()); |
Sets layout of the panel to BorderLayout. Widgets added with constraint. |
| p.setLayout(new GridLayout(r, c)); |
Sets layout to GridLayout with specified rows and columns. |
| p.setLayout(new GridLayout(r, c, h, v)); |
As above but also specifies horizontal and vertical space between cells. |
| p.setLayout(new BoxLayout(p, dir)); |
Layout is horizontal (dir is BoxLayout.X_AXIS) or vertical (BoxLayout.X_AXIS). |