【问题标题】:Change a jPanel Background Color to an RGB Value将 jPanel 背景颜色更改为 RGB 值
【发布时间】:2018-04-22 09:45:44
【问题描述】:

我正在尝试制作一个简单的 Hello World 应用程序,当您单击按钮时,它将 jPanel 的背景颜色更改为随机颜色。这是我的代码:

import java.util.Random;

public class Window extends javax.swing.JFrame {

/**
 * Creates new form Window
 */

public int r;
public int g;
public int b;
public int color;
Random colorOut = new Random();

public Window() {
    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() {

    colorPanel = new javax.swing.JPanel();
    colorBtn = new javax.swing.JButton();
    exitBtn = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout colorPanelLayout = new javax.swing.GroupLayout(colorPanel);
    colorPanel.setLayout(colorPanelLayout);
    colorPanelLayout.setHorizontalGroup(
        colorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 0, Short.MAX_VALUE)
    );
    colorPanelLayout.setVerticalGroup(
        colorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 204, Short.MAX_VALUE)
    );

    colorBtn.setText("Color!");
    colorBtn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            colorBtnActionPerformed(evt);
        }
    });

    exitBtn.setText("Exit :(");
    exitBtn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            exitBtnActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(colorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(colorBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(exitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(colorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(colorBtn)
                .addComponent(exitBtn))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

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

private void colorBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
    color = colorOut.nextInt(9) + 1;

    switch (color) {
        case 1:
            r = 255;
            g = 17;
            b = 17;
            break;
        case 2:
            r = 255;
            g = 151;
            b = 17;
            break;
        case 3:
            r = 255;
            g = 255;
            b = 17;
            break;
        case 4:
            r = 17;
            g = 255;
            b = 100;
            break;
        case 5:
            r = 10;
            g = 120;
            b = 50;
            break;
        case 6:
            r = 20;
            g = 160;
            b = 255;
            break;
        case 7:
            r = 25;
            g = 20;
            b = 255;
            break;
        case 8:
            r = 240;
            g = 20;
            b = 255;
            break;
        case 9:
            r = 110;
            g = 10;
            b = 120;
            break;
    }


}                                        

private void exitBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
    System.exit(1);
}                                       

/**
 * @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(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Window.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 Window().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton colorBtn;
private javax.swing.JPanel colorPanel;
private javax.swing.JButton exitBtn;
// End of variables declaration                   

}

(其他大部分内容只是 NetBeans 代码生成。)

注意colorBtnActionPerformed函数

我遇到的大多数其他问题都得到了改变它的回复,例如:

setBackground(Color.BLUE);

但我想将其设置为某个 RGB 值。有什么办法可以做到吗?

【问题讨论】:

    标签: java swing netbeans jframe jpanel


    【解决方案1】:

    看看Color类可能的构造函数:

    Color(int rgb)
    Color(int r, int g, int b)
    Color(int r, int g, int b, int a)
    Color(float r, float g, float b)
    Color(float r, float g, float b, int a)
    

    因此,对于带有十六进制代码 #92f442 的颜色,您可以调用

    setBackground(new Color(0x92f442));
    

    setBackground(new Color(146, 244, 66));
    

    setBackground(new Color(0.57255f, 0.95686f, 0.25882f));
    

    所以我建议将背景设置为随机颜色:

    Random rand = new Random();
    Color col = new Color(rand.nextInt(255),rand.nextInt(255),rand.nextInt(255));
    setBackground(col);
    

    【讨论】:

    • 我收到一条错误消息,提示找不到适合 setBackground(Color) 的方法,是的,我确实说过 panelName.setBackground(col)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2012-02-19
    • 2015-09-15
    • 2017-02-23
    • 2014-01-19
    • 1970-01-01
    相关资源
    最近更新 更多