将jPanel背景颜色更改为RGB值

时间:2018-04-22 09:45:45

标签: java swing netbeans jframe jpanel

我正在尝试创建一个简单的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值。我有什么方法可以做到吗?

1 个答案:

答案 0 :(得分: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);