A few days ago, I encountered a Swing error when trying to change the transparency of the JFrame (undecorated), which lost its color and transparency information.
When the application starts, it starts as “transparent,” then I change it to ‘opaque’ (no problems up to that point), but when I try to change it back to “transparent,” the error mentioned above appears.
Here is the code that show the problem:
public class TheSwingError extends JFrame {
Color transparent = new Color( 255, 0, 0, 100 ),
opaque = new Color( 255, 0, 0, 255 );
public TheSwingError() {
feel();
setDefaultCloseOperation( javax.swing.WindowConstants.EXIT_ON_CLOSE );
setBounds( 10, 10, 500, 500 );
setUndecorated( true );
setLayout( null );
setBackground( transparent );
JButton alternate = new JButton( "Transparent" );
alternate.setBounds( 10, 10, 160, 26 );
add( alternate );
setVisible( true );
alternate.addMouseListener( new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked( java.awt.event.MouseEvent evt ) {
JButton aux = ( JButton ) evt.getSource();
if( aux.getText().equals( "Transparent" ) ) {
setBackground( opaque );
aux.setText( "Opaque" );
}
else {
setBackground( transparent );
aux.setText( "Transparent" );
}
}
} );
}
private void feel() {
try {
for( javax.swing.UIManager.LookAndFeelInfo info: javax.swing.UIManager.getInstalledLookAndFeels() ) {
if( "Nimbus".equals( info.getName() ) ) {
javax.swing.UIManager.setLookAndFeel( info.getClassName() );
break;
}
}
}
catch( ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e ) {
e.printStackTrace();
}
}
public static void main( String[] args ) {
SwingUtilities.invokeLater( () -> {
new TheSwingError();
} );
}
}
How can I fix this without resorting to overwriting the paintComponent() method?.
As you will see in my response, this post is intended, rather than to provide a way to achieve the objective, to prevent others from wasting a considerable amount of time solving a problem that stems from a language bug.
JFrame
. It may have aJFrame
as the top-level element of a GUI, but you should distinguish. In most cases you can and should build your GUI with stock classes. This is certainly such a case.