Tri Nguyen Tri Nguyen - 21 days ago 7
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);
getContentPane().add(scrPane);
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
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false); //unresizable
setVisible(true);
}

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

g2.drawLine(getWidth()/5,0,getWidth()/5,getHeight());
g2.drawLine(getWidth()*2/5,0,getWidth()*2/5,getHeight());
g2.drawLine(getWidth()*3/5,0,getWidth()*3/5,getHeight());
g2.drawLine(getWidth()*4/5,0,getWidth()*5/5,getHeight());
}
}


enter image description here

Answer

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.