有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JButton数组按钮不可见,除非添加了非来自数组的按钮

我有一个JButton数组,它不希望可见,除非在按钮数组的循环之前添加另一个JButton。 窗口类:

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

public class Window extends JFrame {
private Container mContainer = new Container();

public Window()
{
    super();
    this.setTitle("Calculator");
    this.setSize(200, 300);
    this.setLocationRelativeTo(null);
    this.setResizable(false);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mContainer.setBorder(null);
    mContainer.setBackground(Color.GRAY);
    mContainer.setOpaque(true);
    this.setContentPane(mContainer);

    //Panels
    JPanel panel = new JPanel();
    JPanel center = new JPanel();
    center.setBackground(Color.GRAY);
    center.setBorder(null);
    JPanel displayOutput = new JPanel();
    displayOutput.setBackground(Color.GRAY);

    this.getContentPane().add(panel);

    //TextArea
    JTextArea textArea = new JTextArea(1, 20);
    textArea.setForeground(Color.WHITE);
    textArea.setBackground(Color.GRAY);
    textArea.setPreferredSize(new Dimension(200, 60));

    //Panel Layouts
    panel.setLayout(new BorderLayout());
    center.setLayout(new GridLayout(5, 4, 2, 2));

    //Add other panel elements
    displayOutput.add(textArea);
    panel.add(displayOutput, BorderLayout.NORTH);
    panel.add(center, BorderLayout.CENTER);

    //For some reason adding this makes the array of buttons appear
    JButton btnNewButton = new JButton("1");
    center.add(btnNewButton);

    //Create buttons
    for(int i = 0; i < 20; i++){
       CalcButtons cButtons[] = new CalcButtons[20];
       cButtons[i] = new CalcButtons();
    //Add buttons to center box below output
        center.add(cButtons[i]);
    //Sets fourth column of buttons in cyan.
       if(((i + 1) % 4) == 0){
            cButtons[i].setBackground(Color.CYAN);
        }
    }

    //Add panel to window
    getContentPane().add(panel);
    this.setVisible(true);
    }
}

集装箱类别:

import java.awt.Graphics;
import javax.swing.JPanel;

public class Container extends JPanel {

    public Container() {
        super();
    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
    }
}

按钮类别:

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

public class CalcButtons extends JButton
{
    public CalcButtons()
    {
        this.setBackground(Color.WHITE);
        this.setBorder(null);
    }
}

该代码随后生成以下内容:

buttons displayed

但是,如果我删除此项:

//For some reason adding this makes the array of buttons appear
JButton btnNewButton = new JButton("1");
center.add(btnNewButton);

它产生了以下结果:

buttons not displayed


共 (1) 个答案

  1. # 1 楼答案

    问题是按钮的大小为0。您已将边框设置为null,并且没有图标或文本集。因此,当GridLayout在按钮上调用getPreferredSize()时,它们返回的大小为0,0(宽度、高度)。当您添加带有1的JButton时,一个组件突然变大了。由于Gridlayout使所有组件的大小相同,您现在可以看到您的按钮。如果希望按钮为空白,但也要绘制,请将边框设置为空白边框,每条边的大小为1或更大