java - 使用 Nimbus Look And Feel 时无法在 JTextArea 背景上绘制图像

标签 java swing background-image jtextarea

我在 JTextArea 背景上绘制图像,它是使用其他外观(Metal、Windows 等)绘制的,但是当我使用 Nimbus Look And Feel 时它确实如此不绘制图像可能是什么问题以及如何解决? 这是我正在使用的代码

图像文本区域类

public class ImageTextArea extends JTextArea{
    File image;
    public ImageTextArea(File image)
    {
        setOpaque(false);
        this.image=image;
    }

    @Override
    public void paintComponent(final Graphics g)
    {
        try
        {
            // Scale the image to fit by specifying width,height
            g.drawImage(new ImageIcon(image.getAbsolutePath()).getImage(),0,0,getWidth(),getHeight(),this);
            super.paintComponent(g);
        }catch(Exception e){}
    }
}

和测试类

public class TestImageTextArea extends javax.swing.JFrame {

    private ImageTextArea tx;

    public TestImageTextArea() {
        tx = new ImageTextArea(new File("img.jpg"));
        setTitle("this is a jtextarea with image");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel mainp = new JPanel(new BorderLayout());
        add(mainp);
        mainp.add(new JScrollPane(tx), BorderLayout.CENTER);
        setSize(400, 400);
    }

    public static void main(String args[]) {
/*
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            System.out.println("Unable to use Nimbus LnF: "+ex);
        }
*/
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TestImageTextArea().setVisible(true);
            }
        });
    }

}

当我删除评论时,它不会绘制图像。

最佳答案

基本上,当您调用 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 的职责,填充背景,绘制我们的背景,然后在 UI 委托(delegate)上调用 paint

enter image description here

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();
        }

    }
}

别搞错了。如果您没有正确执行此操作,它不仅会损坏此组件,而且可能会损坏屏幕上的大多数其他组件。

关于java - 使用 Nimbus Look And Feel 时无法在 JTextArea 背景上绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17879079/

相关文章:

java - 如何判断JTextPane中所选文本的大小是否不同?

iOS - 动画背景图片 (GIF)

css - 底部固定图像,如所附截图所示

Java Applet : Call JavaScript - JSObject. getWindow(this) 总是返回 null

java - HyperLinkListener 未触发 - java swing

java - 我无法从其他设备连接到 Flask 服务器(=不是来自本地主机)

java - 在弹出窗口中使用 TextBubbleBorder

java - JPanel 上的永久背景图像

Java Spring RestTemplate POST 问题,而 Postman 工作

java - Metro 服务和 WCF 客户端之间的传输安全