I'm trying to add a JComponent onto a Jpanel whenever I switch my selection for daysOfTheWeek comboBox. However, it doesn't seem to work, but only works when I put it ouside of theactionPerformed(ActionEvent e) method. What am I doing wrong? Here is my simplified code:
public class App extends JFrame {
public static final int WIDTH = 1900;
public static final int HEIGHT = 1000;
JPanel scheduleArea;
private String[] days = {"Monday", "Tuesday"};
public App() {
super("Schedule");
scheduleArea = new JPanel();
initializeGraphics();
}
public void initializeGraphics() {
setMinimumSize(new Dimension(WIDTH, HEIGHT));
getContentPane().setBackground(Color.LIGHT_GRAY);
getContentPane().setLayout(null);
createScheduleArea();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createScheduleArea() {
JPanel schedulePanel = new JPanel();
schedulePanel.setBounds(850,40,990,870);
schedulePanel.setLayout(null);
scheduleArea.setBounds(25,105,940,740);
scheduleArea.setBackground(new java.awt.Color(197,218,221));
JComboBox daysOfTheWeek = new JComboBox(days);
daysOfTheWeek.setBounds(750,30,200,45);
schedulePanel.add(daysOfTheWeek);
daysOfTheWeek.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedDay = (String) daysOfTheWeek.getSelectedItem();
switch (selectedDay) {
case "Monday":
scheduleArea.add(new JLabel("Monday")); // JLabel not added
break;
case "Tuesday":
scheduleArea.add(new JLabel("Tuesday"));
break;
default:
System.out.println("Please select");
}
}
});
schedulePanel.add(scheduleArea);
add(schedulePanel);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
Generally, you design a Swing GUI so that you create all the Swing components once. Then, you update the values of the Swing Components.
Generally, you create a Swing GUI from the inside out. You define your Swing components and
JPanelsand let theJFramesize itself.Here's a GUI I came up with, based on your GUI.
I use a
JFrame. The only time you should extend aJFrame, or any Java class, is when you want to override one or more of the class methods.I created two separate
JPanels, one for theJComboBoxand one for theJTextArea. I added aJButtonto the combo box panel so you could select the same day more than once. I used aJTextAreaso I could define one Swing component and append the text.Here's the complete runnable code.