一、界面组件
- 布局
流式布局:所有组件都放在一行上(居中显示),若一行空间不够,就显示在下一行。
边框布局:分为东、西、南、北、中,与流布局不同,边框布局会扩展所有组件的尺寸以便填满可用空间。
网格布局:像电子数据表一样,按行列排列所有组件,它的每个单元大小都是也一样的。
package gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorPanel extends JPanel {
public static void main(String[] args) {
EventQueue.invokeLater(() ->{
JFrame frame = new JFrame();
frame.setContentPane(new CalculatorPanel());
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
public CalculatorPanel() {
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
display = new JButton("0");
display.setEnabled(true);
add(display, BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
add(panel, BorderLayout.CENTER);
}
private void addButton(String label, ActionListener ac) {
JButton button = new JButton(label);
button.addActionListener(ac);
panel.add(button);
}
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
display.setText("");
start = false;
}
display.setText(display.getText() + input);
}
}
private class CommandAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(start) {
if (command.equals("-")) {
display.setText(command);
start = false;
} else {
lastCommand = command;
}
} else {
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}
}
public void calculate(double x) {
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
display.setText("" + result);
}
}
}
- 文本输入
文本域JTextField、文本区JTextArea、密码域JPassword,获取(get)、设置(set)操作文本方法,例如getText(),setText(String text),isEditable(),setEditable(boolean b)是否允许编辑。
标签JLabel显示文本和图标。
密码域JPassword,用户输入的字符不显示出来,每个输入的字符都用回显字符(echo character)表示,典型的回显字符是(*),可以设置setEchoChar(char echo)。
文本区JTextArea,输入回车"/n"换行,开启自动换行setLineWrap(true)。配合滚动窗格JScrollPane,如果文本超出了文本区可以显示的范围,滚动条就会自动出现,并且在删除部分文本后,当文本能够显示在文本区范围内时,
JEditorPane可以显示格式化文本,例如HTML。
package gui;
import javax.swing.*;
import java.awt.*;
public class TextComponentFrame extends JFrame {
public static final int TEXTAREA_ROWS = 8;
public static final int TEXTAREA_COLUMNS = 20;
public TextComponentFrame() {
JTextField textField = new JFormattedTextField();
JPasswordField passwordField = new JPasswordField();
JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(2, 2));
northPanel.add(new JLabel("User name:", SwingConstants.RIGHT));
northPanel.add(textField);
northPanel.add(new JLabel("Password:", SwingConstants.RIGHT));
northPanel.add(passwordField);
add(northPanel, BorderLayout.NORTH);
JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
JPanel southPanel = new JPanel();
JButton insertButton = new JButton("Insert");
southPanel.add(insertButton);
insertButton.addActionListener(event -> {
textArea.append("User name: " + textField.getText() + " Password: "
+ new String(passwordField.getPassword()) + "\n");
});
add(southPanel, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(()-> {
TextComponentFrame frame = new TextComponentFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
- 选择组件
复选框JCheckBox,setSelected方法设置选定或取消选定,isSelected返回是否选中
package gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class CheckBoxFrame extends JFrame {
private JLabel label;
private JCheckBox bold;
private JCheckBox italic;
private static final int FONTSIZE = 24;
public CheckBoxFrame() {
label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.BOLD, FONTSIZE));
add(label, BorderLayout.CENTER);
ActionListener listener = event -> {
int mode = 0;
if (bold.isSelected()) mode += Font.BOLD;
if (italic.isSelected()) mode += Font.ITALIC;
label.setFont(new Font("Serif", mode, FONTSIZE));
};
JPanel buttonPanel = new JPanel();
bold = new JCheckBox("Bold");
bold.addActionListener(listener);
bold.setSelected(true);
buttonPanel.add(bold);
italic = new JCheckBox("Italic");
italic.addActionListener(listener);
buttonPanel.add(italic);
add(buttonPanel, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(()-> {
CheckBoxFrame frame = new CheckBoxFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
单选框JRadioBox
package gui;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
public class RadioButtonFrame extends JFrame {
private JPanel buttonPanel;
private ButtonGroup group;
private JLabel label;
private static final int DEFAULT_SIZE = 36;
public RadioButtonFrame() {
label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
add(label, BorderLayout.CENTER);
buttonPanel = new JPanel();
group = new ButtonGroup();
addRadioButton("Small", 18);
addRadioButton("Medium", 12);
addRadioButton("Large", 18);
addRadioButton("Extra large", 36);
add(buttonPanel, BorderLayout.SOUTH);
pack();
}
private void addRadioButton(String name, int size) {
boolean selected = size == DEFAULT_SIZE;
JRadioButton button = new JRadioButton(name, selected);
group.add(button);
buttonPanel.add(button);
ActionListener listener = event -> label.setFont(new Font("Serif", Font.PLAIN, size));
button.addActionListener(listener);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
RadioButtonFrame frame = new RadioButtonFrame();
frame.setTitle("radioButton Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
下拉列表JComboBox
package gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class ComboBoxFrame extends JFrame {
private JComboBox<String> faceCombo;
private JLabel label;
private static final int DEFAULT_SIZE = 24;
public ComboBoxFrame() {
label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
add(label, BorderLayout.CENTER);
faceCombo = new JComboBox<>();
faceCombo.addItem("Serif");
faceCombo.addItem("SansSerif");
faceCombo.addItem("Monospaced");
faceCombo.addItem("Dialog");
faceCombo.addItem("DialogInput");
faceCombo.addActionListener(event -> {
label.setFont(new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()), Font.PLAIN,
DEFAULT_SIZE));
});
JPanel comboPanel = new JPanel();
comboPanel.add(faceCombo);
add(comboPanel, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
ComboBoxFrame frame = new ComboBoxFrame();
frame.setTitle("ComboBox Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
• • JPopupMenu popup = new JPopupMenu();
popup.show(panel, x, y);// 必须调用show方法显示
component.setComponentPopupMenu(popup);// 设置某一组件弹出菜单
- 菜单
窗口顶部为菜单栏(menu bar),下拉菜单项(menu items)和子菜单(submenus),各个菜单项的分隔符(addSeparator)。
菜单项又有复选框和单选钮: - 弹出菜单:
- 对话框
1)选择对话框(JOptionPane)
showMessageDialog只有确认/showConfirmDialog选择确定或者取消/showOptionDialog定制选项/showInputDialog提示输入一行文本
Object[] options = {"OK", "CANCEL", "OTHERS", "APPEND"};
JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
2)继承JDialog,创建自定义对话框。
3)文件对话框JFileChooser,使用showOpenDialog打开对话框。
4)颜色选择器JColorChooser
*滑动条JSlider、工具栏JToolBar、工具提示toolTips
三、小记
慢慢探索、深入,争取写出点有意义的东西。