编程包含一个标签和一个按钮,单击按钮时,标签的内容在"你好"和"再见"之间切换

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Mr_wxc/article/details/93467847

编程包含一个标签和一个按钮,单击按钮时,标签的内容在"你好"和"再见"之间切换。

package exercise;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class changeGUI extends JFrame{
	private JButton button;
	private JLabel label;
	public changeGUI() {
		super();
		JPanel jPanel=new JPanel();
		JPanel jPanel2=new JPanel();
		setLayout(new GridLayout(2,1));
		button=new JButton("切换");
		button.setBackground(Color.gray);
		button.setForeground(Color.RED);
		jPanel.add(button);
		button.addActionListener(new changeActionListener());
		label=new JLabel("你好");
		label.setForeground(Color.BLUE);
		jPanel2.add(label);
		add(jPanel2);
		add(jPanel);
	}
 
	private class changeActionListener implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			if(label.getText()=="你好") {
				label.setText("再见");
			}else {
				label.setText("你好");
			}
		}
	}
	
	public static void main(String[] args) {
		changeGUI change=new changeGUI();
		change.setSize(300,200);
		change.setVisible(true);
		change.setLocationRelativeTo(null);
		change.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

}

运行结果如下:

经过测试,可以放心使用

猜你喜欢

转载自blog.csdn.net/Mr_wxc/article/details/93467847