首页 > 解决方案 > 如何在 jLabel 中应用新行?

问题描述

我想使用 jLabel 在多行中显示数据库中的值。我尝试使用 html 技巧,但我不知道如何在我的代码中应用它。我只是得到错误。也许我做错了。哈哈。

     try{
            //display doctor's name by selected classification
            String url = "jdbc:mysql://localhost/sched";
            Connection conn = DriverManager.getConnection(url,"root","");
            Statement stmt = conn.createStatement();
            String classification = comboClass.getSelectedItem().toString();
            String sqlSelect= "select * from doctorsched where class = '"+classification+"'";
            ResultSet rs = stmt.executeQuery(sqlSelect); 
            String finalText ="";
        while(rs.next()){
             String docsName= rs.getString("docName");
             String room = rs.getString("room");
             String days = rs.getString("day");
             String from = rs.getString("timefrom");
             String to = rs.getString("timeto");
             
             finalText += docsName+" (room "+room+", "+days+", "+from+"-"+to+") \\n";
             // i want to display values from database in many lines but using jLabel
             
        }
        jLabel10.setText(finalText);
      
} catch (Exception ex) {
  
    Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}

这样的东西应该是我的输出

doc riza (room 104, Every Thursday, 10:30AM-10:00AM)
doc j (room 101, null, 10:30AM-11:30AM)
doc lea (room 102, Every Saturday, 10:30AM-4:30PM)
frida (room 101, null, 8:00AM-9:30AM)

请帮帮我:( '\n' 在 jTextArea 中有效,但在 jLabel 中无效。我也在标签中尝试了 '\n',但也不起作用。

好的,所以我尝试了这个

finalText += "<html>"+docsName+" (room "+room+", "+days+", "+from+"-"+to+")<br></html>";

但是这段代码只显示一行。我的数据库中的第一行。我需要显示所有行。

现在,下一个代码显示了这一切,但下一行仍然不起作用。

while(rs.next()){
             String docsName= rs.getString("docName");
             String room = rs.getString("room");
             String days = rs.getString("day");
             String from = rs.getString("timefrom");
             String to = rs.getString("timeto");
             
             finalText += docsName+" (room "+room+", "+days+", "+from+"-"+to+")\n";
        }
        jLabel10.setText("<html>"+finalText+"<br></html>");
} 

为什么

标签: javamysqlswingnewlinejlabel

解决方案


使用这样的代码

String finalText = "";
for (int i = 0; i < 10; i++) {
    finalText += "line:" + i;
    finalText += "<br>";
}
label.setText("<html>" + finalText + "</html>");

推荐阅读