如何在JTextField中添加单词标签?

时间:2014-11-02 03:15:57

标签: java swing swingx

我正在创建Java Swing应用程序。我想为JTextField添加标签。当我添加标签时,我可以搜索另一个标签进行添加。与堆栈溢出相同。

有没有jar文件可以做到这一点?请告诉我是否有其他解决方案。

example image tag http://imageshack.com/a/img674/925/kQRLxw.jpg

1 个答案:

答案 0 :(得分:5)

基本上你需要在一个面板中添加2 jlables,然后将该面板添加到另一个面板。

我创建了一个名为" Tagpanel"的自定义面板并将新的TagPanel添加到面板。

这就是它的外观。你应该对你的案例采用适当的布局。

enter image description here

示例代码

public class Example extends JFrame {

    static Example example;
    JPanel panel;

    String tagarr[] = {"swing", "java", "c++", "awt"};

    public Example() {
        setSize(new Dimension(500, 80));
        GridBagLayout layout = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        setLayout(layout);
        c.gridx = 0;
        c.gridy = 0;

        panel = new JPanel();
        panel.setPreferredSize(new Dimension(400, 20));
        panel.setLayout(new FlowLayout(1, 2, 2));
        panel.setBackground(Color.white);
        panel.setBorder(javax.swing.BorderFactory.createLineBorder(Color.magenta));
        add(panel,c);
        JTextField t = new JTextField("type here", 10);
        t.setBorder(null);
        t.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tagcheck(evt);
            }

            private void tagcheck(KeyEvent evt) {
                String s = t.getText();
                if (s.length() > 0) {
                    for (String tag : tagarr) {
                        if (s.equals(tag)) {
                            TagPanel tagp1 = new TagPanel(s);
                            panel.add(tagp1, panel.getComponentCount() - 1);
                            t.setText("");
                            repaint();
                            revalidate();
                        }
                    }
                }
            }
        });

        panel.add(t);
        setVisible(true);
    }

    public void removecomp(JPanel p) {
        panel.remove(p);
        repaint();
        revalidate();
    }

    public static void main(String[] args) {
        example = new Example();
    }
}

TagPanel.java

public class TagPanel extends JPanel {

    public TagPanel(String text) {
        JLabel textlable = new JLabel(text);
        JLabel close = new JLabel("X");
        close.setOpaque(true);
        close.setBackground(new Color(123, 123, 123));
        textlable.setOpaque(true);
        textlable.setBackground(new Color(0,185,203));
        textlable.setForeground(Color.white);
        setLayout(new BorderLayout());
        close.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                Example.example.removecomp(TagPanel.this);
            }
        });
        add(close, BorderLayout.EAST);
        add(textlable, BorderLayout.WEST);
    }

}