我要求文字包装+文本居中+ Nimbus外观和感觉+背景颜色为黑色。 我尝试了以下两个组件 1. JTextPane -------支持:使用StyledDocument进行文本换行+文本居中 -------问题:自定义背景颜色不起作用Nimbus外观(禁用或启用) 这是在这里显示的错误http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=ab1938d61a7fd83ca2b54eb8df7?bug_id=6789980
我的jdk版本是:1.6.0_33 尝试修复:
UIManager.getLookAndFeelDefaults().put("TextPane.background", Color.RED);
但这也无法覆盖Nimbus默认值,即#d6d9df(214,217,223) 任何人都可以帮我解决JTextArea中的文本居中问题吗?提前致谢
1. JTextArea -------支持:使用Nimbus LnF进行文本环绕+背景着色(仅在启用时) -------问题:文本居中是这里的一个问题
要使文本居中,您应该使用JTextPane而不是JTextArea。居中文本是一个大问题。
最好用JTextPane解决背景问题。
使用Nimbus LAF时,您需要提供自定义Painter才能将背景绘制为纯色。查看@mKorbel的answer。您需要更改属性标记。同样在FillPainter中我改变了:
g.setColor(color);
g.setColor(object.getBackground());
谢谢......工作,,,,这就是我用过的......
UIManager.getLookAndFeelDefaults().put("TextPane[Enabled].backgroundPainter", new FillPainter());`
public class FillPainter implements Painter<JComponent> {
@Override
public void paint(Graphics2D g, JComponent object, int width,int height) {
g.setColor(object.getBackground());
}
}
我使用它来在JTextArea中居中文本
public static void centerText (JTextArea ta)
{
BufferedImage fake1 = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D fake2 = fake1.createGraphics();
FontMetrics fm = fake2.getFontMetrics(ta.getFont());
int lines = ta.getLineCount();
ArrayList<String> list = new ArrayList<>();
try
{
for (int i = 0; i < lines; i++)
{
int start = ta.getLineStartOffset(i);
int end = ta.getLineEndOffset(i);
String line = ta.getText(start, end - start).replace("\n","");
list.add (line.trim());
}
}
catch (BadLocationException e)
{
System.out.println(e);
}
alignLines (list, fm, ta);
}
private static void alignLines (ArrayList<String> list, FontMetrics fm, JTextArea ta)
{
String leading = " ";
int longest = -1;
for (String s : list)
{
if (fm.stringWidth(s) > longest)
longest = fm.stringWidth(s);
}
for (int n=0; n<list.size(); n++)
{
String s = list.get(n);
if (fm.stringWidth(s) >= longest)
continue;
while (fm.stringWidth(s) < longest)
s = ' '+s+' ';
list.set(n, s);
}
StringBuilder sb = new StringBuilder();
for (String s : list)
{
sb.append(leading).append(s).append('\n');
}
ta.setText (sb.toString());
}
使用填充的JTextArea作为参数调用CenterText