How to Draw a Line on a JPanel in Java When a Button is Clicked

Question

How can I draw a line on a JPanel using a button click in Java?

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

public class LineDrawer extends JPanel {
    private int x1 = 0, y1 = 0, x2 = 100, y2 = 100;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawLine(x1, y1, x2, y2);
    }

    public void drawLine() {
        // Update line coordinates
        x2 += 10;
        y2 += 10;
        repaint();  // Redraw the JPanel
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Line Drawer");
        LineDrawer panel = new LineDrawer();
        JButton button = new JButton("Draw Line");

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel.drawLine();
            }
        });

        frame.add(panel, BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Answer

In Java, drawing on a JPanel in response to user actions such as button clicks involves overriding the appropriate painting methods and handling events. This guide demonstrates how to draw a line on a JPanel, updating the line's position with each button press.

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

public class LineDrawer extends JPanel {
    private int x1 = 0, y1 = 0, x2 = 100, y2 = 100;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawLine(x1, y1, x2, y2);
    }

    public void drawLine() {
        // Update line coordinates
        x2 += 10;
        y2 += 10;
        repaint();  // Redraw the JPanel
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Line Drawer");
        LineDrawer panel = new LineDrawer();
        JButton button = new JButton("Draw Line");

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel.drawLine();
            }
        });

        frame.add(panel, BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Causes

  • Understanding how to respond to button click events in Java.
  • Properly overriding the paintComponent method in a JPanel to handle custom drawing.

Solutions

  • Create a custom JPanel class that overrides paintComponent.
  • Use a JButton to trigger repainting and change line attributes.
  • Manage line coordinates to be flexible and responsive to button actions.

Common Mistakes

Mistake: Not calling repaint() after updating line coordinates.

Solution: Always call repaint() within the method that updates the line attributes to ensure the JPanel is redrawn.

Mistake: Forgetting to initialize JFrame properties before setting it visible.

Solution: Ensure that you set the size, default close operation, and visibility of the JFrame in the correct order.

Helpers

  • Java JPanel drawing
  • Java draw line button click
  • Java GUI programming
  • JPanel paintComponent
  • Drawing in Java Swing

Related Questions

⦿What is the Difference Between Date and Date-Time Fields in Swagger?

Understand the distinctions between date and datetime fields in Swagger for effective API documentation.

⦿How to Use Java 8 Lambda Expressions for Conditional Filtering and Ordering

Learn how to leverage Java 8 lambda expressions to filter data based on conditions and order it effectively. Stepbystep guide with examples.

⦿How to Mock a Void Method to Throw an Exception in Java?

Learn how to effectively mock void methods in Java to throw exceptions using Mockito with detailed explanations and code snippets.

⦿How to Locate the lib Directory for Unmanaged JARs in an SBT Directory Structure

Learn how to find the lib directory for unmanaged JAR files in the SBT directory structure and how to manage dependencies effectively.

⦿How to Use Retrofit and Jackson for JSON Parsing in Android Development

Learn how to effectively integrate Retrofit with Jackson for parsing JSON in your Android applications. Stepbystep guide included.

⦿How Many Java String Objects Are Created with the Code: String s="abc" + "xyz"?

Discover how many String objects are created in Java when using string concatenation. Understand String Interning and performance implications.

⦿Why Did Google Select Java as the Primary Language for the Android Operating System?

Explore the reasons Google chose Java for Android OS including its benefits and implications for developers.

⦿What is the Difference Between Multi-Module POM and Java Module System?

Discover the differences between multimodule POM projects and the Java module system. Explore their benefits features and use cases.

⦿How to Resolve No Code Coverage Issue in IntelliJ IDEA 2017

Learn how to fix the no code coverage issue in IntelliJ IDEA 2017 with our comprehensive guide including solutions and tips.

⦿How Can I Implement a Ribbon UI Component Similar to Office 2007 in a Java Application?

Learn how to create a Ribbon UI component in Java similar to Office 2007 with detailed steps and code snippets.

© Copyright 2025 - CodingTechRoom.com