我很难将标题放在自己的行上。页眉显示一周中的几天,而不是显示页眉,然后在底部显示日历中的天数。这是不是少了一块面板?我尝试了多次更改,但我真的无法告诉
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("ttt04/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);
}
}
尝试将面板的布局设置为new GridLayout(0,7)
。
GridLayout API声明如下:
当同时设置了行数和列数时通过构造函数或setRows和setColumns方法,则忽略指定的列数。相反,列的数量由指定的数量确定行数和布局中组件的总数。所以,对于例如,如果指定了三行两列和九行组件被添加到布局中,它们将显示为三个三列的行。指定列数会影响仅当行数设置为零时才进行布局。
您的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("ttt04/2014"),
BorderLayout.NORTH);
monthHeader.add(calendar, BorderLayout.CENTER);
add(monthHeader);