运行时在GUI上添加JPanel附加列?

时间:2013-05-15 23:50:34

标签: java swing jpanel jtextfield 2d-games

正在开展一个学校项目,在这个项目中,我和我的团队正在制作一个带有GUI的所有游戏。在显示拼图的panel时,我遇到了正在创建其他列的问题。它也可能只是空的空间,但无论如何,我想知道如何摆脱它。以下是letterBoard类的代码,它贯穿wheelGUI类。

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

 public class letterBoard extends JPanel
                            implements ActionListener                   
 {
 private JTextField[] fields = new JTextField[TEXT_FIELD_COUNT];
 private Box[] boxes = new Box[SUIT_COUNT];
 private static int TEXT_FIELD_COUNT = 14;
 private static int SUIT_COUNT = 1;
 Color datGreen=new Color(0, 180, 100);

public letterBoard()
{
    setBackground(Color.GRAY);
    JPanel panel = new JPanel(new GridLayout(4,1));
    panel.setBackground(datGreen);
    for(int t=0; t<4; t++)
    {
        for (int i =0; i < boxes.length; i++)
        {
            boxes[i] = Box.createHorizontalBox();
            for (int j=0; j< TEXT_FIELD_COUNT/SUIT_COUNT; j++)
            {
                int index = i * (TEXT_FIELD_COUNT/SUIT_COUNT) + j;
                fields[index] = new JTextField("   ");
                fields[index].setEditable(false);
                fields[index].setPreferredSize(new Dimension(50, 50));
                fields[index].setBorder(BorderFactory.createLineBorder(Color.BLACK,1));
                panel.add(fields[index]);
                panel.add(boxes[i]);
                panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK,3),"WHEEL OF FORTUNE"));
            }
        }
    }
    Box b1 = Box.createVerticalBox();
    b1.add(panel);
    b1.add(Box.createVerticalStrut(5));
    b1.add(Box.createHorizontalStrut(5));
    add(b1);
}
public void actionPerformed(ActionEvent e) 
{

}
}

任何帮助识别问题都会很棒。 Here's编辑时的样子。右边的绿色条是问题所在。谢谢!

1 个答案:

答案 0 :(得分:3)

也许我只是错过了重点,但我认为不需要所有Box属性......

我只是将GridLayout修改为布局14列作为行的优先级,并删除了所有Box内容......

enter image description here

public LetterBoard() {
    setBackground(Color.GRAY);
    JPanel panel = new JPanel(new GridLayout(0, 14));
    panel.setBackground(datGreen);
    for (int t = 0; t < 4; t++) {
        for (int i = 0; i < boxes.length; i++) {
            for (int j = 0; j < TEXT_FIELD_COUNT / SUIT_COUNT; j++) {
                int index = i * (TEXT_FIELD_COUNT / SUIT_COUNT) + j;
                fields[index] = new JTextField("   ");
                fields[index].setEditable(false);
                fields[index].setPreferredSize(new Dimension(50, 50));
                fields[index].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                panel.add(fields[index]);
            }
        }
    }
    panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 3), "WHEEL OF FORTUNE"));
    add(panel);
}

所有Box内容都在每行末尾添加了一个额外的“列”...