0
솔직히, 나는 이것을 조사했다. 나는 약간의 대답 here을 찾았고 명확하게 이해하지 못한다. 왜냐하면 나는 내 코드에서 색을 재현 할 수 없기 때문이다.JEditorPane에서 특정 텍스트를 색으로 설정
특정 줄을 빨간색으로 표시하고 싶습니다. 나는 JEditorPane
과 Style
을 사용했지만, 나는 이해하지 못합니다.
여기에 전체 코드
public class Window extends JFrame implements ActionListener{
private JButton theButton = new JButton("Calculer sur 100");
private JTextPane text = new JTextPane();
private JTextField textField = new JTextField("Écrire un nombre");
private JScrollPane scroller = new JScrollPane(text);
private StringBuilder sb = new StringBuilder();
private StyledDocument doc = text.getStyledDocument();
private Style style;
public Window() {
setLayout(new BorderLayout());
setTitle("Test");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
theButton.addActionListener(this);
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(theButton, BorderLayout.SOUTH);
setVisible(true);
}
/**
* Prints the result on text
* @param num
*/
private void print100(int num) {
for (int i = 1; i < num + 1; i++) {
text.setText(appendString(i));
}
}
/**
* convert the number to string
* @param i
* @return a string that contains the information
*/
private String appendString(int i){
double a = doMath(i, checkForNumber());
String s = "";
if(a < 60){
style = text.addStyle("red", null);
StyleConstants.setForeground(style, Color.red);
s = "\n" + i + " : " + a;//This need to be red
}
else
s = "\n" + i + " : " + a;
return sb.append(s).toString();
}
/**
* Check if the text in the text is numbers
* return numl
*/
private int checkForNumber() {
int numl;
try {
numl = Integer.parseInt(textField.getText());
} catch (NumberFormatException e) {
text.setText("Essayer avec des nombres...");
return 0;
}
return numl;
}
/**
* leave specific number of digit after the dot
* return myNum
*/
private double doMath(int i, int num) {
double myNum = ((double) i/num) * 100;
int precision = 100; //Number of zero = number of digits
myNum = Math.floor(myNum * precision + .5)/precision;
return myNum;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == theButton) {
text.setText("");
print100(checkForNumber());
}
}
은}의
어떻게 모든 특정 라인이 JEditorPane
에 빨간색 표시 할 수 있습니까?
문제를 나타내는 [실행 가능한 예제] (https://stackoverflow.com/help/mcve)를 제공하십시오. 이것은 덜 혼란스럽고 더 나은 응답이 될 것입니다. – MadProgrammer
@mad 저기 있습니다. 나는 다른 사람이 달릴 것이라고 생각했다. 미안하다. – Chax
@mad 귀하의 예를 사용하여 [여기] (http://stackoverflow.com/questions/18948148/jeditorpane-set-foreground-color-for-different-words?lq=1) 나는 어떤 텍스트를 색칠 수 있지만 나도 원했어. 게다가 내가 인쇄하고 싶었던 텍스트의 첫 부분은 나타나지 않았다. – Chax