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



因为我习惯了用javascript编码,所以我想创建具有属性的对象。

这是我的代码:

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

你有什么建议吗?

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

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

完整示例:

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);
}

最新更新