R0nRoberts
R0nRoberts

Reputation: 1

Draw on Panel after ButtonPress

I am a bit stuck on this Problem, I am not programming a lot but I wanted to draw something on a panel in java swing (after pressing a button)

I don't know how to do it, but I found out, that I can draw on a panel on the creation of the panel ( see code) now I want something to not draw the line on creation but after I pressed a button ( so a code that I could put into my ButtonActionPerformed Method would be nice. Hope someone can help
Robert

jPanel16 = new javax.swing.JPanel() {
public void paintComponent( Graphics g ) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;

    Line2D line = new Line2D.Double(10, 100, 40, 400);
    g2.setColor(Color.blue);
    g2.setStroke(new BasicStroke(1));
    g2.draw(line);
}};

Upvotes: 0

Views: 51

Answers (1)

Prasad Karunagoda
Prasad Karunagoda

Reputation: 2148

I hope below example would show you how to achieve this.

Here, the responsibility of Drawing class is to draw a line. This line is provided by outside. So, if the line exists Drawing class draws it. Otherwise it skips drawing because there is nothing to draw.

In this example, line is given to Drawing object when user clicks the button.

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

public class DrawOnEvent {

  public static void main(String[] args) {
    Drawing drawing = new Drawing();

    JButton button = new JButton("Draw");
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        drawing.setLine(new Line2D.Double(10, 100, 80, 200));
        drawing.repaint();
      }
    });

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(drawing, BorderLayout.CENTER);
    frame.getContentPane().add(button, BorderLayout.SOUTH);
    frame.setBounds(300, 200, 400, 300);
    frame.setVisible(true);
  }
}

class Drawing extends JPanel {

  private Line2D line;

  void setLine(Line2D line) {
    this.line = line;
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (line != null) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setColor(Color.blue);
      g2.setStroke(new BasicStroke(1));
      g2.draw(line);
    }
  }
}

Upvotes: 1

Related Questions