简体   繁体   中英

How do I use a separate method to call the paint component method and draw a rectangle?

I am using Swing to create a GUI which would draw a new rectangle every time a method runs. I want to use variables that would get incremented and continue making new rectangles in a series. My goal is to give a visual representation of a linked list and to emphasize on the concept that a linked list has a head which points to the next item which points to the next and so on.

I am a beginner with basic knowledge of Java, and I'm just getting started with Swing and creating User interfaces.

void insert(int i, int j) {
    //some code which would create a new rectangle and add to my GUI.
}

// this is my panel class
public class MyPanel extends JPanel{
    MyPanel() {
        this.setPreferredSize(new Dimension(500, 500)); 
    }

    public void paint(Graphics g) {
        Graphics2D g2D = (Graphics2D) g;
        g2D.setPaint(Color.blue);
        g2D.setStroke(new BasicStroke(5));
        g2D.drawRect(i, j, 100, 50);    
    }
}

What you can do:

  1. Create a list to store the passed arguments to the insert(int,int) method
  2. Fill that list in the insert(int,int) method
  3. the paintComponents() -method can loop over the saved values and display them
// records are fairly new to Java. See (*) for what it does
private record Tuple(int i, int j) {}

// this list contains values added by the `insert(int, int)` method
private final List<Tuple> tuples = new ArrayList<>();

private void insert(final int i, final int j) {
    // do some stuff
    // ...

    // save passed values to a list using the helper class "Tuple"
    this.tuples.add(new Tuple(i, j));

    // repaint UI
    this.repaint();
}

@Override
public void paintComponents(final Graphics g) {
    super.paintComponents(g);
    // loop over saved values and do something with their values
    for (final Tuple tuple : this.tuples) {
        // draw rect for saved tuple
        g.drawRect(tuple.i * 10, tuple.j * 10, 20, 20);
    }
}

(*) records were introduced in Java 14 and they can be used to create data classes in a short way.

They automatically generate Getters, the equals() , hashCode() and toString() -method.

For this example, the record could be be rewritten to:

private class Tuple {
  private final int i;
  private final int j;

  public Tuple(final int i, final int j) {
    this.i = i;
    this.j = j;
  }
}

(we don't need equals() , hashCode() and toString() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM