如何解决Java Swing:为按钮使用图标会使图标变得丑陋
我正在创建一个 Java 应用程序并使用 Swing 作为 UI。我想添加一些带有图标而不是文本的 JButton。但是,当我在按钮上设置图标时,图标变得非常难看。
图标是 20x20,我放置图标的 JButton 也是 20x20,但在 JButton 上,图标看起来像这样:
我该如何解决这个问题?
这是代码(刚刚从 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,ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE,ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE,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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。