Graphical example code of the javaSwing basic tutorial

  • 2020-06-07 04:34:10
  • OfStack

java Swing Basic tutorial graphical example code

Unlike multithreading, generics, etc., Swing is mainly used.

The following is mainly code and comments, less talk.

(1) Basic framework


package Swing;

import java.awt.*;
import javax.swing.*;

/**
 * 
 * @author QuinnNorris
 *  The basic framework 
 */
public class FrameTest {
  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    //  open 1 Three threads, all of them Swing Components must be configured by the event dispatch thread that transfers mouse click and keystroke control to the user interface component. 
    EventQueue.invokeLater(new Runnable() {
      //  Anonymous inner class, yes 1 a Runnable An instance of the interface run methods 
      public void run() {

        SimpleFrame frame = new SimpleFrame();
        //  Create the following self-defined ones SimpleFrame Class object so that constructor methods can be called 

        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 action to take when the user closes the framework   In some cases, you need to hide the window, you can't exit directly, you need this method 

        frame.setVisible(true);
        //  Make the window visible so that the user is in control 1 We can add content to the window before we see it again 
      }

    });
  }
  // main When it ends, the program doesn't end, but ends the main thread until all the frames are closed or called  System.exit The procedure is terminated only after the event 
}

class SimpleFrame extends JFrame {
  public SimpleFrame() {

    Toolkit kit = Toolkit.getDefaultToolkit();
    //  Modify the position of the window at the top of the screen, changing the window size 
    // Toolkit Class contains many methods for interacting with a local window 

    Dimension screenSize = kit.getScreenSize();
    // Toolkit Gets the screen size of the method returned 1 a Dimension The class object 

    setSize((int) (screenSize.getWidth()), (int) (screenSize.getHeight()));
    // setBounds(0,0,(int)(screenSize.getWidth()),(int)(screenSize.getHeight()));
    //  Define the location and size of the window 
    // setLocation(0,0);  Position the window from the upper-left corner 
    // setLocationByPlatform(true);  Let the window system control the window position and distance 1 A small offset for a window 

    //  Replace window ICONS with images 
    Image img = new ImageIcon("D:/icon.png").getImage();
    setIconImage(img);

  }
}

The output: a box that fills the entire screen. The title bar is called Christmas.

(2) Output text


package Swing;

import java.awt.*;
import javax.swing.*;

/**
 * 
 * @author QuinnNorris
 *  The output text 
 */
public class HelloWorld {

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    //  open 1 Three threads, all of them Swing Components must be configured by the event dispatch thread that transfers mouse click and keystroke control to the user interface component 
    EventQueue.invokeLater(new Runnable() {
      //  Anonymous inner class, yes 1 a Runnable An instance of the interface run methods 
      public void run() {

        JFrame frame = new HelloWorldFrame();
        // HelloworldFrame Defined below, inherited JFrame, Use one of the constructor methods 

        frame.setTitle("HelloWrold");
        //  Set the title 

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //  Select the action to take when the user closes the framework   In some cases, you need to hide the window, you can't exit directly, you need this method 

        frame.setVisible(true);
        //  Make the window visible so that the user is in control 1 We can add content to the window before we see it again 
      }
    });

  }

}

//  Authoring inherits JFrame Class, our work is carried out here 
class HelloWorldFrame extends JFrame {
  public HelloWorldFrame() {

    add(new HelloWorldComponent());
    // Add to it 1 The implementation of the instantiation JComponent A subclass of a class 

    pack();
    // Call the preferred size of the framework component, or we can use SetSize Method to replace it 
  }
}

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 overwrite this to use for writing 
   * 
   * @param g
   *      Graphics Object holds Settings for drawing images and text 
   */
  public void paintComponent(Graphics g) {
    g.drawString("Hello World!", MESSAGE_X, MESSAGE_Y);
    //  Parameter: Write content, the first in the string 1 The characters are located from left to right 75 Pixel, the first in a string 1 Two characters from top to bottom 100 pixel 
  }

  /**
   *  We override this method to indicate the size of the component of the class 
   * 
   * @return  Returns how big the component of the class itself should be 
   */
  public Dimension getPreferredSize() {
    return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    //  return 1 a Dimension Object that represents the size of the component 
  }
}

Output: A small window called HelloWrold in the upper left corner and "Hello World!" in the middle. With the words.

(3) Print graphics


package Swing;

import java.awt.EventQueue;

import javax.swing.*;

import java.awt.*;
import java.awt.geom.*;

/**
 * 
 * @author QuinnNorris
 *  Print graphics 
 */
