Paul Samsotha
Paul Samsotha

Reputation: 208944

How to make JPanel sizes relative to JFrame size

Im pretty new to Java (and programming). Trying to figure out how to make Jpanel sizes relative to the JFrame size. I'm just trying to create a calendar and I have three different panels: one for the month title; one for the days of the week; and another for the calendar body.

Here's my code:

public DisplayACalendar() {
    setLayout(new GridLayout(3, 1));
    
    // create JPanel for month/year
    JPanel monthTitle = new JPanel();
    monthTitle.add(new JLabel(month + " " + year));
    
    // create JPanel for Days of Week
    String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday",
                     "Thursday", "Friday", "Saturday"};
    JPanel daysOfWeekPanel = new JPanel(new GridLayout(1, 7));
    for (int i = 0; i < 7; i++) {
        daysOfWeekPanel.add(new JLabel(days[i]));
    }
    
    // Create JPanel for calendar dates
    JPanel calendarMonth = new JPanel(new GridLayout(6, 7));
    for (int i = 1; i < firstDay; i++) 
        calendarMonth.add(new JLabel());
    for (int i = 1; i <= daysInMonth; i++) {
        JLabel jlblDayCell = new DayCell(i);
        jlblDayCell.setHorizontalAlignment(JLabel.RIGHT);
        calendarMonth.add(jlblDayCell);
    }
    int daysLeft = 42 - daysInMonth - firstDay;
    for (int i = 0; i < daysLeft; i++)
        calendarMonth.add(new JLabel());
    
    add(monthTitle);
    add(daysOfWeekPanel);
    add(calendarMonth);
    
}

And here's the Result:

JFrame Calendar
(source: staticflickr.com)

How do I fix this? For example, let's say I want to make the body panel 80% of the frame and the other two 10% each.

Upvotes: 1

Views: 2824

Answers (2)

Darryl Gerrow
Darryl Gerrow

Reputation: 167

Instead of GridLayout, which sizes each row/column exactly the same, take a look at GridBagLayout as an alternative. It's a bit bulkier, but you may enjoy more control over your component sizing.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Don't worry about percents but instead create components that fit right according to their sizes and the sizes of their text. Using an appropriate combination of layout managers will easily allow you to do this. For instance the overall layout could be BorderLayout with the calender placed BorderLayout.CENTER. The top two components could be placed in a JPanel that uses BoxLayout, and it can be placed into the main JPanel BorderLayout.PAGE_START.

If you absolutely need to use percents, then you may have to create your own layout manager which may be a little tricky at your stage, but again if absolutely needed, is not too terribly difficult.

Also as trashgod notes, consider just using a tool built for this exact purpose, JCalendar.

Upvotes: 4

Related Questions