[英]How to add word tags in to JTextField?
我正在創建Java Swing應用程序。 我想將標簽添加到JTextField
。 添加標簽時,我可以搜索要添加的其他標簽。 就像堆棧溢出一樣。
是否有任何jar文件可以做到這一點? 請告訴我是否還有其他解決方案。
基本上,您需要在一個面板中添加2個jlables
,然后將該面板添加到另一個面板中。
我創建了一個名為“ Tagpanel
”的自定義面板,並將新的TagPanel添加到面板中。
這就是它的外觀。您應根據情況使用適當的布局。
示例代碼
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.