日历GridLayout

时间:2014-04-13 03:54:55

标签: java swing user-interface layout calendar

我很难让我的标题出现在它自己的路线上。标题会在一周中显示,而不是显示标题,然后是日历中的天数。这是否缺少一个小组?我尝试过多次更改,但我无法告诉

package Exercise15_5;
import java.awt.*;
import javax.swing.*;
import java.util.*;

public class Exercise15_5 extends JFrame {
    public Exercise15_5(){
        //Create panel with gridlayout
        JPanel calendar = new JPanel(new BorderLayout());
        calendar.setLayout(new GridLayout(5,7));
        //Add headers
        String[] headers = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
        for(int i = 0; i <7; i++){
            calendar.add(new JLabel("" + headers[i]));
        }
        //Add days to calendar
        for(int i = 1; i <31; i++){
            calendar.add(new JLabel("" + i));
        }

        JPanel monthHeader = new JPanel(new BorderLayout());
        monthHeader.add(new JTextField("\t\t\t04/2014"), BorderLayout.NORTH);

        monthHeader.add(calendar, BorderLayout.CENTER);



        add(monthHeader);
    }

    public static void main(String[] args) {
        Exercise15_5 frame = new Exercise15_5();
        frame.setTitle("Exercise 15_5");
        frame.setSize(600,300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);


    }

}

2 个答案:

答案 0 :(得分:4)

尝试将面板的布局设置为new GridLayout(0,7)

GridLayout API声明如下:

  

当设置了行数和列数时   通过构造函数或setRows和非零值   setColumns方法,忽略指定的列数。   而是根据指定的数量确定列数   行和布局中的组件总数。因此对于   例如,如果指定了三行和两列,则为九行   组件添加到布局中,它们将显示为三个   三列的行。指定列数会影响   仅当行数设置为零时才进行布局。

答案 1 :(得分:2)

row计数被1关闭(但0更为一般),我还建议您稍微清理一下构造函数。也许是这样,

// Create panel with gridlayout
JPanel calendar = new JPanel(new GridLayout(6, 7)); // 6 (or 0), not 5.
// Add headers
String[] headers = { "Sunday", "Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday",
    "Saturday" };
// Use for-each loop.
for (String header : headers) {
  calendar.add(new JLabel(header));
}
// Add days to calendar, use String.valueOf
for (int i = 1; i < 31; i++) {
  calendar.add(new JLabel(String.valueOf(i)));
}

JPanel monthHeader = new JPanel(new BorderLayout());
monthHeader.add(new JTextField("\t\t\t04/2014"),
    BorderLayout.NORTH);

monthHeader.add(calendar, BorderLayout.CENTER);

add(monthHeader);