如何在 java 的一行中创建一个自存在的按钮?

How to create a selfexisting button in one line in java?

如何创建:

JButton b = new JButton("text").addActionListener(e -> classX.addNewTest()));
buttons.add(b);

在一行中?我试过这个:

panel.add(b = new JButton("text").addActionListener(e -> classX.addNewTest()));

但是如果不创建 "b" 怎么办呢?

如果我没记错的话一条线是不可能的

为什么?

因为有不同的类型所以例如: jButton.addActionListener(Action) 不要 return 任何东西 void 所以你不能将 void 类型添加到采用 JButton 类型的列表中。

你会得到这个错误:'void' type not allowed heretype-mismatch-cannot convert typeX to typeY

What is "Type mismatch" and how do I fix it?

希望对您有所帮助。

如果你真的想在一行中做到这一点,你可以扩展 JButton class 并在实例初始化器中添加侦听器:

    panel.add(new JButton("text") {{ addActionListener(e -> classX.addNewTest()); }} );

不推荐 这样做:它很难理解,几乎是代码混淆,而且它创建了 JButton 的子class 而没有真正扩展它的完全没有功能。参见 What is Double Brace initialization

更好的方法可能是编写一个方法来创建按钮 - 我对大多数组件都这样做:

    panel.add(createJButton("test", e -> classX.addNewTest()));

...

private JButton createJButton(String text, ActionListener listener) {
    JButton button = new JButton(text);
    button.addActionListener(listener);
    // more customization if needed
    return button;
}

您还可以查看 Action:

    JButton b;
    new JPanel().add(b=new JButton(new AbstractAction("Click Me"){
        @Override
        public void actionPerformed(ActionEvent e){
            //
        }
    }));