Java创建对象作为函数的参数

Yun*_*zel 2 java object

因为,我习惯于在javascript中编码,我想创建具有属性的对象.

这是我的代码:

jPanel2.add( new JPanel(){ this.add(new JButton("Add")); });
Run Code Online (Sandbox Code Playgroud)

你有什么建议吗 ?

dac*_*cwe 7

您始终可以使用以下语法:

container.add(new JPanel() {{ this.add(new JButton("Add")); }});
Run Code Online (Sandbox Code Playgroud)

完整示例:

public static void main(String[] args) throws Exception {

    JFrame frame = new JFrame("Test");

    frame.add(new JPanel() {{ this.add(new JButton("Add")); }});

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)