Add JButton array to a JPanel (buttons not visible)

devamat :

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?

am9417 :

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];

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=94201&siteId=1