Table of Contents
(1) Basic framework
(2) Output text
(3) Print graphics
(4) Graphic coloring
(5) Special font
(6) Add pictures
Home Java javaTutorial java graphical Swing tutorial (1)

java graphical Swing tutorial (1)

Mar 01, 2017 am 11:29 AM


Different from multi-threading, generics, etc., Swing mainly lies in usage.
The following is mainly about code and comments, and less talking.

(1) Basic framework

package Swing;import java.awt.*;import javax.swing.*;/**
 * 
 * @author QuinnNorris
 * 基本框架
 */public class FrameTest {
    /**
     * @param args
     */
    public static void main(String[] args) {        
    // TODO Auto-generated method stub

        // 开启一个线程,所有的Swing组件必须由事件分派线程进行配置,线程将鼠标点击和按键控制转移到用户接口组件。
        EventQueue.invokeLater(new Runnable() {            
        // 匿名内部类,是一个Runnable接口的实例,实现了run方法
            public void run() {

                SimpleFrame frame = new SimpleFrame();                
                // 创建下面自己定义的SimpleFrame类对象,以便于调用构造器方法

                frame.setExtendedState(Frame.MAXIMIZED_BOTH);                
                // 将窗口最大化
                // 其他可选属性:Frame.NORMAL ICONIFIED MAXIMIZED_HORIZ MAXIMIZED_VERT
                // MAXIMIZED_BOTH

                frame.setTitle("Christmas");                
                // 设置窗口标题

                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                
                // 选择当用户关闭框架时进行的操作 ,在有些时候需要将窗口隐藏,不能直接退出需要用到这个方法

                frame.setVisible(true);                
                // 将窗口可见化,这样以便用户在第一次看见窗口之前我们能够向其中添加内容
            }

        });
    }    // main结束时,程序并没有结束,而是结束了主线程,知道所有框架关闭或者调用了 System.exit事才终止程序}

class SimpleFrame extends JFrame {    public SimpleFrame() {

        Toolkit kit = Toolkit.getDefaultToolkit();        
        // 修改窗口在屏幕上面的位置,改变窗口大小
        // Toolkit类包含很多与本地窗口交互的方法

        Dimension screenSize = kit.getScreenSize();        
        // Toolkit的获取频幕大小的方法返回一个Dimension的类对象

        setSize((int) (screenSize.getWidth()), (int) (screenSize.getHeight()));        
        // setBounds(0,0,(int)(screenSize.getWidth()),(int)(screenSize.getHeight()));
        // 定义窗口的位置和大小
        // setLocation(0,0); 定位窗口距离左上角的位置
        // setLocationByPlatform(true); 让窗口系统控制窗口位置,距离上一个窗口很小的偏移量

        // 用图片来替换窗口图标
        Image img = new ImageIcon("D:/icon.png").getImage();
        setIconImage(img);

    }
}
Copy after login

Output result: a frame that fills the entire screen, the title bar is called Christmas, and the chart is itself Filled picture.

(2) Output text

package Swing;import java.awt.*;import javax.swing.*;/**
 * 
 * @author QuinnNorris
 * 输出文字
 */public class HelloWorld {

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

        // 开启一个线程,所有的Swing组件必须由事件分派线程进行配置,线程将鼠标点击和按键控制转移到用户接口组件
        EventQueue.invokeLater(new Runnable() {            
        // 匿名内部类,是一个Runnable接口的实例,实现了run方法
            public void run() {

                JFrame frame = new HelloWorldFrame();                
                // HelloworldFrame在下面定义,继承了JFrame,使用其中的构造器方法

                frame.setTitle("HelloWrold");                
                // 设置标题

                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                
                // 选择当用户关闭框架时进行的操作 ,在有些时候需要将窗口隐藏,不能直接退出需要用到这个方法

                frame.setVisible(true);                
                // 将窗口可见化,这样以便用户在第一次看见窗口之前我们能够向其中添加内容
            }
        });

    }

}// 编写继承了JFrame的类,我们的工作在这里进行class HelloWorldFrame extends JFrame {    public HelloWorldFrame() {

        add(new HelloWorldComponent());        
        //向其中添加一个实例化的实现JComponent类的子类

        pack();        
        //调用框架组件的首选大小,或者我们可以用SetSize方法来替换它
    }
}

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;    
/**
     * 我们覆盖了这个以用来书写内容
     * 
     * @param g
     *            Graphics对象保存着用于绘制图像和文本的设置
     */
    public void paintComponent(Graphics g) {
        g.drawString("Hello World!", MESSAGE_X, MESSAGE_Y);        
        // 参数:书写内容,字符串中第一个字符位于从左向右75像素,字符串中第一个字符从上向下100像素
    }    /**
     * 我们覆盖了这个方法来表示出这个类的组件的大小
     * 
     * @return 返回这个类的组件本身应该有多大
     */
    public Dimension getPreferredSize() {        
    return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);        
    // 返回一个Dimension对象,表示这个组件的大小
    }
}
Copy after login

Output result: a small window named HelloWrold located in the upper left corner, There are words "Hello World!" in the middle of the window.

(3) Print graphics

