如何获得返回值到标签值

时间:2013-06-10 08:51:10

标签: java swing jlabel

您好我已经编写了这段代码,我在这段代码中尝试的是获取方法的返回值到java swing标签

这是我的代码:

public static int search(java.util.Date date)
    {

         Connection conn = null;
         ResultSet rs = null;
         Statement st = null;
           int b=0;
          try
          {

          conn=DBMgr.openConnection();      
          DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
          String dateStr=formatter.format(date);  
          System.out.println("date"+dateStr);
          String sqlQuery = "select sum(time_spend) as Time_Billed_Per_Day,datetime from time_entry  where datetime like '"+dateStr+"%' ";


              st = conn.createStatement();
               rs = st.executeQuery(sqlQuery); 

               while(rs.next())
              {

                      b = rs.getInt(1);
                     System.out.println("BILL of the date u specified is:"+b);         
               }
        }
        catch(SQLException ex) 
        {
             System.out.println(ex.toString());  
        }
        finally
        {
            try
            {

                if(rs!=null)
                    rs.close();
                if(conn!=null)
                    DBMgr.closeConnection(conn);
            }
           catch(Exception ex)
           {
           }

        }
      return b;
      }

这是代码:

JLabel lblTimeBilledDayText = new JLabel( "00:45:20" , JLabel.RIGHT);
pnlOuter.add(lblTimeBilledDayText);

我希望得到方法的返回值来代替“00:45:20”

怎么做?

4 个答案:

答案 0 :(得分:7)

试试这个

JLabel lblTimeBilledDayText = new JLabel(String.valueOf(search(date)) , JLabel.RIGHT);
pnlOuter.add(lblTimeBilledDayText);

答案 1 :(得分:5)

如果b是返回int值,那么

JLabel lblTimeBilledDayText = new JLabel(new String(Integer.toString(b)), JLabel.RIGHT);
pnlOuter.add(lblTimeBilledDayText);

答案 2 :(得分:5)

int searchResult = search( date);
// convert to String. You might want to opt for a method 
// which offers more formatting options
String searchResultAsString = Integer.toString( searchResult );

JLabel lblTimeBilledDayText = new JLabel( searchResultAsString , JLabel.RIGHT);
pnlOuter.add(lblTimeBilledDayText);

话虽这么说,你不应该在同一个线程上混合数据库查询和Swing对象修改/创建。必须在事件调度线程(EDT)上处理Swing对象,并且不应在EDT上执行长时间运行的操作(例如数据库查询),因为在操作发生时UI将被阻止/不响应。

查看Concurrency in Swing教程以获取更多信息。典型的解决方案是使用SwingWorker在工作线程上执行查询。查询完成后,SwingWorker有一个简单的机制来在正确的线程上更新Swing组件。

答案 3 :(得分:3)

JLabel lblTimeBilledDayText = new JLabel(搜索(@ year,@ month,@ date,00,45,20),JLabel.RIGHT);