Search code examples
javaswingjbutton

how to make JButtons in java with less code?


I am creating a program for a personal project and I ended up creating many JButtons, which are taking up quite bit of lines in the project, is it possible to reduce the amount of lines that still produces that same amount of JButton?

JButton button1 = new JButton("Empty"); 
JButton button2 = new JButton("Empty"); 
JButton button3 = new JButton("Empty"); 
JButton button4 = new JButton("Empty"); 
JButton button5 = new JButton("Empty"); 
JButton button6 = new JButton("Empty"); 
JButton button7 = new JButton("Empty"); 
JButton button8 = new JButton("Empty"); 
JButton button9 = new JButton("Empty"); 
JButton button10 = new JButton("Empty"); 
JButton button11 = new JButton("Empty"); 
and about 5 more

Solution

  • For repetitive tasks with similar functionality, I like to use methods. Most of the time it will make the code cleaner. It won't shorten the current code you have, but after you add listener or anything else you may want to add, it will. You can pass any number of variables you want to it.

    public JButton createButton(String name, Color color) {
        JButton button = new JButton(name);
        button.setForeground(color);
        button.addActionListener(listener);
        return button;
    }
    

    Then you can just call it a bunch of times like

    JButton button = createButton("Hello", Color.BLUE);
    

    Overall though it's really a case by case basis on how you create your components. If you concern is really to shorten your code. You can always use loops, and some data structure for your the names

    String[] names = { "Hey", "Ya", "Yada" };
    JButton[] buttons = new JButton[names.lenght];
    for (int i = 0; i < buttons.length; i++) {
        buttons[i] = createButton(names[i], Color.BLUE);
    } 
    

    Maybe even look at some of the answers from this question