Tri Nguyen Tri Nguyen - 8 months ago 71
Java Question

Java,Swing - cannot draw lines on a JFrame

I'm trying to draw vertical lines to separate days in a week on a JFrame. The code seems fine as no error but when I run it, it output a frame like the picture below. Am I missing anything?

public class WeekToView extends JFrame{
public WeekToView(){

setTitle("Sheffield Dental Care"); //set title
Toolkit toolkit = Toolkit.getDefaultToolkit();

Dimension screenDimensions = toolkit.getScreenSize();
setLocation(new Point(screenDimensions.width*1/4, screenDimensions.height*1/4)); //set location based on screen size

JPanel container = new JPanel();
JScrollPane scrPane = new JScrollPane(container);
double size[][] = {{150, 150, 150, 150, 150}, // Columns
{100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100}}; // Rows
container.setLayout(new TableLayout(size));

String daysInWeek[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
JLabel daysInWeekLabels[] = new JLabel[daysInWeek.length];

for (int i = 0; i < daysInWeek.length; i++) {
daysInWeekLabels[i] = new JLabel(daysInWeek[i],SwingConstants.CENTER);

container.add(daysInWeekLabels[0], "0,0");
container.add(daysInWeekLabels[1], "1,0");
container.add(daysInWeekLabels[2], "2,0");
container.add(daysInWeekLabels[3], "3,0");
container.add(daysInWeekLabels[4], "4,0");

setSize(780,600); //set size based on screen size
setResizable(false); //unresizable

public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);


enter image description here

Answer Source

There is no paintComponent() method in a JFrame. Whenever you attempt to override a method you should always use @Override before the method name. You will get a compile error if you don't override the method correctly.

You could override paint() but in general don't try to do custom painting in the paint() method of a JFrame.

Instead custom painting is done by overriding the piantComponent() method of the panel that you add to the frame.

Better yet you can use a JTable, which already provides you with a row/column based component.