有没有办法将JLabel添加到JtextArea?因为我尝试add
但它没有工作并将其设置为可见true,是否允许在JTextArea中添加JLabel?通过追加?
这是我目前无效的代码
jta = new JTextArea();
jta.setEditable(false);
jta.setLineWrap(true);
jta.setWrapStyleWord(true);
jta.setFont(new Font("calibri", Font.PLAIN,16));
jlArray = new JLabel("radsjhkaljk sadf");
jta.add(jlArray);
jta.setVisible(true);
jspTextField = new JScrollPane(jta);
每次添加邮件时,我都可以将JLabel附加到JTextArea中吗?
答案 0 :(得分:4)
JTextArea
不是插入swing
或其中任何其他组件的适当JLabels
组件。您可以使用JTextPane
来实现此目的。例如,考虑下面给出的代码:
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*;
class JLabelToTextPane extends JFrame implements ActionListener
{
JTextField tf;
JTextPane tp ;
JButton click;
StyledDocument doc;
SimpleAttributeSet attr;
public void createAndShowGUI()
{
setTitle("Add JLabel to JTextPane");
tf = new JTextField(10);
tp = new JTextPane();
click = new JButton("Click");
doc = tp.getStyledDocument();
attr = new SimpleAttributeSet();
JScrollPane pane = new JScrollPane(tp);
JPanel nPanel = new JPanel();
nPanel.add(tf);nPanel.add(click);
tf.addActionListener(this);
click.addActionListener(this);
Container c = getContentPane();
c.add(nPanel,BorderLayout.NORTH);
c.add(pane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);setLocationRelativeTo(null);setVisible(true);
}
@Override
public void actionPerformed(ActionEvent evt)
{
String text = tf.getText();
if (text!=null && !"null".equals(text) && !"".equals(text.trim()))
{
JLabel label = new JLabel(text);
label.setOpaque(true);
label.setBackground(Color.gray);
label.setBorder(BorderFactory.createLineBorder(Color.black,1));
tp.setCaretPosition(tp.getDocument().getLength());
tp.insertComponent(label);
label.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
String text = ((JLabel)evt.getSource()).getText();
JOptionPane.showMessageDialog(JLabelToTextPane.this,"Hi, My text is "+text,"Information",JOptionPane.INFORMATION_MESSAGE);
}
});
try
{
doc.insertString(doc.getLength(), " ", attr );
}
catch (BadLocationException ex)
{
ex.printStackTrace();
}
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater( new Runnable()
{
@Override
public void run()
{
JLabelToTextPane lta = new JLabelToTextPane();
lta.createAndShowGUI();
}
});
}
}