辛苦工作之后,我的咔嚓声工作得很好。不幸的是,当我将JTextPane
的格式更改为"text/html"
并向JTextPane添加文本时,我的按钮就会消失。我几乎受够了这个严厉的女主人。有人能帮忙吗?
代码如下。。。
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.JButton;
import java.applet.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class jlabeltest extends Applet {
public void init() {
jlabeltest textPaneExample = new jlabeltest();
textPaneExample.setSize(550, 300);
textPaneExample.setVisible(true);
}
public jlabeltest() {
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
InlineB button = new InlineB("Button");
textPane.setText("<p color='#FF0000'>Cool!</p>");
button.setAlignmentY(0.85f);
button.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
JOptionPane.showMessageDialog(null,"Hello!");
// Right Click
}
if (SwingUtilities.isLeftMouseButton(e)) {
JOptionPane.showMessageDialog(null,"Click!");
// Left Click
}
}
});
textPane.insertComponent(button);
this.add(textPane);
}
}
最佳答案
在添加组件时,此内容类型似乎有问题(请参见thispost),但您可以尝试以下操作:
JTextPane textPane = new JTextPane();
JButton button = new JButton("Button");
button.setAlignmentY(0.85f);
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
textPane.setEditorKit(kit);
textPane.setDocument(doc);
try {
kit.insertHTML(doc, doc.getLength(), "<p color='#FF0000'>Cool!", 0, 0, HTML.Tag.P);
kit.insertHTML(doc, doc.getLength(), "<p></p>", 0, 0, null);
} catch (BadLocationException ex) {
} catch (IOException ex) {
}