方案一:使用标签
package First;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class _9_图形页面与事件处理例题 {
public static void main(String[] args) {
new JiaFaFrame1("图形页面与事件处理");
}
}
class JiaFaFrame1 extends JFrame{
JLabel lab;
JButton jbtn ;
JPanel jp1,jp2;
JiaFaFrame1(String title){
super(title);
lab = new JLabel("0");
jbtn = new JButton("按钮(+5)");
jbtn.addActionListener(new MyMointor3());
jp1 = new JPanel();
jp2 = new JPanel();
this.setLayout(new GridLayout(2,1));
this.add(jp1);
this.add(jp2);
jp1.add(lab);
jp2.add(jbtn);
//窗体的属性设置(前两个参数时位置,后两个参数是大小)
this.setBounds(300, 300, 100, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
//内部类
class MyMointor3 implements ActionListener{
public void actionPerformed(ActionEvent e) {
String s1 = lab.getText();
int n =Integer.parseInt(s1);
n += 5 ;
String s2 = String.valueOf(n);
lab.setText(s2);
}
}
}
每一次点击按钮数值都会相加5
方案二:使用标签
package First;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class _a1_图形页面与事件处理例题2 {
public static void main(String[] args) {
new JiaFaFrame2("图形页面与事件处理");
}
}
class JiaFaFrame2 extends JFrame{
JLabel lab;
JButton jbtn ;
JPanel jp;
JiaFaFrame2(String title){
super(title);
lab = new JLabel("0",JLabel.CENTER);
jbtn = new JButton("按钮(+5)");
jbtn.addActionListener(new MyMointor3());
jp = new JPanel();
jp.setLayout(new GridLayout(2,1));
this.add(jp);
jp.add(lab);
jp.add(jbtn);
//窗体的属性设置(前两个参数时位置,后两个参数是大小)
this.setBounds(500, 500, 150, 130);
//设置窗体的大小刚好能够容纳组件
//this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
//内部类
class MyMointor3 implements ActionListener{
public void actionPerformed(ActionEvent e) {
String s1 = lab.getText();
int n =Integer.parseInt(s1);
n += 5 ;
String s2 = String.valueOf(n);
lab.setText(s2);
}
}
}
方案三:使用文本框
package First;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class _a2_图形页面与事件处理例题3 {
public static void main(String[] args) {
new JiaFaFrame3("图形页面与事件处理");
}
}
class JiaFaFrame3 extends JFrame{
JTextField jtf;
JButton jbtn ;
JPanel jp;
JiaFaFrame3(String title){
super(title);
jtf = new JTextField("0");//设置默认值初始为0
//将文本居中
jtf.setHorizontalAlignment(JTextField.CENTER);
jbtn = new JButton("按钮(+5)");
jbtn.addActionListener(new MyMointor3());
jp = new JPanel();
jp.setLayout(new GridLayout(2,1));
this.add(jp);
jp.add(jtf);
jp.add(jbtn);
//窗体的属性设置(前两个参数时位置,后两个参数是大小)
this.setBounds(500, 500, 150, 130);
//设置窗体的大小刚好能够容纳组件
//this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
//内部类
class MyMointor3 implements ActionListener{
public void actionPerformed(ActionEvent e) {
String s1 = jtf.getText();
int n =Integer.parseInt(s1);
n += 5 ;
String s2 = String.valueOf(n);
jtf.setText(s2);
}
}
}