package Swing;import java.awt.EventQueue;import javax.swing.*;import java.awt.*;import java.awt.geom.*;/**
 * 
 * @author QuinnNorris
 * 打印图形
 */public class DrawTest {

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

        // 开启一个线程,所有的Swing组件必须由事件分派线程进行配置,线程将鼠标点击和按键控制转移到用户接口组件。
        EventQueue.invokeLater(new Runnable()
        {            
        // 匿名内部类,是一个Runnable接口的实例,实现了run方法
            public void run(){

                JFrame frame = new DrawFrame();                
                // 创建下面自己定义的SimpleFrame类对象,以便于调用构造器方法

                frame.setTitle("DrawTest");                
                // 设置标题

                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                
                // 选择当用户关闭框架的时候进行的操作 ,在有些时候需要将窗口隐藏,不能直接退出需要用到这个方法

                frame.setVisible(true);                
                // 将窗口可见化,这样以便用户在第一次看见窗口之前我们能够向其中添加内容
            }
        });
    }

}


class DrawFrame extends JFrame
{    public DrawFrame(){

        add(new DrawComponent());        
        //向其中添加一个实例化的实现JComponent类的子类

        pack();        
        //调用框架组件的首选大小,或者我们可以用SetSize方法来替换它
    }
}

class DrawComponent extends JComponent
{    private static final int DEFAULT_WIDTH = 400;    
private static final int DEFAULT_HEIGHT = 400;    
/**
     * 我们覆盖了这个以用来打印图形
     * 
     * @param g
     *            Graphics对象是我们需要用的Graphics2D的父类
     */
    public void paintComponent(Graphics g){

        Graphics2D g2 = (Graphics2D)g;        
        //实例化Graphics2D这个类的对象,他是参数Graphics2D的一个子类

        double leftX = 100;        
        double topY = 100;        
        double width = 200;        
        double height = 150;        
        //我们设置矩形的四个属性

        Rectangle2D rect = new Rectangle2D.Double(leftX,topY,width,height);        
        //创建一个Rectangle2D的对象,这个对象继承了Sharp接口
        //Double是其中的一个静态内部类,当我们初始化时需要在Double中设置参数

        g2.draw(rect);        
        //传入一个实现Sharp接口的实例,并在画布上画出

        Ellipse2D ellipse = new Ellipse2D.Double();        
        //创建一个椭圆的实例

        ellipse.setFrame(rect);        
        //椭圆和矩形类是兄弟关系,因为他们有着相同的边界判断方式
        //这里我们直接用rect来对椭圆形进行描述(通过椭圆的外接矩形)

        g2.draw(ellipse);        
        //传入一个实现Sharp接口的实例,并在画布上画出

        g2.draw(new Line2D.Double(leftX,topY,leftX+width,topY+height));        
        //在画布上画出一条直线

        double centerX = rect.getCenterX();        
        double centerY = rect.getCenterY();        
        double radius = 150;        
        //定义圆心坐标和半径

        Ellipse2D circle = new Ellipse2D.Double();        
        //创建一个圆的实例
        circle.setFrameFromCenter(centerX, centerY, centerX+radius, centerY+radius);        
        //设置坐标和半径
        g2.draw(circle);        
        //在画布上画出一个圆
    }    
    /**
     * 我们覆盖了这个方法来表示出这个类的组件的大小
     * 
     * @return 返回这个类的组件本身应该有多大
     */
    public Dimension getPreferredSize(){        
    return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);        
    // 返回一个Dimension对象,表示这个组件的大小
    }
}
Copy after login

Output result: There is an ellipse in the upper left corner of the window, and there are An outer rectangle has 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 with the center of the rectangle as the origin.

(4) Graphic coloring

Rectangle2D rect = new Rectangle2D.Double(leftX,topY,width,height);
//创建一个Rectangle2D的对象,这个对象继承了Sharp接口
//Double是其中的一个静态内部类,当我们初始化时需要在Double中设置参数g2.setColor(Color.BLUE);
//为g2对象设置一种填充颜色,会影响线条颜色g2.fill(rect);
//将我们选择的颜色填充到rect表示的封闭图形中g2.draw(rect);
//传入一个实现Sharp接口的实例,并在画布上画出
Copy after login

Without changing other parts of the previous code, insert these two lines of code (in Insert 2 or 3 lines of code in the middle of the original position of 1 or 4 lines of code). Get the coloring effect.

Output result: A blue rectangle in the middle, a circle with a blue line with the center of the rectangle as the origin and a 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 特殊字体
 */public class FontTest {

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

        // 开启一个线程,所有的Swing组件必须由事件分派线程进行配置,线程将鼠标点击和按键控制转移到用户接口组件。
        EventQueue.invokeLater(new Runnable() {            
        // 匿名内部类,是一个Runnable接口的实例,实现了run方法
            public void run() {
                JFrame frame = new FontFrame();                
                // 创建下面自己定义的SimpleFrame类对象,以便于调用构造器方法

                frame.setTitle("FontTest");                
                // 设置标题

                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                
                // 选择当用户关闭框架的时候进行的操作 ,在有些时候需要将窗口隐藏,不能直接退出需要用到这个方法

                frame.setVisible(true);                
                // 将窗口可见化,这样以便用户在第一次看见窗口之前我们能够向其中添加内容
            }
        });
    }

}

