import javax.swing.*;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
//The class extends JFrame for GUI purposes, and implements ActionListener
//so events can take place within the JFrame.
public class FinalProject extends JFrame implements ActionListener
{
//First, I declare GUI elements: the JLabel that lets the user know what the program does,
//my choice of font, the "Submit Fruit" button that the user will press
//once they have selected their fruit, and a place holder label that will eventually
//display a final message.
JLabel label = new JLabel("I can tell you the colors of certain fruits!");
Font font = new Font("Times New Roman", Font.BOLD, 20);
JButton submit = new JButton("Submit Fruit");
JLabel lastLabel = new JLabel(" ");
//The following two parallel arrays contain the selection of fruits and their respective colors.
String[] fruit = {"Apples", "Bananas", "Blueberries", "Limes", "Oranges"};
String[] color = {"red", "yellow", "blue", "green", "orange"};
//Now the JComboBox is created, and the fruit array is used as an argument so that the fruits
//will all appear in the drop down menu. Also, constants that will be used for the width and height
//of the JFrame are also declared.
JComboBox fruitChoice = new JComboBox(fruit);
final int WIDTH = 425;
final int HEIGHT = 200;
Container con = getContentPane();
//Here is where the constructor is formed, and all necessary elements will be added.
public FinalProject()
{
super("Final Program");
//First, the size of the JFrame is set, default close operation is set to exit on close,
// the layout is set, and the font of the first label is set.
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
label.setFont(font);
//Now the GUI components will be added, adding an action listener to the submit button
//so that it can trigger an event.
con.add(label);
con.add(fruitChoice);
con.add(submit);
submit.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int index = fruitChoice.getSelectedIndex();
for(int x = 0; x < 5; x++)
{
if(x == index)
{
lastLabel.setText(fruit[x] + " are " + color[x]);
lastLabel.setFont(font);
if(x == 0)
{
lastLabel.setForeground(Color.RED);
}
if(x == 1)
{
lastLabel.setForeground(Color.YELLOW);
}
if(x == 2)
{
lastLabel.setForeground(Color.BLUE);
}
if(x == 3)
{
lastLabel.setForeground(Color.GREEN);
}
if(x == 4)
{
lastLabel.setForeground(Color.ORANGE);
}
con.add(lastLabel);
}
}
invalidate();
validate();
}
public static void main(String[] args)
{
FinalProject frame = new FinalProject();
frame.setVisible(true);
}
}