如何在Eclipse中消除Java重复代码:封装按钮创建方法
把重复的按钮样式逻辑抽成复用方法,只传入变化的参数(文本、图标路径、位置坐标),就能快速生成符合要求的按钮:
第一步:编写可复用的按钮生成方法
private JButton createBlueStyledButton(String text, String iconPath, int x, int y) { JButton button = new JButton(text); // 设置按钮图标 button.setIcon(new ImageIcon(WindowBook.class.getResource(iconPath))); // 固定样式配置 button.setFont(new Font("Arial", Font.BOLD, 16)); button.setBounds(x, y, 160, 38); // 蓝色按钮专属样式 button.setBackground(Color.BLUE); button.setForeground(Color.WHITE); button.setOpaque(true); button.setContentAreaFilled(false); button.setBorderPainted(false); button.setFocusPainted(false); return button; }
第二步:调用方法生成按钮
// 生成图书按钮并添加到面板 JButton btnBook = createBlueStyledButton(" Libros", "/interfaces/images/Book.png", 33, 115); panelBlue.add(btnBook); // 生成用户按钮并添加到面板 JButton btnUser = createBlueStyledButton(" Usuarios", "/interfaces/images/User.png", 43, 165); panelBlue.add(btnUser);
额外优化建议
如果后续需要给不同面板添加这类按钮,可以把父面板也作为参数传入方法,直接在方法内完成添加操作:
private void addBlueStyledButtonToPanel(String text, String iconPath, int x, int y, JPanel targetPanel) { JButton button = createBlueStyledButton(text, iconPath, x, y); targetPanel.add(button); }
调用时只需一行:
addBlueStyledButtonToPanel(" Libros", "/interfaces/images/Book.png", 33, 115, panelBlue);
内容的提问来源于stack exchange,提问作者William
相关产品推荐
相关产品推荐

