简体   繁体   中英

Why can't I add buttons to my GridLayout JPanel?

I am trying to add 24 JButtons to the GridLayout of my JPanel buttonPanel , but when I run it, I see that no buttons are added. (At least, they are not visible.). I tried giving the buttonPanel a background color, and it was visible. Does anyone know what I'm doing wrong?

This is my code (there is an other class):

package com.Egg;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;



public class NormalCalc implements ActionListener {
    static JPanel normalCalcPanel = new JPanel();
    JPanel buttonPanel = new JPanel(new GridLayout(6,4,10,10));
    Font font = new Font("Monospaced Bold", Font.BOLD, 18);
    
    JButton powB = new JButton("^");
    JButton sqrtB = new JButton("sqrt(");
    JButton hOpenB = new JButton("(");
    JButton hCloseB = new JButton(")");
    JButton delB = new JButton("DEL");
    JButton acB = new JButton("AC");
    JButton mulB = new JButton("*");
    JButton divB = new JButton("/");
    JButton addB = new JButton("+"); 
    JButton minB = new JButton("-");
    JButton decB = new JButton(".");
    JButton equB = new JButton("=");
    JButton negB = new JButton("(-)");
    
    JButton[] numberButtons = new JButton[10];
    JButton[] functionButtons = new JButton[13];

    
    
    public NormalCalc() {
        functionButtons[0] = powB;
        functionButtons[1] = delB;
        functionButtons[2] = acB;
        functionButtons[3] = sqrtB;
        functionButtons[4] = mulB;
        functionButtons[5] = divB;
        functionButtons[6] = hOpenB;
        functionButtons[7] = addB;
        functionButtons[8] = minB;
        functionButtons[9] = hCloseB;
        functionButtons[10] = decB;
        functionButtons[11] = negB;
        functionButtons[12] = equB;
        
        
        for (int i=0; i<10; i++) {
            numberButtons[i] = new JButton(String.valueOf(i));
            numberButtons[i].setFocusable(false);
            numberButtons[i].setFont(font);
            numberButtons[i].addActionListener(this);
        }
        for (int i=0; i <13; i++) {
            functionButtons[i].setFocusable(false);
            functionButtons[i].setFont(font);
            functionButtons[i].addActionListener(this);
        }
        normalCalcPanel.setBounds(0, 0, 500, 700);
        
        buttonPanel.setBounds(50, 200, 400, 400);
        

        // Adding the buttons;
        buttonPanel.add(functionButtons[0]);
        buttonPanel.add(numberButtons[7]);
        buttonPanel.add(numberButtons[8]);
        buttonPanel.add(numberButtons[9]);
        buttonPanel.add(functionButtons[1]);
        buttonPanel.add(functionButtons[2]);
        buttonPanel.add(functionButtons[3]);
        buttonPanel.add(numberButtons[4]);
        buttonPanel.add(numberButtons[5]);
        buttonPanel.add(numberButtons[6]);
        buttonPanel.add(functionButtons[4]);
        buttonPanel.add(functionButtons[5]);
        buttonPanel.add(functionButtons[6]);
        buttonPanel.add(numberButtons[1]);
        buttonPanel.add(numberButtons[2]);
        buttonPanel.add(numberButtons[3]);
        buttonPanel.add(functionButtons[7]);
        buttonPanel.add(functionButtons[8]);
        buttonPanel.add(functionButtons[9]);
        buttonPanel.add(numberButtons[0]);
        buttonPanel.add(functionButtons[10]);
        buttonPanel.add(functionButtons[11]);
        buttonPanel.add(functionButtons[12]);
        
        buttonPanel.repaint();
        
        normalCalcPanel.add(buttonPanel);
        normalCalcPanel.add(MainMath.exitButton);
        
        MainMath.frame.add(normalCalcPanel);
        MainMath.frame.repaint();
    }



    @Override
    public void actionPerformed(ActionEvent e) {
        
        
    }
}

Other (main) class:

