给大家推荐个靠谱的公众号程序员探索之路,大家一起加油
主类:
import java.awt.*;
public class 猜数字 {
public static void main(String[] args) {
window win=new window();
win.setTitle("猜数字");
win.setBounds(100, 100, 300, 300);
Container c=win.getContentPane();
c.setBackground(Color.green);//设置背景颜色
}
}
window类
import javax.swing.*;
import java.awt.*;
public class window extends JFrame{
JButton button1,button2;
JLabel b1;
JTextField text;
public window(){
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init(){
setLayout(new FlowLayout());
button1=new JButton("(点击)得到一个随机数");
add(button1);
text =new JTextField(10);
b1=new JLabel("");
add(b1);
add(text);
button2=new JButton("确定");
add(button2);
action ac=new action();
ac.setJlabel(b1);
ac.settext(text);
button1.addActionListener(ac);
action2 a=new action2();
a.setabel(b1);
a.settext(text);
button2.addActionListener(a);
}
}
action类
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class action implements ActionListener{
int num;
JLabel abel;
JTextField text;
public void setJlabel(JLabel abel){
this.abel=abel;
}
public void settext(JTextField text){
this.text=text;
}
JButton b1=new JButton("(点击)得到一个随机数");
JButton b2=new JButton("确定");
public void actionPerformed(ActionEvent e) {
Random rd=new Random();
num=rd.nextInt(100)+1;
abel.setText("请输入你的猜测");
init();
}
int init(){
return num;
}
}
action2类
import java.awt.event.*;
import javax.swing.*;
public class action2 implements ActionListener{
action a=new action();
int num=a.init();
JTextField text;
JLabel abel;
public void settext(JTextField text){
this.text=text;
}
public void setabel(JLabel abel){
this.abel=abel;
}
public void actionPerformed(ActionEvent e){
int guess=0;
try{
guess=Integer.parseInt(text.getText());
if(guess==num){
abel.setText("猜对了!");
}
if(guess>num){
abel.setText("猜大了!");
text.setText(null);
}
if(guess<num){
abel.setText("猜小了!");
text.setText(null);
}
}
catch(NumberFormatException event){
abel.setText("请输入数字字符!");
text.setText(null);
}
}
}