java settext 用不了_Java中的JTextPane调用setText方法之后没有效果可能是什么原因?...

写程序会遇上很多自我觉得诡异的问题,无论是老手还是新手。

遇到这种事情的时候,我最喜欢的、也是用起来非常有效的方式。是“制造一个新的工程,专门测试自我觉得可能的问题”。

这里是一段类似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很隐蔽,不调试一下不知道什么情况。

所以,这个方式你可以学着用用,这是“渔”。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值