全窗口JButton在背景中

时间:2014-01-13 22:49:42

标签: java swing layout-manager null-layout-manager

我正在尝试用它上面的一堆Jbuttons创建一个JFrame。 40中间,4行,6个J按钮,垂直线向左下方。问题是,侧面按钮上的第五个Jbutton出现在所有其他按钮后面,占据了整个窗口。我不知道它来自何处,因为我从未将JButton的大小设置得那么大,或者适合屏幕。

import javax.swing.*;
public class Buttons {

static JButton[][] middle = new JButton [10][4]; //middle buttons
static JButton[] colours = new JButton[6]; //colour buttons


public static void main (String arg[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600,700);

    int xcor = 100; //x coordinate
    int ycor = 5; //y coordinate

    //middle buttons
    for (int y = 0; y<10; y++) {
        for (int x = 0; x<4; x++) {
            middle[y][x] = new JButton();
            middle[y][x].setBounds(xcor, ycor, 100, 60);
            middle[y][x].setVisible(true);
            frame.getContentPane().add(middle[y][x]);

            xcor+=100;
        }
        xcor=100;
        ycor+=60;
    }

    //colour buttons 
    ycor=65;
    for (int y = 0; y<5; y++){
        colours[y] = new JButton();
        colours[y].setBounds(5, ycor, 90, 60);

        switch (y) {
        case 0: colours[y].setText("Red");
        break;
        case 1: colours[y].setText("Blue");
        break;
        case 2: colours[y].setText("Green");
        break;
        case 3: colours[y].setText("Yellow");
        break;
        case 4: colours[y].setText("Purple");
        break;
        case 5: colours[y].setText("Black");
        break;
        }
        colours[y].setVisible(true);
        frame.getContentPane().add(colours[y]);

        ycor += 60;
    }
    frame.setVisible(true);
}

enter image description here

2 个答案:

答案 0 :(得分:3)

可以通过在{{1 }}。这两个面板可能会设置GridLayout,并添加到GridLayout(0,4)的{​​{1}}和JPanel

像这样:

enter image description here

EmptyBorder

答案 1 :(得分:0)

将布局设置为nullframe.setLayout(null);)可以解决此特定问题,但会引入更多问题。制作自定义LayoutManager将是更好的解决方案。