我正在尝试学习java GUI,但我注意到,当尝试创建多个类似的按钮时,有很多重复。例如在这段代码中:
JButton btnAddCar = new JButton("Add Car");
btnAddCar.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddCar.setBounds(5, 5, 355, 155);
addInternalFrame.getContentPane().add(btnAddCar);
JButton btnAddHybridCar = new JButton("Add Hybrid Car");
btnAddHybridCar.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddHybridCar.setBounds(5, 165, 355, 155);
addInternalFrame.getContentPane().add(btnAddHybridCar);
JButton btnAddVan = new JButton("Add Van");
btnAddVan.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddVan.setBounds(5, 325, 355, 155);
addInternalFrame.getContentPane().add(btnAddVan);
JButton btnAddMotorcycle = new JButton("Add Motorcycle");
btnAddMotorcycle.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddMotorcycle.setBounds(5, 485, 355, 155);
addInternalFrame.getContentPane().add(btnAddMotorcycle);
JButton btnAddHybridMotorcycle = new JButton("Add Hybrid Motorcycle");
btnAddHybridMotorcycle.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddHybridMotorcycle.setBounds(5, 645, 355, 155);
addInternalFrame.getContentPane().add(btnAddHybridMotorcycle);
JButton btnAddCustomer = new JButton("Add Customer");
btnAddCustomer.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddCustomer.setBounds(365, 5, 355, 155);
addInternalFrame.getContentPane().add(btnAddCustomer);
JButton btnAddVIPCustomer = new JButton("Add VIP Customer");
btnAddVIPCustomer.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddVIPCustomer.setBounds(365, 165, 355, 155);
addInternalFrame.getContentPane().add(btnAddVIPCustomer);
JButton btnAddEmployee = new JButton("Add Employee");
btnAddEmployee.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddEmployee.setBounds(365, 325, 355, 155);
addInternalFrame.getContentPane().add(btnAddEmployee);
JButton btnAddDepartmentManager = new JButton("Add Department Manager");
btnAddDepartmentManager.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnAddDepartmentManager.setBounds(365, 485, 355, 155);
addInternalFrame.getContentPane().add(btnAddDepartmentManager);
是否有一种更短、更美观的方式来编写这段代码?
您可以尝试将按钮创建外包给如下方法
注意:您可能还需要添加addInternalFrame
作为参数
private JButton createButton(String name, int x, int y){
JButton button = new JButton(name);
button.setFont(new Font("Tahoma", Font.PLAIN, 20));
button.setBounds(x, y, 355, 155);
addInternalFrame.getContentPane().add(button);
return button;
}
并使用它创建按钮
JButton btnAddCar = createButton("Add Car", 5, 5);
JButton btnAddHybridCar = createButton("Add Hybrid Car", 5, 165);