Reputation: 8371
I'm trying to create a custom Calendar in Java. For this I extend javax.swing.JComponent
.
public class GMCalendar extends JComponent { ... }
In my constructor I do some basic setup and load my image:
calendarDay = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/resources/images/calendar_day.png"));
And in paintComponent
it should draw my calendar, but it won't draw all, which looks very weird.
public void paintComponent(Graphics g) {
super.paintComponent(g);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, currentMonth);
int numberOfWeeks = calendar.getActualMaximum(Calendar.WEEK_OF_MONTH);
for (int i = 0; i < 7; i++) {
for (int j = 0; j < numberOfWeeks; j++) {
int x = i * (DAY_SIZE + DAY_SPACE);
int y = j * (DAY_SIZE + DAY_SPACE);
g.drawImage(calendarDay, x, y, null);
}
}
}
The result is either nothing or something like this:
It seems like paintComponent
gets called before the component has a size bigger than 1x1.
This is in my main()
:
GMContainerFrame cf = new GMContainerFrame();
cf.setMinimumSize(new Dimension(800,600));
cf.setVisible(true);
This is from the constructor of GMContainerFrame
(which doesn't use a LayoutManager
!):
calendarFrame = new GMMiniFrame("Kalender", new GMCalendar(), 230);
GMMiniFrame
extends JSplitPane
.
Upvotes: 3
Views: 161
Reputation: 109823
don't to reinvent the wheel, use JPanels
, better with JLabels
layed by GridLayout
by using JLabels
(JPanel
nesting multiple JComponents
) there no reason for paintComponents
notice JLabel
is transparent, non_opaque,
use JCalendar
/JDatePicker
from SwingX
, my favorite is JCalendar by Kai Toedter, (no issue with renderer, editor, special days, min and max Date)
Upvotes: 4