I'm having a little trouble trying to nest two component classes (both extend JComponent) together. When I create the frame in my tester file, instantiate each class, and try to add both of them to the frame, it doesn't come out correctly. For instance, I want my frame to display the TimeComponent right next to the DayComponent in this program:
Tester.java
import java.awt.*;
import javax.swing.*;
public class DayTester
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
TimeComponent time = new TimeComponent();
DayComponent day = new DayComponent();
frame.add(time);
frame.add(day);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setVisible(true);
}
private static final int FRAME_WIDTH = 1000;
private static final int FRAME_HEIGHT = 1000;
}
TimeComponent.java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class TimeComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Rectangle rect = new Rectangle(0, 0, 50, 25);
g2.drawString("Time", (int)rect.getWidth() / 4, (int)rect.getHeight());
g2.draw(rect);
String time = null;
for (int i = 0; i < 24; i++)
{
if (i == 0)
time = Integer.toString(12) + " AM";
else if (i > 0 && i < 12)
time = Integer.toString(i) + " AM";
else if (i == 12)
time = Integer.toString(12) + " PM";
else
time = Integer.toString(i - 12) + " PM";
rect.translate(0, (int)rect.getHeight());
g2.drawString(time, (int)(rect.getX() + rect.getWidth() / 4), (int)(rect.getY() + rect.getHeight()));
g2.draw(rect);
}
}
}
DayComponent.java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class DayComponent extends JComponent
{
public DayComponent()
{
events = new String[10];
events[0] = "Soccer";
events[9] = "Piano";
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Rectangle rect = new Rectangle(50, 0, 200, 25);
rect.translate(0, (int)rect.getHeight());
g2.drawString(events[0], (int)(rect.getX() + rect.getWidth() / 4), (int)(rect.getY() + rect.getHeight()));
g2.draw(rect);
}
private String[] events;
}