class FontFrame extends JFrame {    
public FontFrame() {
        add(new FontComponent());        
        // 向其中添加一个实例化的实现JComponent类的子类

        pack();        
        // 调用框架组件的首选大小,或者我们可以用SetSize方法来替换它
    }
}

class FontComponent extends JComponent {    
private static final int DEFAULT_WIDTH = 300;    
private static final int DEFAULT_HEIGHT = 200;    
/**
     * 我们覆盖了这个以用来做一些工作
     * 
     * @param g
     *            
     Graphics对象是我们需要用的Graphics2D的父类
     */
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;        
        // 实例化Graphics2D这个类的对象,他是参数Graphics2D的一个子类

        String message = "Hello World!";        
        // 写出我们要操作的文字

        Font f = new Font("Dialog", Font.BOLD, 36);        
        // 创建一个字体类型,参数包括字体族,风格类型,大小
        // 也可以通过特殊的方法,调用加载得到本地的字体包

        g2.setFont(f);        
        // 将f设置在g2之中

        FontRenderContext context = g2.getFontRenderContext();        
        // 通过调用方法,得到屏幕设备字体属性的描述对象

        Rectangle2D bounds = f.getStringBounds(message, context);        
        // getStringBounds方法返回一个包围着字符串的矩形

        double x = (DEFAULT_WIDTH - bounds.getWidth()) / 2;        
        // bounds.getWidth方法可以获得字符串的宽度

        double y = (DEFAULT_HEIGHT - bounds.getHeight()) / 2;        
        // bounds.getHeight方法可以获得字符串的高度

        double ascent = -bounds.getY();        
        // 获得字体的上坡度

        double baseY = y + ascent;        
        // 文字的基线位置

        g2.drawString(message, (int) x, (int) y);        
        // 设置字符串位置

        g2.setPaint(Color.LIGHT_GRAY);        
        // 设置线条颜色为亮灰色

        g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));        
        // 在文字的基线上画下一条横线

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

        g2.draw(rect);
    }    /**
     * 我们覆盖了这个方法来表示出这个类的组件的大小
     * 
     * @return 返回这个类的组件本身应该有多大
     */
    public Dimension getPreferredSize() {        
    return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);        
    // 返回一个Dimension对象,表示这个组件的大小
    }
}
Copy after login

Output result: There is the text "Hello World" in the middle of the window, and the outer edge Enclosed by a gray rectangle and divided by a horizontal line at the baseline.

(6) Add pictures

package Swing;import javax.swing.*;import java.awt.*;/**
 * 
 * @author QuinnNorris 添加图片
 */public class ImageTest {

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

        // 开启一个线程,所有的Swing组件必须由事件分派线程进行配置,线程将鼠标点击和按键控制转移到用户接口组件。
        EventQueue.invokeLater(new Runnable() {            
        // 匿名内部类,是一个Runnable接口的实例,实现了run方法
            public void run() {
                JFrame frame = new ImageFrame();                
                // 创建下面自己定义的SimpleFrame类对象,以便于调用构造器方法

                frame.setTitle("ImageTest");                
                // 设置标题

                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                
                // 选择当用户关闭框架的时候进行的操作 ,在有些时候需要将窗口隐藏,不能直接退出需要用到这个方法

                frame.setVisible(true);                
                // 将窗口可见化,这样以便用户在第一次看见窗口之前我们能够向其中添加内容
            }
        });
    }

}

class ImageFrame extends JFrame {    
public ImageFrame() {
        add(new ImageComponent());        
        // 向其中添加一个实例化的实现JComponent类的子类

        pack();        
        // 调用框架组件的首选大小,或者我们可以用SetSize方法来替换它
    }
    
}

class ImageComponent extends JComponent {    
private static final int DEFAULT_WIDTH = 300;    
private static final int DEFAULT_HEIGHT = 200;    
private Image image;    
/**
     * ImageComponent的构造函数,用来实例化图片
     */
    public ImageComponent(){
        image = new ImageIcon("D:/image.jpg").getImage();        
        //通过路径得到图片
    }    
    /**
     * 我们覆盖了这个以用来做一些工作
     * 
     * @param g
     *           
     */
    public void paintComponent(Graphics g) {        
    if(image == null ) return;        
    //如果图片不正确,则直接返回避免发生错误

        g.drawImage(image, 0,0,null);        
        //在画布上给出图片
    }    
    /**
     * 我们覆盖了这个方法来表示出这个类的组件的大小
     * 
     * @return 返回这个类的组件本身应该有多大
     */
    public Dimension getPreferredSize() {        
    return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);        
    // 返回一个Dimension对象,表示这个组件的大小
    }
}
Copy after login

Output results: Place the image you added starting from the upper left corner of the canvas picture.

Different from multi-threading, generics, etc., Swing mainly lies in usage.
The following is mainly about code and comments, and less talking.

The above is the content of java graphical Swing tutorial (1). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles