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