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

时间:2016-10-31 12:27:06

标签: java arrays swing

我有一个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 个答案:

答案 0 :(得分:0)

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