接下来给”数据源配置“面板添加下拉框。
/**
* @author: lishuai
* @date: 2018/11/26 13:51
*/
public class WeimingSyncApplets {
public static void main(String[] args) {
// 面板组件
JPanel taskPanel = new JPanel();
JPanel dbPanel = new JPanel();
JTabbedPane tabbedPane = buildJTabbedPane(taskPanel, dbPanel);
buildFrame(tabbedPane);
}
private static JTabbedPane buildJTabbedPane(JPanel taskPanel, JPanel dbPanel) {
// 选项卡面板
JTabbedPane tabbedPane = new JTabbedPane();
// 通过BorderFactory来设置边框的特性
tabbedPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
tabbedPane.add("执行任务", taskPanel);
tabbedPane.add("数据源配置", dbPanel);
dbPanel.add(buildJLabel("数据库类型", 10, 20, 80, 25));
String dbs[] = {"mysql", "oracle", "sqlserver"};
dbPanel.add(buildJComboBox("mysql", "mysql", dbs, 0, 100, 20, 165, 25));
return tabbedPane;
}
private static void buildFrame(JComponent component) {
// 窗体容器
JFrame frame = new JFrame("数据同步工具");
frame.add(component);
// JFrame.EXIT_ON_CLOSE 退出
// JFrame.HIDE_ON_CLOSE 最小化隐藏
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
// 设置布局
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(BorderLayout.CENTER, component);
// 设置窗口最小尺寸
frame.setMinimumSize(new Dimension(1060, 560));
// 调整此窗口的大小,以适合其子组件的首选大小和布局
frame.pack();
// 设置窗口相对于指定组件的位置
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// 设置窗口尺寸是否固定不变
frame.setResizable(true);
}
private static JComboBox buildJComboBox(Object selectedItem, String name, String[] elements, int selectedIndex, int x, int y, int width, int height) {
DefaultComboBoxModel codeTypeModel = new DefaultComboBoxModel();
// elements 下拉框中的选项
for (String element : elements) {
codeTypeModel.addElement(element);
}
JComboBox codeTypeBox = new JComboBox(codeTypeModel);
codeTypeBox.setName(name);
// 默认选中的下拉框选项
codeTypeBox.setSelectedItem(selectedItem);
// codeTypeBox.setSelectedItem(selectedIndex);
codeTypeBox.setBounds(x, y, width, height);
// 添加下拉框事件监听器
codeTypeBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
// 选择的下拉框选项
System.out.println(e.getItem());
}
}
});
return codeTypeBox;
}
private static JLabel buildJLabel(String name, int x, int y, int width, int height) {
JLabel label = new JLabel(name);
label.setBounds(x, y, width, height);
return label;
}
}
效果如下:
下拉框选中对象改变时,监听器监听到事件:
内容来源于网络如有侵权请私信删除