I am creating a Java application and use Swing for the UI. I would like to add some JButtons with icons instead of text. However, when I set the icon on the button, the icon becomes very ugly.
The icon is 20x20, and the JButton I place the icon on is also 20x20, but on the JButton the icon looks like this:
(Screenshot from Netbeans IDE)
How do I fix this?
Here is the code (just copied from Netbeans):
package com.mycompany.mavenproject2;
public class Test extends javax.swing.JFrame {
/** Creates new form Test*/
public Test() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS));
jButton1.setIcon(new javax.swing.ImageIcon(path_to_file)); // NOI18N
jButton1.setMaximumSize(new java.awt.Dimension(20, 20));
jButton1.setMinimumSize(new java.awt.Dimension(20, 20));
jButton1.setPreferredSize(new java.awt.Dimension(20, 20));
getContentPane().add(jButton1);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
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 (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}