[SOLVED] It won't draw the line


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Game4 extends JPanel {
  public Game4() {

  public void paint(Graphics g) {
    Graphics2D twoD = (Graphics2D) g; 

  public void boxes(Graphics2D twoD) {
    twoD.drawLine(getWidth() / 3, 0, getWidth() / 3, getHeight());

For some reason, I can’t get this code to draw out. I’m not that good with Graphics2D so if I could get some help that would be great.


Start by taking a look at Painting in AWT and Swing and Performing Custom Painting for more details on how painting works in Swing.

paint does a lot of really important work, like setting the default color of the Graphics context based on the components foreground color, filling the background, setting the clip, etc.

Unless you’re really willing to take over ALL the control, you’re best to avoid it. Instead, prefer using paintComponent.

You may also need to supply some basic sizing hints for the component and in order to be shown on the screen the component will need to be added to some kind of window (ie JFrame)

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());

    public class TestPane extends JPanel {
        public TestPane() {

        public Dimension getPreferredSize() {
            return new Dimension(200, 200);

        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g.create();

        protected void boxes(Graphics2D twoD) {
            twoD.drawLine(getWidth() / 3, 0, getWidth() / 3, getHeight());


Answered By – MadProgrammer

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *