Java Swing使用ActionListener清理代码

375*_*tor 0 java swing code-cleanup actionlistener

我想在我的程序中制作更清晰的代码.所以我试图压缩我的代码来创建按钮:

以前,我需要每次复制一次:

Dimension JButton_Cryption_Size = JButton_Cryption.getPreferredSize();
        JButton_Cryption.setBounds(5, 5, JButton_Cryption_Size.width + 50, JButton_Cryption_Size.height);
        JButton_Cryption.setFocusPainted(false);

        JButton_Cryption.addActionListener(this);

        add(JButton_Cryption);
Run Code Online (Sandbox Code Playgroud)

但现在我做了这个方法:(不要注意按钮名称,它们是用于测试)

public JButton  JButton_Testing1,
                    JButton_Testing2,
                    JButton_3;

    private void addJButton(JButton ButtonName, String Name, int x, int y, int width, int height, String ToolTip, boolean FocusedPainted, boolean Opaque, boolean ContentAreaFilled, boolean BorderPainted){
        ButtonName = new JButton(Name);

        Dimension Button_Size = ButtonName.getPreferredSize();
        if(width == 0){
            ButtonName.setBounds(x, y, Button_Size.width, height);
        }if(height == 0){
            ButtonName.setBounds(x, y, width, Button_Size.height);
        }if(width == 0 && height == 0){
            ButtonName.setBounds(x, y, Button_Size.width, Button_Size.height);
        }if(width != 0 && height != 0){
            ButtonName.setBounds(x, y, width, height);
        }

        ButtonName.addActionListener(this); // class: implements ActionListener

        ButtonName.setToolTipText(ToolTip);
        ButtonName.setFocusPainted(FocusedPainted);
        ButtonName.setOpaque(Opaque);
        ButtonName.setContentAreaFilled(ContentAreaFilled);
        ButtonName.setBorderPainted(BorderPainted);

        add(ButtonName);
    }

    private void addButtonToFrame(){
        addJButton(JButton_Testing1, "Testing 1", 150, 100, 172, 0, null, false, true, true, true);
        addJButton(JButton_Testing2, "Testing 2", 0, 0, 0, 0, null, false, true, true, true);
        addJButton(JButton_Testing3, "Testing 3", 200, 150, 250, 100, "YO", false, true, true, true);

    }
Run Code Online (Sandbox Code Playgroud)

但是当我想在按钮上添加一个动作时,它就无法工作了

@Override
    public void actionPerformed(ActionEvent e){
        Object src = e.getSource();
        if(src == JButton_Testing1){
            System.out.println("yo");
        }
    }
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做我可以保留我的东西(或稍微修改它)所以我可以正确使用ActionListener

JB *_*zet 6

你的问题是干净的代码,你要求我们不要注意按钮名称.拥有干净代码的一半就是拥有好名字.尊重Java约定,并为变量和方法指定有意义的名称.变量和方法以Java中的小写字符开头.它们不包含下划线.

此外,Swing还有布局管理器.停止设置边界.使用布局管理器.

避免使用11个参数的方法.

避免拥有公共领域.字段应该是私有的.

最后,不要this用作动作监听器.使用单独的类作为您的侦听器.

关于你的问题:你的addJButton()方法没有为作为参数传递的按钮添加一个监听器.它会忽略此参数,创建一个新按钮,并将侦听器添加到此新按钮:

public void addJButton(JButton ButtonName, ...) {
    ButtonName = new JButton(Name);
Run Code Online (Sandbox Code Playgroud)

  • @ 3751_Creator一直都是练习良好实践的合适时间,然后它变成了习惯,你不需要在"模式"之间切换 (3认同)
  • 为什么测试项目使用蹩脚的名称并包含不可读的代码?为什么不使用正确的名称和编写可读代码呢?无论项目是否为测试项目,良好的名称和可读代码都可以节省时间.您的问题以"我正在尝试在我的程序中制作更清晰的代码"开头.所以这样做:尝试制作更干净的代码. (2认同)