Проблема заключается в том, где я объявляю и назначаю:
String emotionText = (String) emotions.getSelectedItem();
Я пытаюсь использовать его позже для сравнения с одним из элементов массива из JcomboBox. Где я говорю
if (emotionText.equals("Happy") {
JLabel newText = new JLabel(verse);
panel2.add(newText);
}
т.е. если результат такой... то сделайте это, но это не работает должным образом. Любое понимание будет высоко оценено. Заранее спасибо.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JComboBox {
public static void main(String[] args) {
JFrame frame = new JFrame("Mood Food");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900, 800);
frame.setLocation(430, 100);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // added code
frame.add(panel);
var name = javax.swing.JOptionPane.showInputDialog("What is your name?");
JLabel lblName = new JLabel(name + " ,welcome to the Mood Food Program");
lblName.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(lblName);
JLabel lbl = new JLabel("How are you feeling today?");
lbl.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(lbl);
String[] choices = {"Select..", "Happy", "Content", "Grateful", "Excited", "Sad",
"Angry", "Lonely", "Heartbroken", "Worried"};
JComboBox emotions = new JComboBox(choices);
emotions.setMaximumSize(panel.getPreferredSize());
emotions.setAlignmentX(Component.CENTER_ALIGNMENT);
emotions.setAlignmentY(Component.TOP_ALIGNMENT);
String emotionText = (String) emotions.getSelectedItem();
panel.add(emotions);
String verse = Happy.Verses();
JPanel panel2 = new JPanel();
panel2.setVisible(false);
frame.add(panel2);
if (emotionText.equals("Happy") {
JLabel newText = new JLabel(verse);
panel2.add(newText);
}
JButton btn = new JButton("OK");
btn.setAlignmentX(Component.CENTER_ALIGNMENT); // added code
panel.add(btn);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
boolean visible = panel.isVisible();
panel.setVisible(!visible);
panel2.setVisible(visible);
}});
frame.setVisible(true); // added code
}
}
Подробнее здесь: https://stackoverflow.com/questions/784 ... -assign-it