我正在尝试使用Swing在Java中创建日历界面,类似于Google日历中的每周视图,如下所示:
https://github.com/json-ld/json-ld.org/issues/311
这是我到目前为止创建的日历的图像:
目前我已经创建了一个名为GridPanel的类,它只是一个JPanel容器,用于填充日历的列标题,行标题或单元格。
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
public class GridPanel extends JPanel {
private JLabel label;
public GridPanel() {
setupPanel();
}
public GridPanel(String text) {
setupPanel();
label = new JLabel(text);
this.add(label);
}
public void setupPanel() {
this.setBorder(new BevelBorder(BevelBorder.RAISED));
this.setPreferredSize(new Dimension(100, 50));
}
public JPanel getGridPanel() {
return this;
}
}
日历和行标题的单元格添加到名为“CalendarPanel”的类中。
import javax.swing.*;
import java.awt.*;
public class CalendarPanel extends JPanel {
private JPanel hoursPanel, rowHeaderPanel;
private String[] hours = {"00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00",
"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00",
"22:00", "23:00", };
public CalendarPanel() {
this.setLayout(new BorderLayout());
hoursPanel = new JPanel(new GridLayout(24, 7));
addHourPanels();
this.add(hoursPanel, BorderLayout.CENTER);
rowHeader();
}
public void addHourPanels() {
for(int i = 0; i < 168; i++) {
hoursPanel.add(new GridPanel());
}
}
public void rowHeader() {
rowHeaderPanel = new JPanel(new GridLayout(24, 1));
for(int i = 0; i < hours.length; i++) {
rowHeaderPanel.add(new GridPanel(hours[i]));
}
this.add(rowHeaderPanel, BorderLayout.WEST);
}
}
最后,列标题会单独添加,因此无论用户是否向下滚动,它们都会保持可见状态。
import javax.swing.*;
import java.awt.*;
public class ColumnHeaderPanel extends JPanel {
private String[] days = {"", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
private GridPanel endPanel;
public ColumnHeaderPanel() {
this.setLayout(new GridLayout(1, 8));
for(int i = 0; i < days.length; i++) {
this.add(new GridPanel(days[i]));
}
}
}
主要课程:
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
private JScrollPane scrollPane;
public Main() {
super("Calendar");
this.setSize(new Dimension(834, 591));
this.setLayout(new BorderLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
CalendarPanel calendarPanel = new CalendarPanel();
// this.add(calendarPanel);
scrollPane = new JScrollPane(calendarPanel);
this.add(scrollPane, BorderLayout.CENTER);
this.add(new ColumnHeaderPanel(), BorderLayout.NORTH);
setVisible(true);
}
public static void main(String args[]) {
Main test = new Main();
}
}
如初始图片所示,JScrollPane导致GridPanel上标记为“Sunday”的对齐问题。另外,我不得不在JFrame上使用setSize,就像用户调整窗口大小一样,所有面板对齐都搞砸了。解决这些问题的最佳方法是什么?