当前位置: 代码迷 >> J2SE >> 高手帮小弟我看看,swing的有关问题
  详细解决方案

高手帮小弟我看看,swing的有关问题

热度:98   发布时间:2016-04-24 16:32:06.0
高手帮我看看,swing的问题
import   java.awt.*;
import   java.awt.event.*;
import   javax.swing.*;

public   class   ComponentTest   extends   JFrame   {

private   JTextField   jtextfield1;
private   JTextField   jtextfield2;
private   JButton   jbutton;
int   randomNumber;
int   typedNumber;

public   ComponentTest(){
super( "Testing   JFrame ");
Container   container   =   getContentPane();
container.setLayout(new   FlowLayout());
jtextfield1   =   new   JTextField( "随机数字! ",10);
jtextfield1.setEditable(false);
jtextfield2   =   new   JTextField( "请输入数字 ",10);
             
                jbutton   =   new   JButton( "Start ");
container.add(jtextfield1);
container.add(jtextfield2);
container.add(jbutton);


TextFieldHandler   handler   =   new   TextFieldHandler();
jtextfield2.addActionListener(handler);
jbutton.addActionListener(handler);
setSize(325,100);
setVisible(true);
}
public   static   void   main(String   args[]){
ComponentTest   component   =   new   ComponentTest();
component.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//定义私有内部类
private   class   TextFieldHandler   implements   ActionListener{
public   void   actionPerformed(ActionEvent   e)   {

try{
if(e.getSource()   ==   jtextfield2)
typedNumber   =   Integer.parseInt(e.getActionCommand());
if(e.getSource()   ==   jbutton)
randomNumber   =   (int)(Math.random()*100+1);
if(typedNumber   >   randomNumber)
JOptionPane.showMessageDialog(null,   "大了 ");
else   if   (typedNumber   <   randomNumber)
JOptionPane.showMessageDialog(null, "小了 ");
else
JOptionPane.showMessageDialog(null, "恭喜你,答对了 ");

}catch   (Exception   exception){
JOptionPane.showMessageDialog(null,   "请检查你输入的信息 ");
}



}
}

}
一个比数字的程序,数字范围在1-100;
这个程序运行结果无论我输入什么数字,它都说数字小了。请高手帮我看看哪里出错了。


------解决方案--------------------
上面的貌似还是不行,看看我的

private class TextFieldHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jbutton)
{
int k = 1;
do
{

try
{
typedNumber = Integer.parseInt(jtextfield2.getText());

}catch (Exception exception)
{
System.out.println( "typedNumber "+typedNumber);
JOptionPane.showMessageDialog(null, "请检查你输入的信息 ", " ",
JOptionPane.DEFAULT_OPTION);
break;

}

randomNumber = (int) (Math.random() * 100 + 1);

//System.out.println(typedNumber);
//System.out.println(randomNumber);

if (typedNumber > randomNumber)
JOptionPane.showMessageDialog(null, "大了 ");
else if (typedNumber < randomNumber)
JOptionPane.showMessageDialog(null, "小了 ");
else
JOptionPane.showMessageDialog(null, "恭喜你,答对了 ");