Change the Form element color using the Button Event in Java

0
471

This tutorial entitled “Change the Form element color using the Button Event in Java” will teach you on how you can change the element color added to your JFrame. Please follow all the steps to complete this tutorial.

Java is composed of javax.Swing element to create and design the GUI (Graphical User Interface). Every element composed of Text, Color, alignment, Size and etc. properties. By modifying the following properties, it can help our Java GUI design more attractive.

Change JFrame element color using Button Event in Java Steps

  1. Add or Create a new JFrame inside your project.

2. Add the following element and design your form just look like the image below.

3. Double click your button and add the following codes below.

[java]//change jpanel color
if (jComboBox1.getSelectedItem().equals(“Red”)){
jPanel1.setBackground(Color.RED);
}else if (jComboBox1.getSelectedItem().equals(“Green”)){
jPanel1.setBackground(Color.GREEN);
}else if (jComboBox1.getSelectedItem().equals(“Blue”)){
jPanel1.setBackground(Color.BLUE);
}else if (jComboBox1.getSelectedItem().equals(“Yellow”)){
jPanel1.setBackground(Color.YELLOW);
}
//change txt color
if (jComboBox2.getSelectedItem().equals(“Red”)){
jLabel1.setForeground(Color.RED);
jLabel2.setForeground(Color.RED);
jComboBox1.setForeground(Color.RED);
jComboBox2.setForeground(Color.RED);
jButton1.setForeground(Color.RED);
}else if (jComboBox2.getSelectedItem().equals(“Green”)){
jLabel1.setForeground(Color.GREEN);
jLabel2.setForeground(Color.GREEN);
jComboBox1.setForeground(Color.GREEN);
jComboBox2.setForeground(Color.GREEN);
jButton1.setForeground(Color.GREEN);
}else if (jComboBox2.getSelectedItem().equals(“Blue”)){
jLabel1.setForeground(Color.BLUE);
jLabel2.setForeground(Color.BLUE);
jComboBox1.setForeground(Color.BLUE);
jComboBox2.setForeground(Color.BLUE);
jButton1.setForeground(Color.BLUE);
}else if (jComboBox2.getSelectedItem().equals(“Yellow”)){
jLabel1.setForeground(Color.YELLOW);
jLabel2.setForeground(Color.YELLOW);
jComboBox1.setForeground(Color.YELLOW);
jComboBox2.setForeground(Color.YELLOW);
jButton1.setForeground(Color.YELLOW);
}[/java]

4. Run your program and the output should look like the image below.

This program uses if statement to perform the correct algorithm. The if Statement will identify what color to execute in the Form.

NO COMMENTS

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.