English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
java Swing Basic Tutorial Graphical Example Code
Different from multithreading, generics, etc., Swing mainly focuses on usage.
The following mainly contains code and comments, and speaks less.
(I) Basic framework
package Swing; import java.awt.*; import javax.swing.*; /** * * @author QuinnNorris * Basic framework */ public class FrameTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Start a thread, all Swing components must be configured by the event dispatch thread, the thread transfers mouse clicks and key controls to the user interface components. EventQueue.invokeLater(new Runnable() { // Anonymous inner class, an instance of the Runnable interface, implements the run method public void run() { SimpleFrame frame = new SimpleFrame(); // Create an object of the self-defined SimpleFrame class to call the constructor method frame.setExtendedState(Frame.MAXIMIZED_BOTH); // Maximize the window // Other optional properties: Frame.NORMAL ICONIFIED MAXIMIZED_HORIZ MAXIMIZED_VERT // MAXIMIZED_BOTH frame.setTitle("Christmas"); // Set window title frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Select the operation to be performed when the user closes the frame, sometimes it is necessary to hide the window and not exit directly, this method needs to be used frame.setVisible(true); // Make the window visible so that we can add content to it before the user sees it for the first time } }); } // When the main process ends, the program does not terminate, but the main thread ends, and the program terminates only when all frames are closed or System.exit is called. } class SimpleFrame extends JFrame { public SimpleFrame() { Toolkit kit = Toolkit.getDefaultToolkit(); // Modify the position of the window on the screen, change the size of the window // The Toolkit class contains many methods for interacting with local windows Dimension screenSize = kit.getScreenSize(); // The method to get the screen size of Toolkit returns an object of the Dimension class setSize((int) (screenSize.getWidth()), (int) (screenSize.getHeight())); // setBounds(0,0,(int)(screenSize.getWidth()),(int)(screenSize.getHeight())); // Define the position and size of the window // setLocation(0,0); Position the window relative to the top-left corner // setLocationByPlatform(true); Let the window system control the window position, a small offset from the previous window // Use an image to replace the window icon Image img = new ImageIcon("D:/icon.png").getImage(); setIconImage(img); } }
Output result: a frame filling the entire screen, the title bar is named Christmas, and the chart is a picture filled by yourself.
(II) Output text
package Swing; import java.awt.*; import javax.swing.*; /** * * @author QuinnNorris * Output text */ public class HelloWorld { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Start a thread, all Swing components must be configured by the event dispatch thread, the thread transfers mouse clicks and key controls to the user interface components EventQueue.invokeLater(new Runnable() { // Anonymous inner class, an instance of the Runnable interface, implements the run method public void run() { JFrame frame = new HelloWorldFrame(); // HelloworldFrame is defined below, inherits from JFrame, using its constructor method frame.setTitle("HelloWrold"); // Set the title frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Select the operation to be performed when the user closes the frame, sometimes it is necessary to hide the window and not exit directly, this method needs to be used frame.setVisible(true); // Make the window visible so that we can add content to it before the user sees it for the first time } }); } } // Write a class that inherits from JFrame, where our work is carried out here class HelloWorldFrame extends JFrame { public HelloWorldFrame() { add(new HelloWorldComponent()); //Add an instantiated subclass of the JComponent class to it pack(); //The preferred size of the framework component is called, or we can replace it with the SetSize method } } class HelloWorldComponent extends JComponent { public static final int MESSAGE_X = 75; public static final int MESSAGE_Y = 100; private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; /** * We override this to write content * * @param g * The Graphics object contains the settings used to draw images and text */ public void paintComponent(Graphics g) { g.drawString("Hello World!", MESSAGE_X, MESSAGE_Y); // Parameters: writing content, the first character of the string is from left to right75pixels, the first character of the string is from top to bottom100 pixels } /** * We override this method to represent the size of this class's component * * @return Returns the size that this class's component should be */ public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); // Returns a Dimension object representing the size of this component } }
Output result: A small window named 'HelloWrold' located at the upper left corner with 'Hello World!' in the center of the window.
(3) Print the graphics
package Swing; import java.awt.EventQueue; import javax.swing.*; import java.awt.*; import java.awt.geom.*; /** * * @author QuinnNorris * Print the graphics */ public class DrawTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Start a thread, all Swing components must be configured by the event dispatch thread, the thread transfers mouse clicks and key controls to the user interface components. EventQueue.invokeLater(new Runnable() { // Anonymous inner class, an instance of the Runnable interface, implements the run method public void run(){ JFrame frame = new DrawFrame(); // Create an object of the self-defined SimpleFrame class to call the constructor method frame.setTitle("DrawTest"); // Set the title frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Select the operation to be performed when the user closes the framework, sometimes it is necessary to hide the window and not exit directly, this method needs to be used frame.setVisible(true); // Make the window visible so that we can add content to it before the user sees it for the first time } }); } } class DrawFrame extends JFrame { public DrawFrame(){ add(new DrawComponent()); //Add an instantiated subclass of the JComponent class to it pack(); //The preferred size of the framework component is called, or we can replace it with the SetSize method } } class DrawComponent extends JComponent { private static final int DEFAULT_WIDTH = 400; private static final int DEFAULT_HEIGHT = 400; /** * We override this to print the graphics * * @param g * The Graphics object we need to use is Graphics2D is the superclass */ public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D)g; //Instance Graphics2An object of this class, it is the parameter Graphics2D is a subclass double leftX = 100; double topY = 100; double width = 200; double height = 150; //We set the four properties of the rectangle Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height); //Create a Rectangle2The D object, which inherits the Sharp interface //Double is one of the static inner classes, when initializing we need to set parameters in Double g2.draw(rect); //Pass an instance that implements the Sharp interface and draw it on the canvas Ellipse2D ellipse = new Ellipse2D.Double(); //Create an instance of an ellipse ellipse.setFrame(rect); //The ellipse and rectangle classes are sibling relationships because they have the same boundary judgment methods //Here we use rect directly to describe the ellipse (through the circumscribed rectangle of the ellipse) g2.draw(ellipse); //Pass an instance that implements the Sharp interface and draw it on the canvas g2.draw(new Line2D.Double(leftX, topY, leftX+width, topY+height)); //Draw a line on the canvas double centerX = rect.getCenterX(); double centerY = rect.getCenterY(); double radius = 150; //Define the coordinates of the center of the circle and the radius Ellipse2D circle = new Ellipse2D.Double(); //Create an instance of a circle circle.setFrameFromCenter(centerX, centerY, centerX+radius, centerY+radius); //Set coordinates and radius g2.draw(circle); //Draw a circle on the canvas } /** * We override this method to represent the size of this class's component * * @return Returns the size that this class's component should be */ public Dimension getPreferredSize(){ return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT); // Returns a Dimension object representing the size of this component } }
Output result: In the upper left corner of the window there is an ellipse, outside there is an outer rectangle, there is a straight line from the upper left corner of the rectangle to the lower right corner, with a radius of15A circle with a radius of 0 pixels.
(4) Coloring of Graphics
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height); //Create a Rectangle2The D object, which inherits the Sharp interface //Double is one of the static inner classes, when initializing we need to set parameters in Double g2.setColor(Color.BLUE); //for g2The object sets a fill color, which will affect the line color g2.fill(rect); //Fill the color we choose into the closed figure represented by rect g2.draw(rect); //Pass an instance that implements the Sharp interface and draw it on the canvas
Without changing the other parts of the code, insert the following two lines of code (in1,4insert the code in the original position of the line code2,3get the colored effect.).
Output result: In the middle is a blue rectangle, with the center of the rectangle as the origin,15A circle with a blue line with a radius of 0 pixels.
(5) Special Font
package Swing; import javax.swing.*; import java.awt.*; import java.awt.font.*; import java.awt.geom.*; /** * * @author QuinnNorris Special Font */ public class FontTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Start a thread, all Swing components must be configured by the event dispatch thread, the thread transfers mouse clicks and key controls to the user interface components. EventQueue.invokeLater(new Runnable() { // Anonymous inner class, an instance of the Runnable interface, implements the run method public void run() { JFrame frame = new FontFrame(); // Create an object of the self-defined SimpleFrame class to call the constructor method frame.setTitle("FontTest"); // Set the title frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Select the operation to be performed when the user closes the framework, sometimes it is necessary to hide the window and not exit directly, this method needs to be used frame.setVisible(true); // Make the window visible so that we can add content to it before the user sees it for the first time } }); } } class FontFrame extends JFrame { public FontFrame() { add(new FontComponent()); // Add an instantiated subclass of the JComponent class to it pack(); // The preferred size of the framework component is called, or we can replace it with the SetSize method } } class FontComponent extends JComponent {}} private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; /** * We override this to do some work * * @param g * The Graphics object we need to use is Graphics2D is the superclass */ public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // Instance Graphics2An object of this class, it is the parameter Graphics2D is a subclass String message = "Hello World!"; // Write the text we want to operate on Font f = new Font("Dialog", Font.BOLD, 36); // Create a font type, including font family, style type, and size // You can also call a special method to load and get the local font package g2.setFont(f); // Set f in g2in FontRenderContext context = g2.getFontRenderContext(); // By calling the method, we get the description object of the screen device font properties Rectangle2D bounds = f.getStringBounds(message, context); // The getStringBounds() method returns a rectangle enclosing the string double x = (DEFAULT_WIDTH - bounds.getWidth()) / 2; // The bounds.getWidth() method can obtain the width of the string double y = (DEFAULT_HEIGHT - bounds.getHeight()) / 2; // The bounds.getHeight() method can obtain the height of the string double ascent = -bounds.getY(); // Get the ascent of the font double baseY = y + ascent; // The baseline position of the text g2.drawString(message, (int) x, (int) y); // Set the string position g2.setPaint(Color.LIGHT_GRAY); // Set the line color to light gray g2.draw(new Line2D.Double(x, baseY, x + , baseY)); // Draw a horizontal line below the baseline of the text Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight()); g2.draw(rect); } /** * We override this method to represent the size of this class's component * * @return Returns the size that this class's component should be */ public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); // Returns a Dimension object representing the size of this component } }
Output result: The text "Hello World" is in the center of the window, surrounded by a gray rectangle, and a horizontal line is divided at the baseline.
(Six) Add image
package Swing; import javax.swing.*; import java.awt.*; /** * * @author QuinnNorris Add image */ public class ImageTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Start a thread, all Swing components must be configured by the event dispatch thread, the thread transfers mouse clicks and key controls to the user interface components. EventQueue.invokeLater(new Runnable() { // Anonymous inner class, an instance of the Runnable interface, implements the run method public void run() { JFrame frame = new ImageFrame(); // Create an object of the self-defined SimpleFrame class to call the constructor method frame.setTitle("ImageTest"); // Set the title frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Select the operation to be performed when the user closes the framework, sometimes it is necessary to hide the window and not exit directly, this method needs to be used frame.setVisible(true); // Make the window visible so that we can add content to it before the user sees it for the first time } }); } } class ImageFrame extends JFrame { public ImageFrame() { add(new ImageComponent()); // Add an instantiated subclass of the JComponent class to it pack(); // The preferred size of the framework component is called, or we can replace it with the SetSize method } } class ImageComponent extends JComponent { private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; private Image image; /** * The constructor of ImageComponent, used to instantiate the image */ public ImageComponent(){ image = new ImageIcon("D:/image.jpg").getImage(); //Get the image through the path } /** * We override this to do some work * * @param g * */ public void paintComponent(Graphics g) { if(image == null ) return; //If the image is incorrect, return directly to avoid errors g.drawImage(image, 0,0,null); //Provide an image on the canvas } /** * We override this method to represent the size of this class's component * * @return Returns the size that this class's component should be */ public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); // Returns a Dimension object representing the size of this component } }
Output result: Place the image you add at the top left corner of the canvas.
Thank you for reading, hoping to help everyone, thank you for your support of this site!
Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please send an email to codebox.com (replace # with @ when sending email) to report any violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.