(JAVA) Write a simple text editor using GUI

foreword

Let's try to write a piece of code today, write a simple text editor, let's take a look!

First of all, we need to use inheritance (extends) and interface (implements) in Java. We divide it into two files: one file is all the layout and logic; the other file is the most basic frame (JFrame) in the GUI.

In terms of layout, I chose NullLayout, which is convenient but requires more settings.

The components used are: label (JLabel), slider (JSlider), single-line text box (JTextField), multi-line text box (JTextArea), button (JButton), button group (JButtonGroup), radio button (JRadioButton), Font (Font) and prompt box (JDialog).

The event listeners used are: ItemListener, ChangeListener and ActionListener.

Next, let's look at the code together!

import java.awt.*;      
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class NullLayout extends JFrame implements ItemListener, ChangeListener, ActionListener{
	/**
	 * 设置serialVersionUID属性,防止编译器警告序列化NullLayout没有声明serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * @param 这部分为成员变量设置
	 */
	private JLabel Topjlabel = new JLabel("字体大小");
	private JLabel Bottomjlabel = new JLabel("字体颜色");
	private JLabel Bottomjlabel2 = new JLabel("滑动标签");
	//↓↓↓↓↓↓↓↓这两行顺序不可改变,slider对象应在初始化后调用
	private JSlider slider = new JSlider();			//Slider默认最小值0,最大值100,初始值50
	private JLabel Bottomcenterjlabel = new JLabel("滑块的值是"+slider.getValue());
	//↑↑↑↑↑↑↑↑这两行顺序不可改变,slider对象应在初始化后调用
	private JLabel transformtoRGB = new JLabel("十六进制:");
	private JLabel useRGB_R = new JLabel("R");
	private JLabel useRGB_G = new JLabel("G");
	private JLabel useRGB_B = new JLabel("B");
	private JLabel prompt = new JLabel("      请输入7位16进制色彩代码");
	private JLabel prompt2 = new JLabel("请输入正确的sRGB色彩(要求RGB在0~255)");
	private JTextField R = new JTextField("255",3);
	private JTextField G = new JTextField("255",3);
	private JTextField B = new JTextField("255",3);
	private JTextField jtextfield = new JTextField("#000000",7);
	private JButton RGBbutton = new JButton("转换");
	private JButton jbtn = new JButton("转换");
	private ButtonGroup btngroup = new ButtonGroup();
	private ButtonGroup btngroup2 = new ButtonGroup();
	private JRadioButton rbt1 = new JRadioButton("小号");
	private JRadioButton rbt2 = new JRadioButton("中号");
	private JRadioButton rbt3 = new JRadioButton("大号");
	private JRadioButton rbt4 = new JRadioButton("红色");
	private JRadioButton rbt5 = new JRadioButton("黄色");
	private JRadioButton rbt6 = new JRadioButton("蓝色");
	private JTextArea textarea = new JTextArea("在此输入文本...",20,20);
	private Font f1 = new Font("仿宋",Font.BOLD,25);
	private Font f2 = new Font("仿宋",Font.PLAIN,25);
	private JDialog jdialog = new JDialog(this,"提示",true);
	private JDialog jdialog2 = new JDialog(this,"提示",true);
	/**
	 * @param 成员变量设置完毕
	 */
	//构造器
	public NullLayout(String title){
		super(title);		//调用父类一参构造器,并初始化JFrame的标题为"简单文本编辑器"。
		init();		//为防止构造器内容过多,调用外部函数
	}
	//构造器内部分,为防止构造器内代码过长,通过调用函数实现
	public void init(){
		//设置布局为空布局
		setLayout(null);
		//设置窗口大小不可改变
		setResizable(false);
		//将字体大小文本加入JPanel
		add(Topjlabel);
		//设置字体大小组件位置
		Topjlabel.setBounds(100, 20, 200, 50);
		//设置字体大小组件字体样式
		Topjlabel.setFont(f1);
		//将字体大小单选按钮加入按钮组
		btngroup.add(rbt1);
		btngroup.add(rbt2);
		btngroup.add(rbt3);
		//将字体大小按钮加入JPanel
		add(rbt1);
		add(rbt2);
		add(rbt3);
		//设置字体大小按钮的位置
		rbt1.setBounds(400, 20, 200, 50);
		rbt2.setBounds(600, 20, 200, 50);
		rbt3.setBounds(800, 20, 200, 50);
		//设置字体大小单选按钮的字体
		rbt1.setFont(f1);
		rbt2.setFont(f1);
		rbt3.setFont(f1);
		//将字体大小按钮加入ItemListener监听器
		rbt1.addItemListener(this);
		rbt2.addItemListener(this);
		rbt3.addItemListener(this);
		//将多行文本区域加入JPanel
		add(textarea);
		//设置多行文本区域起始位置
		textarea.setBounds(0, 90, 1000, 400);
		//设置多行文本区域内的字体
		textarea.setFont(f2);
		//添加字体颜色组件到JPanel
		add(Bottomjlabel);
		//设置字体颜色组件位置
		Bottomjlabel.setBounds(100, 510, 200, 50);
		//设置字体颜色组件的字体
		Bottomjlabel.setFont(f1);
		//将字体颜色单选按钮加入按钮组
		btngroup2.add(rbt4);
		btngroup2.add(rbt5);
		btngroup2.add(rbt6);
		//将字体颜色单选按钮加入JPanel
		add(rbt4);
		add(rbt5);
		add(rbt6);
		//设置字体颜色按钮的位置
		rbt4.setBounds(400, 510, 200, 50);
		rbt5.setBounds(600, 510, 200, 50);
		rbt6.setBounds(800, 510, 200, 50);
		//设置字体颜色按钮组的字体
		rbt4.setFont(f1);
		rbt5.setFont(f1);
		rbt6.setFont(f1);
		//将字体颜色按钮加入ItemListener监听器
		rbt4.addItemListener(this);
		rbt5.addItemListener(this);
		rbt6.addItemListener(this);
		//将滑动标签文本加入JPanel
		add(Bottomjlabel2);
		//设置滑动标签文本位置
		Bottomjlabel2.setBounds(100, 580, 150, 50);
		//设置滑动标签文本的字体
		Bottomjlabel2.setFont(f1);
		//将‘滑块的值是’文本加入JPanel
		add(Bottomcenterjlabel);
		//设置‘滑块的值是’文本位置
		Bottomcenterjlabel.setBounds(300, 580, 200, 50);
		//设置‘滑块的值是’文本的字体
		Bottomcenterjlabel.setFont(f1);
		//将滑块加入JPanel
		add(slider);
		//设置滑块位置
		slider.setBounds(550, 580, 300, 50);
		//设置滑块主要刻度间距
		slider.setMajorTickSpacing(10);
		//设置滑块次要刻度间距
		slider.setMinorTickSpacing(5);
		//绘制滑块标签
		slider.setPaintLabels(true);
		//绘制滑块刻度标记
		slider.setPaintTicks(true);
		//绘制滑块滑道
		slider.setPaintTrack(true);
		//将滑块加入ChangeListener监听器
		slider.addChangeListener(this);
		//将‘十六进制’文本加入JPanel
		add(transformtoRGB);
		//设置‘十六进制’文本位置
		transformtoRGB.setBounds(100, 650, 150, 50);
		//设置‘十六进制’文本字体
		transformtoRGB.setFont(f1);
		//将十六进制单行文本框加入JPanel
		add(jtextfield);
		//设置十六进制单行文本框位置
		jtextfield.setBounds(250, 650, 120, 50);
		//设置十六进制单行文本框字体
		jtextfield.setFont(f1);
		//将转换按钮加入JPanel
		add(jbtn);
		//设置转换按钮位置
		jbtn.setBounds(400, 650, 100, 50);
		//设置转换按钮字体
		jbtn.setFont(f1);
		//设置转换按钮的事件监听为ActionListener
		jbtn.addActionListener(this);
		/**将‘R,G,B’加入JPanel
		 * 设置‘R,G,B’位置
		 * 设置‘R,G,B'字体
		 */
		add(useRGB_R);
		useRGB_R.setBounds(105, 720, 20, 50);
		useRGB_R.setFont(f1);
		add(useRGB_G);
		useRGB_G.setBounds(250, 720, 20, 50);
		useRGB_G.setFont(f1);
		add(useRGB_B);
		useRGB_B.setBounds(400, 720, 20, 50);
		useRGB_B.setFont(f1);
		/**将‘R,G,B’文本框加入JPanel
		 * 设置‘R,G,B’文本框位置
		 * 设置‘R,G,B’文本框字体
		 */
		add(R);
		R.setBounds(150, 720, 80, 50);
		R.setFont(f1);
		add(G);
		G.setBounds(300, 720, 80, 50);
		G.setFont(f1);
		add(B);
		B.setBounds(450, 720, 80, 50);
		B.setFont(f1);
		//将转换按钮加入JPanel
		add(RGBbutton);
		//设置转换按钮位置
		RGBbutton.setBounds(550, 720, 100, 50);
		//设置转换按钮字体
		RGBbutton.setFont(f1);
		//设置转换按钮的事件监听为ActionListener
		RGBbutton.addActionListener(this);
		jdialog.setSize(500,250);
		Container con = jdialog.getContentPane();
		prompt.setFont(f1);
		con.add(prompt);
		jdialog2.setSize(500,250);
		Container con2 = jdialog2.getContentPane();
		prompt2.setFont(f1);
		con2.add(prompt2);
	}
	//事件监听函数,用于监听单选按钮的发生
	public void itemStateChanged(ItemEvent e){
	    int size = 25;
	    if (rbt1.isSelected()){			//设置文字大小为10
	    	size = 10;
	    }
	    if (rbt2.isSelected()){			//设置文字大小为30
	    	size = 30;
	    }
	    if (rbt3.isSelected()){			//设置文字大小为50
	    	size = 50;
	    }
	    if(rbt4.isSelected()){
	    	textarea.setForeground(Color.RED);		//设置文字前景色(文字颜色)为红色
	    }
		if(rbt5.isSelected()){
			textarea.setForeground(Color.YELLOW);	//设置文字前景色(文字颜色)为黄色
		}
		if(rbt6.isSelected()){
			textarea.setForeground(Color.BLUE);		//设置文字前景色(文字颜色)为蓝色
		}
		//设置多行文本区域文字大小为size
	    Font font = new Font("仿宋", Font.PLAIN, size);
	    textarea.setFont(font);
	}
	//事件监听函数,用于监听滑块动作,并更改字体大小以及数字显示
	public void stateChanged(ChangeEvent e){
		if(e.getSource() == slider){
		//更改数字显示
		Bottomcenterjlabel.setText("滑块的值是"+slider.getValue());
		//更改字体大小
		Font font = new Font("仿宋",Font.PLAIN,slider.getValue());
		textarea.setFont(font);
		}
	}
	//动作事件
	public void actionPerformed(ActionEvent e){
		/**触发按钮jbtn时更改文字前景颜色
		 * (transform16To_R/G/B为十六进制转sRGB函数)
		 */
		if(e.getSource() == jbtn){
			if(jtextfield.getText().length() == 7){
				Color color = new Color(transform16To_R(jtextfield.getText()),transform16To_G(jtextfield.getText()),transform16To_B(jtextfield.getText()));
				textarea.setForeground(color);
			}else{
				/**此处十六进制代码只需判断JTextField中得到的字符串长度为7。
				 * 满足:返回字体颜色;不满足:返回弹窗
				 */
				jdialog.setLocation(550,350);		//设置弹窗位置
				jdialog.setVisible(true);			//设置弹窗是否可见
			}
			
		}
		if(e.getSource() == RGBbutton){
			/**此处sRGB值需要判断每个JTextField是否为0~255之间的值。
			 * 满足:返回字体颜色;不满足:返回弹窗
			 */
			if((Integer.parseInt(R.getText())>=0 && Integer.parseInt(R.getText())<=255)&&(Integer.parseInt(G.getText())>=0 && Integer.parseInt(G.getText())<=255)&&(Integer.parseInt(B.getText())>=0 && Integer.parseInt(B.getText())<=255)){
				Color color = new Color(Integer.parseInt(R.getText()),Integer.parseInt(G.getText()),Integer.parseInt(B.getText()));
				textarea.setForeground(color);
			}else{
				jdialog2.setLocation(550,350);		//设置弹窗位置
				jdialog2.setVisible(true);			//设置弹窗是否可见
			}
		}
	}
	//十六进制转R
	public int transform16To_R(String RGB){
		if(RGB != null && !"".equals(RGB) && RGB.length() == 7){
			//截取十六进制字符串第1,2位,并将其转换为sRGB中R型整数
			int R = Integer.valueOf(RGB.substring( 1, 3 ), 16);
			//返回R型整数
			return R;
		}
		return 0;
	}
	//十六进制转G
	public int transform16To_G(String RGB){
		if(RGB != null && !"".equals(RGB) && RGB.length() == 7){
			//截取十六进制字符串第3,4位,并将其转换为sRGB中G型整数
			int G = Integer.valueOf(RGB.substring( 3, 5 ), 16);
			//返回G型整数
			return G;
		}
		return 0;
	}
	//十六进制转B
	public int transform16To_B(String RGB){
		if(RGB != null && !"".equals(RGB) && RGB.length() == 7){
			//截取十六进制字符串第5,6位,并将其转换为sRGB中B型整数
			int B = Integer.valueOf(RGB.substring( 5, 7 ), 16);
			//返回B型整数
			return B;
		}
		return 0;
	}
}

