3

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?

2
  • 1
    Note that the default layout manager of a JPanel is FlowLayout , not BorderLayout . Commented Jul 16, 2018 at 9:54
  • 1
    Note2: if the layout manager of the panel was set to BorderLayout, you still would only see the last component since all are being added with BorderLayout.CENTER Commented Jul 16, 2018 at 10:05

3 Answers 3

2

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

Comments

2

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

Comments

0

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

Comments

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.