search
HomeJavajavaTutorialjava graphical Swing tutorial (1)


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);

    }
}

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对象,表示这个组件的大小
    }
}

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对象,表示这个组件的大小
    }
}

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接口的实例,并在画布上画出

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对象,表示这个组件的大小
    }
}

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对象,表示这个组件的大小
    }
}

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
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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor