Question
How can I draw multiple lines using Java Swing?
import javax.swing.*;
import java.awt.*;
public class MultiLineDrawing extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
for (int i = 0; i < 10; i++) {
g2d.drawLine(10, 10 + i * 10, 200, 10 + i * 10);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Multiple Lines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new MultiLineDrawing());
frame.setVisible(true);
}
}
Answer
Drawing multiple lines in Java Swing can be achieved using the `Graphics` or `Graphics2D` class within a custom `JPanel`. By overriding the `paintComponent` method, you can execute custom drawing logic to create multiple lines dynamically based on your requirements.
import javax.swing.*;
import java.awt.*;
public class MultiLineDrawing extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
for (int i = 0; i < 10; i++) {
g2d.drawLine(10, 10 + i * 10, 200, 10 + i * 10);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Multiple Lines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new MultiLineDrawing());
frame.setVisible(true);
}
}
Causes
- Not overriding the `paintComponent` method in a JPanel.
- Improper use of the Graphics context which can lead to unexpected results.
Solutions
- Use a `JPanel` and override the `paintComponent` method for custom drawings.
- Use a loop to manage the drawing of multiple lines spatially on the panel.
Common Mistakes
Mistake: Forgetting to call super.paintComponent(g) in the overridden method.
Solution: Always call the superclass method to ensure proper rendering.
Mistake: Using fixed coordinates without proper scaling
Solution: Use relative positioning or calculate positions dynamically.
Helpers
- Java Swing
- Draw lines Java
- Java graphics drawing
- Swing JPanel
- Graphics Java tutorial