基本上,当你打电话时super.paintComponent
,它将调用 UI delgate 的update
方法。这就是奇迹发生的地方。
下面是 Nimbus 的SynthTextAreaUI
执行
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
SynthLookAndFeel.update(context, g);
context.getPainter().paintTextAreaBackground(context,
g, 0, 0, c.getWidth(), c.getHeight());
paint(context, g);
context.dispose();
}
正如您所看到的,它实际上绘制了背景,而不考虑组件的不透明状态,然后调用paint
,这将调用BasicTextUI.paint
方法(通过super.paint
)
这很重要,因为BasicTextUI.paint
实际上绘制了文本。
那么,这对我们有什么帮助呢?通常情况下,我会把不打电话的人钉在十字架上super.paintComponent
,但这正是我们要做的,但我们会提前知道我们要承担的责任。
首先,我们要承担以下责任update
,填充背景,绘制我们的背景然后调用paint
在 UI 委托上。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class NimbusTest {
public static void main(String[] args) {
new NimbusTest();
}
public NimbusTest() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(new TestTextArea()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestTextArea extends JTextArea {
private BufferedImage bg;
public TestTextArea() {
try {
bg = ImageIO.read(new File("C:\\Users\\swhitehead\\Documents\\My Dropbox\\Ponies\\Rainbow_Dash_flying_past_3_S2E16.png"));
} catch (IOException ex) {
Logger.getLogger(NimbusTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
// Fill the background, this is VERY important
// fail to do this and you will have major problems
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
// Draw the background
g2d.drawImage(bg, 0, 0, this);
// Paint the component content, ie the text
getUI().paint(g2d, this);
g2d.dispose();
}
}
}
不犯错误。如果您没有正确执行此操作,它不仅会损坏该组件,而且可能会损坏屏幕上的大多数其他组件。