我正在使用Swing创建日历组件,但遇到了一些麻烦。
我希望组件能够更改不同视图的列数,但对于GridBagLayout来说这似乎很简单。
问题是让GBL显示一个行和列可能为空的网格。我试过了,但不能这样做。有什么方法可以做到这一点,或者另一种简单的方法是最终能够将面板放置在网格上的某些位置,例如:
我有一个名为PanelCalendarWeek的类,它扩展了JPanel。为简洁起见,省略了一些代码。代码如下,以下链接是其输出的图片。
public PanelCalendarWeek() {
/* This panel holds the date */
innerPanel = new JPanel();
innerPanel.setBackground(Color.BLACK);
innerPanel.setBounds(0, 0, 700, 700);
innerPanel.setPreferredSize(new Dimension(700, 700));
innerPanel.setLayout(new GridBagLayout());
/* Create Grid bag containts for the BLACK area */
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_END;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
/* Add example panels that would be dates */
JPanel panel1 = new JPanel();
panel1.setBorder(BorderFactory.createLineBorder(Color.WHITE, 2));
panel1.setPreferredSize(new Dimension(1, 200));
panel1.setBackground(Color.BLUE);
innerPanel.add(panel1, c);
/* Create more components in the manner above for example reasons */
this.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
innerPanel.setBounds(0, 0, columnView.getWidth(), 1000);
innerPanel.setPreferredSize(new Dimension(columnView.getWidth(), 1000));
} // more code omitted for brevitu
});
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getViewport().setLayout(null);
scrollPane.setViewportView(innerPanel);
scrollPane.setBounds(0, 0, 400, 400);
columnView = new JPanel();
columnView.setBackground(Color.RED);
columnView.setBounds(0, 0, 200, 50);
columnView.setPreferredSize(new Dimension(200, 50));
scrollPane.setColumnHeaderView(columnView);
rowView = new JPanel(); /* omitted, same process as above */
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
}