import javax.swing.*; import java.awt.*; public class DrawLineExample extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawLine(0, 0, 100, 100); } public static void main(String[] args) { JFrame frame = new JFrame("Draw Line Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 500); DrawLineExample panel = new DrawLineExample(); frame.add(panel); frame.setVisible(true); } }
import javax.swing.*; import java.awt.*; public class DrawLinesExample extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.drawLine(50, 50, 150, 50); g.setColor(Color.BLUE); g.drawLine(50, 100, 150, 100); g.setColor(Color.GREEN); g.drawLine(50, 150, 150, 150); } public static void main(String[] args) { JFrame frame = new JFrame("Draw Lines Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 500); DrawLinesExample panel = new DrawLinesExample(); frame.add(panel); frame.setVisible(true); } }In this example, we create a custom JPanel class called DrawLinesExample that overrides the paintComponent method to draw three horizontal lines on the panel using different colors. We use g.setColor to set the color for each line, and then call g.drawLine with the appropriate starting and ending points for each line. We then create a JFrame and add an instance of our DrawLinesExample panel to it. Package library: java.awt