public class DrawTest {

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    //  open 1 Three threads, all of them Swing Components must be configured by the event dispatch thread that transfers mouse click and keystroke control to the user interface component. 
    EventQueue.invokeLater(new Runnable()
    {
      //  Anonymous inner class, yes 1 a Runnable An instance of the interface run methods 
      public void run(){

        JFrame frame = new DrawFrame();
        //  Create the following self-defined ones SimpleFrame Class object so that constructor methods can be called 

        frame.setTitle("DrawTest");
        //  Set the title 

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //  Select the action to take when the user closes the framework   In some cases, you need to hide the window, you can't exit directly, you need this method 

        frame.setVisible(true);
        //  Make the window visible so that the user is in control 1 We can add content to the window before we see it again 
      }
    });
  }

}


class DrawFrame extends JFrame
{
  public DrawFrame(){

    add(new DrawComponent());
    // Add to it 1 The implementation of the instantiation JComponent A subclass of a class 

    pack();
    // Call the preferred size of the framework component, or we can use SetSize Method to replace it 
  }
}

class DrawComponent extends JComponent
{
  private static final int DEFAULT_WIDTH = 400;
  private static final int DEFAULT_HEIGHT = 400;

  /**
   *  We overwrite this to print the graph 
   * 
   * @param g
   *      Graphics Objects are what we need to use Graphics2D The parent class 
   */
  public void paintComponent(Graphics g){

    Graphics2D g2 = (Graphics2D)g;
    // instantiation Graphics2D The object of this class, which is the argument Graphics2D the 1 A subclass 

    double leftX = 100;
    double topY = 100;
    double width = 200;
    double height = 150;
    // We set the rectangle 4 A property 

    Rectangle2D rect = new Rectangle2D.Double(leftX,topY,width,height);
    // create 1 a Rectangle2D This object inherits Sharp interface 
    //Double Is one of the 1 A static inner class that we need to be in when we initialize Double Set parameters in 

    g2.draw(rect);
    // The incoming 1 An implementation Sharp An instance of the interface and draw it on the canvas 

    Ellipse2D ellipse = new Ellipse2D.Double();
    // create 1 An instance of an ellipse 

    ellipse.setFrame(rect);
    // Ellipses and rectangles are siblings because they have the same way of judging boundaries 
    // Here we're going to use it directly rect To describe the ellipse (through the enclosing rectangle of the ellipse) 

    g2.draw(ellipse);
    // The incoming 1 An implementation Sharp An instance of the interface and draw it on the canvas 

    g2.draw(new Line2D.Double(leftX,topY,leftX+width,topY+height));
    // Draw on the canvas 1 A straight line 

    double centerX = rect.getCenterX();
    double centerY = rect.getCenterY();
    double radius = 150;
    // Define the center coordinates and the radius 

    Ellipse2D circle = new Ellipse2D.Double();
    // create 1 An example of a circle 
    circle.setFrameFromCenter(centerX, centerY, centerX+radius, centerY+radius);
    // Set the coordinates and the radius 
    g2.draw(circle);
    // Draw on the canvas 1 A round 
  }

  /**
   *  We override this method to indicate the size of the component of the class 
   * 
   * @return  Returns how big the component of the class itself should be 
   */
  public Dimension getPreferredSize(){
    return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);
    //  return 1 a Dimension Object that represents the size of the component 
  }
}

The window in the upper left corner has an ellipse, an outer rectangle, a straight line from the upper left corner of the rectangle to the lower right corner, and a circle with a radius of 150 pixels starting from the center of the rectangle.

(4) Graphics coloring


Rectangle2D rect = new Rectangle2D.Double(leftX,topY,width,height);
// create 1 a Rectangle2D This object inherits Sharp interface 
//Double Is one of the 1 A static inner class that we need to be in when we initialize Double Set parameters in 

g2.setColor(Color.BLUE);
// for g2 Object to set 1 Fill color , It affects the color of the line 

g2.fill(rect);
// Fill in the color we selected rect Represents a closed graph 

g2.draw(rect);
// The incoming 1 An implementation Sharp An instance of the interface and draw it on the canvas 

Insert these two lines of code (insert 2 and 3 lines of code between the original position of 1 and 4) without changing the rest of the previous code. Get the coloring effect.

Output: A blue rectangle in the middle, with the center of the rectangle as the origin, and a circle with a blue line as the radius of 150 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

    //  open 1 Three threads, all of them Swing Components must be configured by the event dispatch thread that transfers mouse click and keystroke control to the user interface component. 
    EventQueue.invokeLater(new Runnable() {
      //  Anonymous inner class, yes 1 a Runnable An instance of the interface run methods 
      public void run() {
        JFrame frame = new FontFrame();
        //  Create the following self-defined ones SimpleFrame Class object so that constructor methods can be called 

        frame.setTitle("FontTest");
        //  Set the title 

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //  Select the action to take when the user closes the framework   In some cases, you need to hide the window, you can't exit directly, you need this method 

        frame.setVisible(true);
        //  Make the window visible so that the user is in control 1 We can add content to the window before we see it again 
      }
    });
  }

}

