devamat
devamat

Reputation: 2503

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?

Upvotes: 3

Views: 502

Answers (3)

M'aiq the Coder
M'aiq the Coder

Reputation: 812

Usually when you use a for loop you have to initialise your objects for every single loop. If you have a TextView for example, you'll have to do:

TextHeaders[i] = new TextView([activity_name].this);

For your problem,

buttons[i] = new JButton (this);

Upvotes: 0

am9417
am9417

Reputation: 1036

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

Upvotes: 2

Dimitrije Milenkovic
Dimitrije Milenkovic

Reputation: 53

First, I think that your for loop should like like this

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

And after that, in you have to initialize your buttons reference

JButton buttons[] = new JButton[15];

Upvotes: 2

Related Questions