Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add JButton array to a JPanel (buttons not visible)

I'm trying to create a simple calculator with Java. For that purpose I created an array of JButton and added them to the JPanel.

The issue: the buttons are not visible.

I also added a single JLabel and a single JButton for testing, and they show up correctly.

The code:

package test;

import java.awt.BorderLayout;
import javax.swing.*;

public class Test {

    JLabel testLabel = new JLabel("Test label", SwingConstants.CENTER);
    JButton testButton = new JButton("Test button");

    JButton buttons[];

    Test() {

        JFrame frame = new JFrame("Calculator");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();  

        for (int i = 0; i > 15; i++) {

            buttons[i] = new JButton(Integer.toString(i));
            panel.add(buttons[i], BorderLayout.CENTER);

        }

        panel.add(testButton, BorderLayout.CENTER);
        panel.add(testLabel, BorderLayout.CENTER);

        frame.setSize(500, 500);

        frame.add(panel, BorderLayout.CENTER);

        frame.setVisible(true);
    }


    public static void main(String[] args) {

        Test cTest = new Test();

    }

}

What am I doing wrong?

like image 827
devamat Avatar asked Dec 01 '25 01:12

devamat


1 Answers

The problem is that the condition in your for loop is invalid. Replace the > with <: The statement 0 > 15 is never is never evaluated to true which is why your loop never starts iterating:

for(int i = 0; i < 15; i++)

Also you must create the array with new keyword before you assign items to it. Otherwise you will get a NullPointerException:

buttons = new JButton[15];
like image 54
am9417 Avatar answered Dec 02 '25 16:12

am9417



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!