Java Graphics Programming Example
Here's a simple example of graphics programming in Java using the Java Swing library:
javaimport javax.swing.*;
import java.awt.*;
public class MyPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Set background color
this.setBackground(Color.WHITE);
// Draw a rectangle
g.setColor(Color.BLUE);
g.fillRect(10, 10, 100, 100);
// Draw a circle
g.setColor(Color.RED);
g.fillOval(120, 10, 100, 100);
// Draw a line
g.setColor(Color.GREEN);
g.drawLine(10, 120, 220, 120);
}
public static void main(String[] args)
{ JFrame frame = new JFrame("My Graphics");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 250);
MyPanel panel = new MyPanel();
frame.add(panel);
frame.setVisible(true);
}
}
In this example, we create a custom JPanel named MyPanel that overrides the paintComponent method to draw some simple shapes (a rectangle, circle, and line) using the Graphics object. We also set the background color of the panel to white.
In the main method, we create a JFrame and add an instance of our MyPanel to it. We set the title of the frame, its size, and make it visible. When we run the program, we should see a window with the shapes drawn on a white background.
Comments
Post a Comment