package com.Egg;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class MainMath implements ActionListener {

    static JFrame frame = new JFrame("Math Tools");
    static JButton exitButton = new JButton("Exit");

    JPanel mainPanel = new JPanel();
    JLabel mainLabel = new JLabel("Select your tool.", SwingConstants.CENTER);


    JButton nB = new JButton("Normal Calc.");
    JButton tB = new JButton("Right Triangle Calc.");
    JButton eB = new JButton("Equations Calc.");



public MainMath() { 
    frame.setBounds(300, 300, 500, 700);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(null);
    frame.setResizable(false);
    
    mainPanel.setLayout(null);
    mainPanel.setBounds(0, 0, 500, 700);
    
    mainLabel.setBounds(100, 25, 300, 50);
    mainLabel.setFont(new Font("Monospaced Bold", Font.BOLD, 18));
    
    nB.setBounds(100, 100, 300, 40);
    tB.setBounds(100, 150, 300, 40);
    eB.setBounds(100, 200, 300, 40);
    nB.setFocusable(false);
    tB.setFocusable(false);
    eB.setFocusable(false);
    nB.addActionListener(this);
    tB.addActionListener(this);
    eB.addActionListener(this);
    
    mainPanel.add(mainLabel);
    mainPanel.add(nB);
    mainPanel.add(tB);
    mainPanel.add(eB);
    frame.add(mainPanel);
    frame.setVisible(true);
    
    exitButton.setBounds(16, 10, 80, 35);
    exitButton.setFocusable(false);
    exitButton.addActionListener(this);
    
}
public static void main(String[] args) {
    new MainMath();
    
    System.out.println("");
    
}

public void setMainScreen() {
    frame.remove(exitButton);
    
    frame.remove(NormalCalc.normalCalcPanel);
    frame.add(mainPanel);
    frame.repaint();
}

public static JFrame getFrame() {
    return frame;
}





@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == exitButton) 
        setMainScreen();
    
    if (e.getSource() == nB) {
        frame.remove(mainPanel);
        new NormalCalc();
    }
    if (e.getSource() == tB)
        new TriangleCalc();
    if (e.getSource() == eB)
        new EquationCalc();
}

}

I see multiple issues in your code:

  1. Your arrangement of your buttons is weird looking at first glance.

  2. normalCalcPanel is static , why? It should never be

  3. setBounds(...) when using layout managers, those statements are ignored, so no need for them

  4. repaint() unless you've added / removed any element AFTER you've displayed your GUI, these calls are unnecessary, and should come with revalidate() as well.

  5. MainMath.exitButton another static component, STOP

  6. MainMath.frame.add(normalCalcPanel) implies that your JFrame called frame is static as well, which again, shouldn't be

And (I'm gonna guess here) more than probably you're creating a second instance inside MainMath , but because we don't have the code from that class we don't know what's going on

I ran your code and it looks ok, so that's why I believe your MainMath is creating another instance of JFrame

在此处输入图像描述

Here's an example of a calculator arrangement, that should help you to structure your code similarly, not the GUI but the components and classes


Edit

Okay, I understand now that I should not use static things, but how can I add a panel to a frame which I created in another class? I used 'static', because it seemed to work

Let's make an analogy for this case, imagine that your JFrame is a book, and that your JPanel s are the sheets of that book, when you write on those sheets, you don't add / paste the book to the sheets, you add the sheets to the book.

So, in this case it's the same, your main class should create the JPanels and add those to your JFrame , your JPanel classes shouldn't have knowledge of your JFrame

In the case of the book, your sheets don't need to know to which book the belong, you know that and the book knows which sheets belong to it, not viceversa.

I made an example to show you what I mean by this, I didn't recreate your GUI but made it as simple as I could for you to get the idea:

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class AnotherCalculator {
    private JFrame frame;
    private CalculatorPanel calculatorPanel;
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new AnotherCalculator()::createAndShowGUI);
    }
    
    private void createAndShowGUI() {
        frame = new JFrame(getClass().getSimpleName());
        calculatorPanel = new CalculatorPanel();
        
        frame.add(calculatorPanel);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

class CalculatorPanel extends JPanel {
    private String[] operations = {"+", "-", "*", "/", "DEL", "AC", "(", ")", "-", "^", "SQRT", ".", "+/-", "="};
    private static final int NUMBER_OF_DIGITS = 10;
    
    private JButton[] buttons;
    
    public CalculatorPanel() {
        this.setLayout(new GridLayout(0, 4, 5, 5));
        
        buttons = new JButton[operations.length + NUMBER_OF_DIGITS];
        for (int i = 0; i < buttons.length; i++) {
            if (i < NUMBER_OF_DIGITS) {
                buttons[i] = new JButton(String.valueOf(i));
            } else {
                buttons[i] = new JButton(operations[i - NUMBER_OF_DIGITS]);
            }
            this.add(buttons[i]);
        }
    }
}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM