JEditorPane translucent background selection bug

2019-09-02 03:08发布

问题:

I have a JEditorPane, inside a JScrollPane (both transparrent). These are inside a JPanel which have a translucent background. When i select the text inside the JEditorPane i get this strange bug:

So the other elements which arent in the same JPanel, "ghost" around the selection, more seen in this screenshot:

Java GUI is a first for me, i've only done server-side applications with no gui's.

Code for the panel:

    @SuppressWarnings("serial")
    public class NewsPanel extends JPanel {

    private JEditorPane newsArea;


    public NewsPanel() {
        setLayout(new BorderLayout());
        setBackground(new Color(226, 0, 0, 179));
        loadContent();
        setSize(500,400);
    }

    private void loadContent() {
        newsArea = new JEditorPane();
        newsArea.setEditable(false);
        newsArea.setBorder(BorderFactory.createEmptyBorder());
        newsArea.setSelectionColor(Color.GRAY);
        newsArea.setOpaque(false);
        newsArea.setBackground(new Color(0, 0, 0, 0));

        HTMLEditorKit kit = new HTMLEditorKit();
         StyleSheet styleSheet = kit.getStyleSheet();
         styleSheet.addRule("A {color:#0088CC}");
         styleSheet.addRule("#newsHeader {font-weight:bold;font-size:14px;color:#339933;}");
         styleSheet.addRule("#newsBody {font-size:10px;padding-left:20px;}");
         newsArea.setEditorKit(kit);


        JScrollPane scrollPane = new JScrollPane(newsArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        add(scrollPane, BorderLayout.CENTER);

        scrollPane.getViewport().setBackground(new Color(0, 0, 0, 0));
        scrollPane.getViewport().setOpaque(false);
        scrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
        scrollPane.setOpaque(false);
        scrollPane.setBackground(new Color(0, 0, 0, 0));
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
    }

    @Override
    public boolean isOptimizedDrawingEnabled() {
        return false;
    }

    public void reload() {
        removeAll();
        loadContent();
        validate();
        repaint();
    }
}

Any ideas how to fix? I'm sure its something simple, but like i say, i'm new to UI's

回答1:

These are inside a JPanel which have a translucent background. When i select the text inside the JEditorPane i get this strange bug:

Check out Backgrounds With Transparency for the probably problem and a couple of solutions.