Search code examples
javaswingjdialog

Why does this JDialog not draw properly when called from a JFrame?


I'm having a problem with the display of a JDialog when called from a JFrame. The JFrame only contains a button. When pressed, this launches a JDialog with a JLabel, JTextField and JButton.

The JFrame displays fine. The JDialog displays strangely, kinda like it's trying to draw it (or elements of it) offset multiple times! As you move the mouse around over different components, it keeps refreshing, but still weirdly. As soon as you use the mouse to resize the JDialog, it behaves normally (doesn't matter whether you increase/decrease the size).

This is how it first appears:

The dialog showing JButtons drawn weirdly

After resizing it a little, it is drawn properly:

The dialog drawn properly after resizing

Where am I going wrong please?

import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;


public class Demo extends JFrame implements Runnable {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Demo());
    }
    
    public void run() {
        setTitle("My JFrame");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton btn = new JButton("Launch JDialog");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Dlg();
            }
        });
        add(btn);
        pack();
        setVisible(true);
    }
}
    

class Dlg extends JDialog {
    public Dlg() {
        setTitle("My JDialog");
        
        JPanel pnl = new JPanel();
        pnl.setLayout(new BoxLayout(pnl, BoxLayout.X_AXIS));
        
        JLabel lbl1 = new JLabel("Label 1");
        JTextField txt1 = new JTextField(5);
        JButton btn1 = new JButton("Button 1");
        
        pnl.add(lbl1);
        pnl.add(txt1);
        pnl.add(btn1);
        
        add(pnl);
        
        pack();
        setVisible(true);
    }
}

Edit

This is on Windows 10 with JDK 17.0.2


Solution

  • I've found a similar issue descibed in an Apache NetBeans Bugzilla. Comment 7, by "everflux", describes setting a JVM parameter:

    I assume this is due to Java 8 enbabling the xrender extension by default. I have serious graphics issues with Netbeans 8/Java 8 on Nvidia machine, flickering, windows only scrolling partly etc.

    I added the following flag to the netbeans startup options: -J-Dsun.java2d.opengl=true

    this seemed to mitigate the problems, at least during a 10 minute test period. I encourage other users experiencing graphics problems to test it and report their results.

    Adding -Dsun.java2d.opengl=true either on the command line or in Eclipse as a VM argument in the Run Configuration has fixed it for me.