The following is the main function part:

import javax.swing.*; 

public class Main {

	public static void main(String[] args) {
		NullLayout frame = new NullLayout("简单文本编辑器");
		frame.setLocation(300, 50);			//设置JFrame窗体位置
		frame.setSize(1000, 850);			//设置JFrame窗体大小
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		//设置JFrame窗体关闭时为直接结束程序进程
		frame.setVisible(true);				//设置JFrame窗体是否可见,默认false
	}

}

Finally, show the results of the code operation!

insert image description here

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

1. Introduction to Python

The following content is the basic knowledge necessary for all application directions of Python. If you want to do crawlers, data analysis or artificial intelligence, you must learn them first. Anything tall is built on primitive foundations. With a solid foundation, the road ahead will be more stable.All materials are free at the end of the article!!!

Include:

Computer Basics

insert image description here

python basics

insert image description here

Python introductory video 600 episodes:

Watching the zero-based learning video is the fastest and most effective way to learn. Following the teacher's ideas in the video, it is still very easy to get started from the basics to the in-depth.

2. Python crawler

As a popular direction, reptiles are a good choice whether it is a part-time job or as an auxiliary skill to improve work efficiency.

Relevant content can be collected through crawler technology, analyzed and deleted to get the information we really need.

This information collection, analysis and integration work can be applied in a wide range of fields. Whether it is life services, travel, financial investment, product market demand of various manufacturing industries, etc., crawler technology can be used to obtain more accurate and effective information. use.

