Change the Form element color using the Button Event in Java


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.

  1. //change jpanel color
  2. if (jComboBox1.getSelectedItem().equals("Red")){
  3. jPanel1.setBackground(Color.RED);
  4. }else if (jComboBox1.getSelectedItem().equals("Green")){
  5. jPanel1.setBackground(Color.GREEN);
  6. }else if (jComboBox1.getSelectedItem().equals("Blue")){
  7. jPanel1.setBackground(Color.BLUE);
  8. }else if (jComboBox1.getSelectedItem().equals("Yellow")){
  9. jPanel1.setBackground(Color.YELLOW);
  10. }
  11. //change txt color
  12. if (jComboBox2.getSelectedItem().equals("Red")){
  13. jLabel1.setForeground(Color.RED);
  14. jLabel2.setForeground(Color.RED);
  15. jComboBox1.setForeground(Color.RED);
  16. jComboBox2.setForeground(Color.RED);
  17. jButton1.setForeground(Color.RED);
  18. }else if (jComboBox2.getSelectedItem().equals("Green")){
  19. jLabel1.setForeground(Color.GREEN);
  20. jLabel2.setForeground(Color.GREEN);
  21. jComboBox1.setForeground(Color.GREEN);
  22. jComboBox2.setForeground(Color.GREEN);
  23. jButton1.setForeground(Color.GREEN);
  24. }else if (jComboBox2.getSelectedItem().equals("Blue")){
  25. jLabel1.setForeground(Color.BLUE);
  26. jLabel2.setForeground(Color.BLUE);
  27. jComboBox1.setForeground(Color.BLUE);
  28. jComboBox2.setForeground(Color.BLUE);
  29. jButton1.setForeground(Color.BLUE);
  30. }else if (jComboBox2.getSelectedItem().equals("Yellow")){
  31. jLabel1.setForeground(Color.YELLOW);
  32. jLabel2.setForeground(Color.YELLOW);
  33. jComboBox1.setForeground(Color.YELLOW);
  34. jComboBox2.setForeground(Color.YELLOW);
  35. jButton1.setForeground(Color.YELLOW);
  36. }

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.

Facebook Comments


Please enter your comment!
Please enter your name here