写程序会遇上很多自我觉得诡异的问题,无论是老手还是新手。
遇到这种事情的时候,我最喜欢的、也是用起来非常有效的方式。是“制造一个新的工程,专门测试自我觉得可能的问题”。
这里是一段类似JTextPane的hello world代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class JTextPaneExample {
public static void main(String args[]) throws BadLocationException {
JFrame frame = new JFrame("JTextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
JTextPane pane = new JTextPane();
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setBold(attributeSet, true);
// Set the attributes before adding text
pane.setCharacterAttributes(attributeSet, true);
pane.setText("Welcome");
attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.red);
StyleConstants.setBackground(attributeSet, Color.blue);
Document doc = pane.getStyledDocument();
doc.insertString(doc.getLength(), "To Java ", attributeSet);
attributeSet = new SimpleAttributeSet();
doc.insertString(doc.getLength(), "World", attributeSet);
JScrollPane scrollPane = new JScrollPane(pane);
cp.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
我使用Intellij测试正常。你可以跑一下,然后对照着自己的代码或者在这个hello world上加入你自己的代码,慢慢逼近真相。
后话:
你这个问题,别人可能要看的代码才能帮到你。但你没有贴出来。可是即使你贴出来了,也许代码很多,没人愿意看。或者bug很隐蔽,不调试一下不知道什么情况。
所以,这个方式你可以学着用用,这是“渔”。