Java Interface Programming-create a simple framework for drawing graphics, java graphics
Introduction: Three. java files are used in total to build a simple interface programming framework.
1st files: NotHelloWorldComponent. java
// NotHelloWorldComponent. java
1 import java. awt. *; 2 import java. awt. geom. *; 3 import javax. swing. *; 4 5 public class NotHelloWorldComponent extends JComponent {6 public static final int MESSAGE_X = 75; // coordinates 7 public static final int MESSAGE_Y = 75 in the upper left corner of the message; 8
// Define the default size of this interface 9 private static final int DEFAULT_WIDTH = 300; 10 private static final int DEFAULT_HEIGHT = 300; 11
// PaintComponent () will be automatically called by the system, and the system will automatically pass a Graphics object to it 12 public void paintComponent (Graphics g) {13 // convert g to Graphics2D object, used as a paint brush to draw 2D graphics 14 Graphics2D g2 = (Graphics2D) g; 15
// Create a Rectangle2D rectangle object
// If other images need to be drawn, you can define them here first, and then use g2 as the paint brush in the next section to draw 16 double leftX = 50; 17 double topY = 50; 18 double width = 200; 19 double height = 150; 20 Rectangle2D rect = new Rectangle2D. double (leftX, topY, width, height); 21
// Use paint brush g2 to draw text and rectangular images 22 g2.drawString ("Not a hello, World program", MESSAGE_X, MESSAGE_Y); 23 g2.draw (rect); 24 25} 26
// Override this function and set the preferred size 27 @ Override28 public Dimension getPreferredSize () {29 return new Dimension (DEFAULT_WIDTH, DEFAULT_HEIGHT); 30} 31}
2nd. java files: NotHelloWorldFrame. java
1 import javax. swing. JFrame; 2 3 public class NotHelloWorldFrame extends JFrame {4 public NotHelloWorldFrame () {5 add (new NotHelloWorldComponent (); 6 pack (); // make the JFrame size fit the size of the components it contains 7} 8}
Note: JFrame is a framework class used to contain JPanel and JComponent.
3rd. java files: NotHelloWorld. java
1 import java. awt. eventQueue; 2 3 import javax. swing. JFrame; 4 5 public class NotHelloWorld {6 public static void main (String [] args) {7 EventQueue. invokeLater (new Runnable () {// use anonymous internal technology to create a thread and use a thread to create window Program 8 public void run () {9 JFrame frame = new NotHelloWorldFrame (); 10 frame. setTitle ("NotHelloWorldFrame"); 11 frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); // when the window is closed, the program ends to avoid 12 frame garbage in memory. setVisible (true); // The window opening is visible 13} 14}); 15} 16}
(Simple use of anonymous internal classes, see this blog: http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html)