java如何在按下按钮后使程序返回ID?
This program return 0, need to stop/pause program, press button and then return ID.
static int ID=0;
static String log="";
static String pass="";
static SessionFactory factory;
public static int enterStudent(JPanel panel){
panel.setLayout(null);
JLabel jLabel=new JLabel("Login");
panel.add(jLabel);
jLabel.setBounds(10,10,100,30);
JLabel jLabel1=new JLabel("Password");
panel.add(jLabel1);
jLabel1.setBounds(110,10,100,30);
final JTextArea textArea=new JTextArea();
textArea.setBounds(10,50,100,50);
panel.add(textArea);
final JTextArea textArea2=new JTextArea();
textArea2.setBounds(110,50,100,50);
panel.add(textArea2);
JButton enterButton=new JButton("Enter");
enterButton.setBounds(10,100,200,50);
panel.add(enterButton);
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ActionListener
enterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e2) {
log=textArea.getText();
pass=textArea2.getText();
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List students = session.createQuery("FROM Student").list();
for (Iterator iterator =
students.iterator(); iterator.hasNext();){
Student student = (Student) iterator.next();
if((student.getLogin().equals(log))&&(student.getPassword().equals(pass))){
ID=student.getId();//this should be returned
JOptionPane.showMessageDialog(null,"return="+ID);
break;
}
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
});
return ID; //returns 0
}
This is function for LogIn, check login and pass in DATABASE. Need return ID of student, but program returns 0
# 1 楼答案
这意味着程序控制未到达此块,因此您的ID将获得默认定义值,即0
这里的if条件不是true,这意味着getLogin()和getPassword的值都不是“”
# 2 楼答案
您不能从ActionListener返回任何内容,因为它的方法
actionPerformed(...)
被定义为返回void
,不返回任何内容。但幸运的是你不需要这么做。这是一个Swing GUI,在ActionListener内部,通过调用myLabel.setText(...)
在JLabel中显示ID,或者在需要显示ID的其他位置显示ID。或者,如果不想显示它,则调用某个类的setId(...)
方法请注意,这个问题的真正规范答案是使用M-V-C或模型-视图-控件类型设计模式,并在ActionListener(控件的一部分)中,将模型的id字段设置为在数据库中找到的值。GUI应该将侦听器连接到模型,如果模型的状态发生变化,侦听器将更新GUI的状态(显示的数据)。但是对于你的简单程序来说,这可能有点过分了
其他方面的建议:
setBounds()
可能会像创建复杂GUI的最简单和最好的方式一样吸引新手,但您创建的Swing GUI越多,在使用它们时遇到的困难就越严重。当GUI调整大小时,它们不会调整您的组件的大小,它们是一个需要增强或维护的皇家女巫,当它们放置在滚动窗格中时会完全失败,当在所有平台或屏幕分辨率与原始分辨率不同的情况下查看时,它们看起来非常糟糕李>编辑:我现在看到您正试图通过JButton的ActionListener从enterStudent方法返回一个int。这不会像编写的那样工作,因为您在ActionListener完成之前返回id字段。解决方案包括使用某种类型的回调方法,该方法可能会传递到enterStudent的方法参数中,或者如果使用JOptionPane提供的模式对话框。否则,基于复杂性的增加,那么是的,您最好使用M-V-C结构,它本身就是基于侦听器(回调)的使用