Our first drawing application simply draws two lines. Class DrawPanel (Fig. 4.18)performs the actual drawing, while class DrawPanelTest (Fig. 4.19) creates a window to display the drawing. In class DrawPanel, the import statements in lines 3–4 allow us to use
class Graphics (from package java.awt), which provides various methods for drawing
text and shapes onto the screen, and class JPanel (from package javax.swing), which provides an area on which we can draw.
Using drawLine to connect the corners of a panel in Java
/*
* Filename: DrawPanel.java
*
* Description: 4.18 - Using drawLine to connect the corners of a panel
*
* @Author: Bilal Tahir Khan Meo
* Website: https://codeblah.com
*
* =====================================================================================
*/
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawPanel extends JPanel{
// draws an x from the panel corners
public void paintComponent(Graphics g){
// call paintComponent to ensure correct panel display
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
// draw a line from the upper left to lower right
g.drawLine(0, 0, width, height);
// draw a line from lower left to upper right
g.drawLine(0, height, width, 0);
}
}
DrawPanelTest.java
/*
* Filename: DrawPanelTest.java
*
* Description: 4.19 - Display a DrawPanel
*
* @Author: Bilal Tahir Khan Meo
* Website: https://codeblah.com
*
* =====================================================================================
*/
import javax.swing.JFrame;
public class DrawPanelTest{
public static void main(String[] args){
DrawPanel panel = new DrawPanel();
// frame to hold the panel
JFrame application = new JFrame();
// set frame to exit on close
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(250, 250);
application.setVisible(true);
}
}