insert image description here

Python crawler video material

insert image description here

3. Data analysis

According to the report "Digital Transformation of China's Economy: Talents and Employment" released by the School of Economics and Management of Tsinghua University, the gap in data analysis talents is expected to reach 2.3 million in 2025.

With such a big talent gap, data analysis is like a vast blue ocean! A starting salary of 10K is really commonplace.

insert image description here

4. Database and ETL data warehouse

Enterprises need to regularly transfer cold data from the business database and store it in a warehouse dedicated to storing historical data. Each department can provide unified data services based on its own business characteristics. This warehouse is a data warehouse.

The traditional data warehouse integration processing architecture is ETL, using the capabilities of the ETL platform, E = extract data from the source database, L = clean the data (data that does not conform to the rules), transform (different dimension and different granularity of the table according to business needs) calculation of different business rules), T = load the processed tables to the data warehouse incrementally, in full, and at different times.

insert image description here

5. Machine Learning

Machine learning is to learn part of the computer data, and then predict and judge other data.

At its core, machine learning is "using algorithms to parse data, learn from it, and then make decisions or predictions about new data." That is to say, a computer uses the obtained data to obtain a certain model, and then uses this model to make predictions. This process is somewhat similar to the human learning process. For example, people can predict new problems after obtaining certain experience.

