删除最近在JTextPane上添加JLabel

时间:2013-05-15 02:39:55

标签: java swing jlabel jtextpane

您好我在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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用从JTextPane中删除标签 setText("")getStyledDocument().remove(0, doc.getLength())

如果您需要获取此帖子可能有用的标签:Get a component from a JTextPane through javax.swing.text.Element?

然后将您想要的标签添加回JTextPane