Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.
JButton
: ButtonModel
, BasicButtonUI
, ButtonUIListener
JPanel
is FlowLayout
.panel.setLayout(new GridLayout(4, 4));
JFrame
.frame.add(panel, BorderLayout.NORTH);
JPanel
, and add the panel.panel.setLayout(new GridLayout(4, 4)); panel.add(new JButton("1")); panel.add(new JButton("2"));
toolbar.setLayout(new GridLayout(1, 0));
JTextField
with default text and size:
JTextField textField = new JTextField("Default input", 20);
String input = textField.getText();
JPasswordField
to mask user input. The input is returned as a char[]
array:
char[] input = passwordField.getPassword(); // Overwrite contents when you are done with it
JLabel label = new JLabel("Password: ", JLabel.RIGHT);
JTextArea
with number of rows and columns:
textArea = new JTextArea(8, 40); // 8 lines of 40 columns each
getText
/setText
to read and write contents.textArea.setLineWrap(true); // long lines are wrapped
textArea = new JTextArea(8, 40); JScrollPane scrollPane = new JScrollPane(textArea); // Add scrollPane to container
boldBox = new JCheckBox("Bold");
isSelected
/setSelected
to read/write state:
boldBox.setSelected(true);
boldBox.addActionListener(event -> { if (boldBox.isSelected()) . . . })
ButtonGroup
:
ButtonGroup group = new ButtonGroup(); JRadioButton smallButton = new JRadioButton("Small", false); group.add(smallButton); JRadioButton mediumButton = new JRadioButton("Medium", true); group.add(mediumButton);
smallButton.addActionListener(event -> label.setFont(new Font("Serif", Font.PLAIN, 8)));
ButtonGroup
.JComponent
.Border etched = BorderFactory.createEtchedBorder(); Border titled = BorderFactory.createTitledBorder(etched, "A Title"); panel.setBorder(titled);
setEditable
to allow editing of the options.
JComboBox
is a generic class: JComboBox<String>
, JComboBox<Integer>
.JComboBox<String> faceCombo = . . .; Object item = faceCombo.getSelectedItem(); String item = faceCombo.getItemAt(combo.getSelectedIndex()); // if not editable
ActionEvent
is fired when an item is selected:
faceCombo.addActionListener(event -> label.setFont(new Font( comboBox.getItemAt(faceCombo.getSelectedIndex()), Font.PLAIN, DEFAULT_SIZE)));
JSlider slider = new JSlider(min, max, initialValue);
ChangeListener listener = event -> { JSlider slider = (JSlider) event.getSource(); int value = slider.getValue(); . . . };
slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); slider.setPaintTicks(true); slider.setPaintLabels(true);
Hashtable<Integer, Component> labelTable = new Hashtable<>(); labelTable.put(0, new JLabel("A")) . . . slider.setLabelTable(labelTable);
JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar);
JMenu editMenu = new JMenu("Edit"); menuBar.add(editMenu);
JMenuItem pasteItem = new JMenuItem("Paste"); editMenu.add(pasteItem); editMenu.addSeparator(); JMenu optionsMenu = . . .; // a submenu editMenu.add(optionsMenu);
pasteItem.addActionListener(event -> . . .);
Action
objects to describe actions that can be triggered by menus, toolbar buttons and keystrokes:
Action exitAction = new AbstractAction("Exit") // menu item text goes here { public void actionPerformed(ActionEvent event) { System.exit(0); } }; JMenuItem exitItem = fileMenu.add(exitAction);
JMenuItem cutItem = new JMenuItem("Cut", new ImageIcon("cut.gif"));
Action
.JCheckBoxMenuItem readonlyItem = new JCheckBoxMenuItem("Read-only");
ButtonGroup group = new ButtonGroup(); JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert"); insertItem.setSelected(true); JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype"); group.add(insertItem); group.add(overtypeItem); optionsMenu.add(insertItem); optionsMenu.add(overtypeItem);
JPopupMenu
on the top level:
JPopupMenu popup = new JPopupMenu(); JMenuItem item = new JMenuItem("Cut"); popup.add(item); . . .
component.setComponentPopupMenu(popup);
aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
setMnemonic
method:
JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H');
openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
saveItem.setEnabled(false);
JToolBar bar = new JToolBar(); bar.add(blueButton); bar.add(yellowAction); // Can also add Action objects bar.addSeparator();
frame.add(bar, BorderLayout.NORTH);
blueButton.setToolTipText("Blue"); yellowAction.putValue(Action.SHORT_DESCRIPTION, "Yellow");
GridBagLayout layout = new GridBagLayout(); panel.setLayout(layout);
GridBagConstraints constraints = new GridBagConstraints(); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = 2; constraints.gridheight = 1; panel.add(component, constraints);
gridx, gridy, gridwidth, gridheight
: Location and spans in the grid.weightx, weighty
: Set to 100 if size should grow, or to 0 if size should stay constant when form is resized.fill, anchor
: If a component shouldn't fill the entire cell, then use GridBagConstraints
constants to specify fill mode and anchor position.insets
: spacing around the component.ipadx, ipady
: added to the minimum size of the component.GBC
helper class in the sample code.LayoutManger
interface and override these methods:
void addLayoutComponent(String s, Component c); void removeLayoutComponent(Component c); Dimension preferredLayoutSize(Container parent); Dimension minimumLayoutSize(Container parent); void layoutContainer(Container parent);
JOptionPane
class has ready-made dialogs for a single piece of information:
showMessageDialog
shows a message.showConfirmDialog
gets a confirmation such as OK/Cancel.showOptionDialog
makes user select from a set of options.showInputDialog
gets an input string.int selection = JOptionPane.showConfirmDialog(parent, "Message", "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
JDialog
class:
public AboutDialog extends JDialog { public AboutDialog(JFrame owner) { super(owner, "About DialogTest", true); add(new JLabel( "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"), BorderLayout.CENTER); . . . setSize(250, 150); } }
JDialog dialog = new AboutDialog(this); dialog.setVisible(true);
ok.addActionListener(event -> setVisible(false));
public class User { . . .}
public class PasswordChooser { public void setUser(User u) { . . . } public User getUser() { . . . } . . . }
public boolean showDialog() { JDialog dialog = new JDialog(frame, true /* modal */); dialog.add(panel); dialog.pack(); dialog.setVisible(true); }
JFileChooser
object and set the directory:
JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new FileNameExtensionFilter("Image files", "gif", "jpg"));
int result = chooser.showOpenDialog(parent); int result = chooser.showSaveDialog(parent);
JFileChooser.APPROVE_OPTION
, get the file:
File filename = chooser.getSelectedFile();