insert image description here

Machine Learning Materials:

insert image description here

6. Advanced Python

From basic grammatical content, to a lot of in-depth advanced knowledge points, to understand programming language design, after learning here, you basically understand all the knowledge points from python entry to advanced.

insert image description here

At this point, you can basically meet the employment requirements of the company. If you still don’t know where to find interview materials and resume templates, I have also compiled a copy for you. It can really be said to be a systematic learning route for nanny and .

insert image description here
But learning programming is not achieved overnight, but requires long-term persistence and training. In organizing this learning route, I hope to make progress together with everyone, and I can review some technical points myself. Whether you are a novice in programming or an experienced programmer who needs to be advanced, I believe that everyone can gain something from it.

It can be achieved overnight, but requires long-term persistence and training. In organizing this learning route, I hope to make progress together with everyone, and I can review some technical points myself. Whether you are a novice in programming or an experienced programmer who needs to be advanced, I believe that everyone can gain something from it.

Data collection

This full version of the full set of Python learning materials has been uploaded to the official CSDN. If you need it, you can click the CSDN official certification WeChat card below to get it for free ↓↓↓ [Guaranteed 100% free]

insert image description here

Good article recommendation

Understand the prospect of python: https://blog.csdn.net/SpringJavaMyBatis/article/details/127194835

Learn about python's part-time sideline: https://blog.csdn.net/SpringJavaMyBatis/article/details/127196603

Guess you like

Origin blog.csdn.net/weixin_49892805/article/details/132038903