这是一个有效的例子:
import javax.swing.*;
import java.awt.*;
public class ScratchSpace {
public static void main(String[] args) {
JFrame frame = new JFrame("");
final MyTextPane textPane = new MyTextPane();
frame.add(textPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class MyTextPane extends JTextPane {
public MyTextPane() {
super();
setText("Hello World");
setOpaque(false);
// this is needed if using Nimbus L&F - see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6687960
setBackground(new Color(0,0,0,0));
}
@Override
protected void paintComponent(Graphics g) {
// set background green - but can draw image here too
g.setColor(Color.GREEN);
g.fillRect(0, 0, getWidth(), getHeight());
// uncomment the following to draw an image
// Image img = ...;
// g.drawImage(img, 0, 0, this);
super.paintComponent(g);
}
}
}
Run Code Online (Sandbox Code Playgroud)
需要注意的重要事项:
你的组件不能是不透明的...所以setOpaque(false);
覆盖paintComponent(Graphics g),而不是paint.
在调用super.paintComponent(g)之前用图像或绘图绘制背景;
如果你想掌握这些东西,我建议阅读"肮脏的富客户",这本书都是关于如何根据自己的意愿弯曲Swing.
| 归档时间: |
|
| 查看次数: |
5753 次 |
| 最近记录: |