即使在编写代码后,JLabel也不会变得不透明?

时间:2017-06-09 13:27:30

标签: java swing background jlabel

我的JFrame表单中有一个标签和一个按钮。我想要做的是 - 当用户点击按钮时,标签变成黑色。

我去了表单,右键单击标签并将背景设置为黑色,然后我双击了JButton并在

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)

我写的方法

lbl.setOpaque(true);

但即使在我单击测试运行按钮后,它也不会变黑!我注意到的另一件事是,如果我使用setToolTipText()方法(用于在悬停时显示字符串)然后从标签中移除鼠标(即,取消悬停标签),该区域保持黑色,这是有意的。

有没有人有理由说这"故障"正在发生什么?

编辑: - 这是一个screenshot,如果有帮助的话。

更新: - 我试过你的方法@coinbird,它仍然无法正常工作!再次出现同样的问题,在悬停和移除光标后变为黑色..

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JLabel;


public class background_test2 extends javax.swing.JFrame {

/**
 * Creates new form background_test2
 */
public background_test2() {
    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();
    lbl = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    lbl.setBackground(new java.awt.Color(0, 0, 0));
    lbl.setForeground(new java.awt.Color(255, 0, 0));
    lbl.setText("Hover HERE!!");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(44, 44, 44)
                    .addComponent(jButton1))
                .addGroup(layout.createSequentialGroup()
                    .addGap(151, 151, 151)
                    .addComponent(lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(94, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jButton1)
            .addGap(18, 18, 18)
            .addComponent(lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(122, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         



    JLabel lbl2 = new JLabel("Test");
    lbl2.setBackground(Color.BLACK);
    lbl2.setOpaque(true);


}                                        


/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    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(background_test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(background_test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(background_test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(background_test2.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 background_test2().setVisible(true);
        }
    });



}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JLabel lbl;
// End of variables declaration                   

}

2 个答案:

答案 0 :(得分:1)

JLabel lbl2 = new JLabel("Test");
lbl2.setBackground(Color.BLACK);
lbl2.setOpaque(true);

该代码没有做任何事情。

您可以创建新标签,但不要将标签添加到框架中。

您需要将添加到框架的标签设为不透明:

lbl = new javax.swing.JLabel();
lbl.setOapaque(true);

每当你提出一个问题发布一个正确的Minimal and Complete Example,我们就可以确切地看到你在做什么。我们无法猜测您是否在ActionListener中创建了新标签。

答案 1 :(得分:0)

您必须在lbl.setOpaque(true);执行任何操作之前设置背景颜色

lbl.setBackground(Color.Black);

确保您在代码中执行此操作。我喜欢手工编写而不是信任GUI工具箱的东西。

这里有更多信息。这个网站看起来像垃圾,但信息很好:http://mindprod.com/jgloss/setopaque.html