JAVA语言编程练习--图形界面--按钮交换

2021/12/4 17:16:41

本文主要是介绍JAVA语言编程练习--图形界面--按钮交换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、效果展示: 

 

 

代码1: 

package Homework01;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;

public class swap01 extends JFrame {
	
	JButton jb1 = new JButton("来打我呀!");
	JButton jb2 = new JButton("不要误伤我!");
	Box boxcase,boxleft,boxright;
	
	
	swap01()
	{
		boxleft = Box.createVerticalBox();
		boxleft.add(jb1);
		
		boxright = Box.createVerticalBox();
		boxright.add(jb2);
		
		boxcase = Box.createHorizontalBox();
		boxcase.add(boxleft);
		boxcase.add(Box.createHorizontalStrut(10));
		boxcase.add(boxright);
		
		setLayout(new FlowLayout());
		add(boxcase);
		
		jb1.addActionListener(new Alistener());
		jb2.addActionListener(new Alistener());
		
		setBounds(120,125,300,200);
		setVisible(true);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}
	
	//内部类不需要写修饰符
	class Alistener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			if(e.getActionCommand().equals("来打我呀!"))
			{
				String s1 = jb1.getText();
				String s2 = jb2.getText();
				jb2.setText(s1);
				jb1.setText(s2);
			}
			else if(e.getActionCommand().equals("不要误伤我!"))
			{
				String s1 = jb1.getText();
				String s2 = jb2.getText();
				jb2.setText(s1);
				jb1.setText(s2);
			}
		}
		
	}
	
}

代码2:

 

package Homework01;

public class swapmain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new swap01();
	}

}



这篇关于JAVA语言编程练习--图形界面--按钮交换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程