Wednesday, July 2, 2008

A Most Basic Graphics App

Here's a simple graphics application in Java. It's about as simple as you can get while doing graphics.


// Import the basic graphics classes.
import java.awt.*;
import javax.swing.*;

public class BasicPanel extends JPanel{

// Create a constructor method
public BasicPanel(){
super();
}

public void paintComponent(Graphics g){
g.drawLine(10,10,150,150); // Draw a line from (10,10) to (150,150)
}

public static void main(String arg[]){
JFrame frame = new JFrame("BasicPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);

BasicPanel panel = new BasicPanel();
frame.setContentPane(panel);
frame.setVisible(true);
}
}

Key points to note:
The line that reads g.drawLine(10,10,150,150); // Draw a line from (10,10) to (150,150) is the line that does the actual drawing. If you want to draw something else, or draw more things, replace this line with your own statements or add additional statements after this line. To see what you can do, check out the Graphics class in the Java API reference.

All of the items in blue,BasicPanel, need to match. You can just as well make it Foodle, but all of these need to match since this is the name of your class (and program.) Note that if you change it to Foodle, you need to save it in a file called Foodle.java, just as the file above needs to be saved in a file named BasicPanel.java

If you want to change the size of the window, change the 200,200 in the line reading frame.setSize(200,200); to some other number. Smaller numbers will make a smaller window, bigger numbers make a bigger window. The first number is how many pixels across it will be, the second number is how many pixels high it is.

Enjoy!

Technorati Profile
StumbleUpon