class FontFrame extends JFrame {
  public FontFrame() {
    add(new FontComponent());
    //  Add to it 1 The implementation of the instantiation JComponent A subclass of a class 

    pack();
    //  Call the preferred size of the framework component, or we can use SetSize Method to replace it 
  }
}

class FontComponent extends JComponent {
  private static final int DEFAULT_WIDTH = 300;
  private static final int DEFAULT_HEIGHT = 200;

  /**
   *  We overwrite this to do that 1 Some work 
   * 
   * @param g
   *      Graphics Objects are what we need to use Graphics2D The parent class 
   */
  public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    //  instantiation Graphics2D The object of this class, which is the argument Graphics2D the 1 A subclass 

    String message = "Hello World!";
    //  Write the text that we want to manipulate 

    Font f = new Font("Dialog", Font.BOLD, 36);
    //  create 1 Font type, including font family, style type, size 
    //  It is also possible to get a local font pack by means of a special method called load 

    g2.setFont(f);
    //  will f Set in the g2 Among the 

    FontRenderContext context = g2.getFontRenderContext();
    //  Get the description object of the screen device font property by calling the method 

    Rectangle2D bounds = f.getStringBounds(message, context);
    // getStringBounds Method returns 1 A rectangle enclosing a string 

    double x = (DEFAULT_WIDTH - bounds.getWidth()) / 2;
    // bounds.getWidth Method to obtain the width of the string 

    double y = (DEFAULT_HEIGHT - bounds.getHeight()) / 2;
    // bounds.getHeight Method to obtain the height of the string 

    double ascent = -bounds.getY();
    //  Gets the upper slope of the font 

    double baseY = y + ascent;
    //  The base line position of the text 

    g2.drawString(message, (int) x, (int) y);
    //  Set string position 

    g2.setPaint(Color.LIGHT_GRAY);
    //  Set the line color to light gray 

    g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));
    //  Draw a line under the text 1 Horizontal lines 

    Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(),
        bounds.getHeight());

    g2.draw(rect);
  }

  /**
   *  We override this method to indicate the size of the component of the class 
   * 
   * @return  Returns how big the component of the class itself should be 
   */
  public Dimension getPreferredSize() {
    return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    //  return 1 a Dimension Object that represents the size of the component 
  }
}

Output: In the middle of the window is the text "Hello World", surrounded by a gray rectangle with a horizontal line at the baseline.

(6) Add pictures


package Swing;

import javax.swing.*;
import java.awt.*;

/**
 * 
 * @author QuinnNorris  Add images 
 */
public class ImageTest {

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    //  open 1 Three threads, all of them Swing Components must be configured by the event dispatch thread that transfers mouse click and keystroke control to the user interface component. 
    EventQueue.invokeLater(new Runnable() {
      //  Anonymous inner class, yes 1 a Runnable An instance of the interface run methods 
      public void run() {
        JFrame frame = new ImageFrame();
        //  Create the following self-defined ones SimpleFrame Class object so that constructor methods can be called 

        frame.setTitle("ImageTest");
        //  Set the title 

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //  Select the action to take when the user closes the framework   In some cases, you need to hide the window, you can't exit directly, you need this method 

        frame.setVisible(true);
        //  Make the window visible so that the user is in control 1 We can add content to the window before we see it again 
      }
    });
  }

}

class ImageFrame extends JFrame {
  public ImageFrame() {
    add(new ImageComponent());
    //  Add to it 1 The implementation of the instantiation JComponent A subclass of a class 

    pack();
    //  Call the preferred size of the framework component, or we can use SetSize Method to replace it 
  }
}

class ImageComponent extends JComponent {

  private static final int DEFAULT_WIDTH = 300;
  private static final int DEFAULT_HEIGHT = 200;

  private Image image;

  /**
   * ImageComponent Constructor to instantiate an image 
   */
  public ImageComponent(){
    image = new ImageIcon("D:/image.jpg").getImage();
    // Get the picture by the path 
  }

  /**
   *  We overwrite this to do that 1 Some work 
   * 
   * @param g
   *      
   */
  public void paintComponent(Graphics g) {
    if(image == null ) return;
    // If the image is incorrect, return it directly to avoid an error 

    g.drawImage(image, 0,0,null);
    // Give the picture on the canvas 
  }

  /**
   *  We override this method to indicate the size of the component of the class 
   * 
   * @return  Returns how big the component of the class itself should be 
   */
  public Dimension getPreferredSize() {
    return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    //  return 1 a Dimension Object that represents the size of the component 
  }
}

Output: Place your added image on the canvas starting at the top left corner.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: