嗨,我正在使用 JTextPane 中的 JLabel 列出在线用户名。
我使用 JLabel 是因为我希望名称可以点击我可以使用 styleddocument 水平对齐它们现在我的问题是
如何删除最近插入的 JLabel?我尝试了 JTextPane 的 remove 方法,但没有用。当用户离线时,我需要删除 JLabel。
我的代码:
public static void getUsernames()
{
try{
String query = "SELECT username FROM members WHERE status = 'offline'";
ps3 = con.prepareStatement(query);
rs2 = ps3.executeQuery();
}catch(Exception ex){ex.printStackTrace();}
}
public static void resultGetUsername(JTextPane jtp,StyledDocument sd)
{
try {
while (rs2.next())
{
final JLabel jl = new JLabel(rs2.getString("username"));
final String username = rs2.getString("username");
Border d = BorderFactory.createEmptyBorder(1,10,1,10);
Border d2 = BorderFactory.createLineBorder(Color.BLACK);
Border d3 = BorderFactory.createCompoundBorder(d2,d);
jl.setFont(new Font("Calibri",Font.BOLD,16));
jl.setBorder(d3);
jl.setOpaque(true);
jl.setBackground(Color.ORANGE);
jl.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
jl.setForeground(new Color(30,144,255));
}
public void mouseExited(MouseEvent arg0) {
jl.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
jl.setForeground(new Color(210,105,30));
jl.setBackground(new Color(154,205,50));
}
public void mouseReleased(MouseEvent e) {
jl.setBackground(Color.ORANGE);
jl.setForeground(Color.BLACK);
if(e.getClickCount() ==2)
new OneToOneChat(username);
}
});
Cursor c = new Cursor(Cursor.HAND_CURSOR);
jl.setCursor(c);
jtp.insertComponent(jl);
sd.insertString(sd.getLength(), "\n", SubPanel1.sas);
}
} catch (SQLException e) {
} catch (BadLocationException e) {
}
finally{
if (rs2 != null) {
try {
rs2.close();
} catch (SQLException sqlEx) { }
rs2 = null;
}
if (ps3 != null) {
try {
ps3.close();
} catch (SQLException sqlEx) { }
ps3 = null;
}
}
}