2

Since, I get used to code in javascript, I want to create objects with properties.

Here is my code:

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

Do you have any suggestions ?

2
  • 2
    jPanel2.add( new JPanel("Text")); Commented May 22, 2012 at 13:27
  • i want to add a JPanel, which has a button, inside jPanel2 Commented May 22, 2012 at 13:29

1 Answer 1

6

You can always use this syntax:

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

Full example:

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Field initializer in anonymous class body?? Genius!!
@DavidB I wouldn't say that it's unreadable, sometimes it's really neat! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.