1
JTextPaneは2つのJLabelが挿入されています。いずれかのラベルがクリックされた場合、AAAからクリックされたコンテンツに変更されます。 JTextPaneの内の要素をJTextPane - コンポーネント値を取得
このコードを反復は:
for(int i = 0; i < tp.getDocument().getLength(); i++) {
System.out.println(((StyledDocument) tp.getDocument()).getCharacterElement(i));
}
は、どのように私はSTDに「」「クリック」AAAAを印刷したラベルにアクセスすることができますか?
package texteditor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import javax.swing.JButton;
public class JTextPaneExample extends JPanel {
private JTextPane tp;
public JTextPaneExample() {
setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Text Content", TitledBorder.LEADING, TitledBorder.TOP, null, null));
add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane, BorderLayout.CENTER);
tp = new JTextPane();
tp.setEditable(false);
scrollPane.setViewportView(tp);
JLabel lbl = new JLabel("AAAA ");
lbl.setOpaque(true);
lbl.setBorder(BorderFactory.createLineBorder(Color.black, 1));
lbl.addMouseListener(new LabelAdapter2(lbl));
tp.insertComponent(lbl);
lbl = new JLabel("BBBB ");
lbl.setOpaque(true);
lbl.setBorder(BorderFactory.createLineBorder(Color.black, 1));
lbl.addMouseListener(new LabelAdapter2(lbl));
tp.insertComponent(lbl);
JButton btnNewButton = new JButton("Write content");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
iterateOverContent(tp);
}
});
panel.add(btnNewButton, BorderLayout.SOUTH);
}
private void iterateOverContent(JTextPane tp2) {
for(int i = 0; i < tp.getDocument().getLength(); i++) {
System.out.println(((StyledDocument) tp.getDocument()).getCharacterElement(i));
}
}
private class LabelAdapter2 extends MouseAdapter {
private JLabel lblNewLabel;
public LabelAdapter2(JLabel lbl) {
this.lblNewLabel = lbl;
}
public void mouseClicked(MouseEvent evt) {
lblNewLabel.setText("clicked");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("GoBoard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JTextPaneExample());
frame.setPreferredSize(new Dimension(400, 400));
frame.pack();
frame.setVisible(true);
}
}