0

I am new to Java GUI, and learning to create a JPanel, then use the same panel to switch different content on it. When I click on the button for the first time, the information showed up and if I click the button "back" and click the button "Leadership Training" again, nothing showed up. I have tried to use removeAll(), repaint() and revalidate() on allContentPanel() but it won't work.

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.Image;
import java.awt.event.*;
import java.text.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioSystem;
import java.io.File;

public class Execute extends JFrame implements ActionListener
{
    private static CardLayout cardLayout = new CardLayout();
    private static JPanel cardPanels,panelMenu,panelInfo,panelSub,allContentPanel;
    private static JScrollPane scrollpane1;
    private static Font titleFont = new Font(Font.DIALOG,Font.BOLD,30);     
    private static Font contentFont = new Font(Font.DIALOG,Font.PLAIN,20);    
    private static Font spacingFont = new Font(Font.DIALOG,Font.PLAIN,5);    
    private static ArrayList<JTextArea> info,leadershipInfo,timeInfo;  

    public Execute()
    {
        super("Training Management System");
        setSize(1500,800);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        init();
    
        setVisible(true);
    }

    public static void main(String[] args)
    {
        new Execute();
    }
    
    public void init()
    {
        cardPanels = new JPanel();
        cardPanels.setLayout(cardLayout);
    
        allContentPanel = new JPanel();
        panelMenu = new JPanel(null);
        panelInfo = new JPanel(null);
        panelSub = new JPanel(null);
    
        cardPanels.add(panelMenu,"menu");
        cardPanels.add(panelInfo,"infoMenu");
        cardPanels.add(panelSub,"subInfo");
    
        add(cardPanels);
    
        leadershipInfo = new ArrayList <JTextArea> ();
        leadershipInfo.add(new JTextArea(" 1. Understand emotional intelligence and how to demonstrate it in the workplace."));
        leadershipInfo.add(new JTextArea(" 2. Become self-aware and learn how to build meaningful relationships."));
        leadershipInfo.add(new JTextArea(" 3. Understand how to build and maintain leadership presence."));
        leadershipInfo.add(new JTextArea(" 4. Study in depth the essentials of leadership, like how to motivate your team."));
        leadershipInfo.add(new JTextArea(" 5. Go through management essentials, like how to communicate effectively."));
        leadershipInfo.add(new JTextArea(" 6. Understand how leadership models are put into practice personally, locally, and globally."));
        leadershipInfo.add(new JTextArea(" 7. Gain a greater understanding of their own personal identities and how their identities shape their leadership " + "\n     and followership."));
        leadershipInfo.add(new JTextArea(" Great leaders are individuals who are passionate and confident about their work, and they inspire others in the " + 
                                      "\n process. Become self-aware, confident and able to make a great first impression. Gain practical knowledge of " + 
                                      "\n team work, communication and how to motivate your team at work. Whether you are new to  management  or " + 
                                      "\n have plenty of experience, this course is a helpful and informative guide. Our learning material  is  available  to " + 
                                      "\n students 24/7 anywhere in the world, so it is extremely convenient. These intensive online courses are open to " + 
                                      "\n everyone, as long as you have an interest in the topic! We provide world-class learning, so you can be assured " + 
                                      "\n that the material is high quality, accurate and up-to-date."));
                                      
        showMenu();
    }

    public void showMenu()
    {
        panelMenu.setBackground(new Color(1,121,111));
    
        JButton buttonCI = new JButton ("View Course Info");
        panelMenu.add(buttonCI);
        buttonCI.setBounds(550,230,400,80);
        buttonCI.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                cardLayout.show(cardPanels,"infoMenu");
            }
        });
    
        JButton buttonTT = new JButton ("View Timetable");
        panelMenu.add(buttonTT);
        buttonTT.setBounds(550,340,400,80);
        
        JButton buttonTMP = new JButton ("Track My Progress");
        panelMenu.add(buttonTMP);
        buttonTMP.setBounds(550,450,400,80);
    
        showSubMenu();
    }

    public void showSubMenu()
    {
        panelInfo.setBackground(new Color(1,121,111));
    
        JButton buttonLT = new JButton ("Leadership Training");
        panelInfo.add(buttonLT);
        buttonLT.setBounds(550,120,400,80);
        buttonLT.addActionListener(this);
    
        JButton buttonTM = new JButton ("Time Management");
        panelInfo.add(buttonTM);
        buttonTM.setBounds(550,230,400,80);
    
        JButton buttonEC = new JButton ("Effective Communication");
        panelInfo.add(buttonEC);
        buttonEC.setBounds(550,340,400,80);
    
        JButton buttonPM = new JButton ("Project Management");
        panelInfo.add(buttonPM);
        buttonPM.setBounds(550,450,400,80);
    
        JButton buttonDT = new JButton ("Diversity Training");
        panelInfo.add(buttonDT);
        buttonDT.setBounds(550,560,400,80);
    
        JButton buttonBack = new JButton ("Back");
        panelInfo.add(buttonBack);
        buttonBack.setBounds(20,650,80,80);
        buttonBack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                cardLayout.show(cardPanels,"menu");
            }
        });
    }       

    public void showPanelSub()
    {
        panelSub.setBackground(new Color(1,121,111));
    
        JButton buttonBack = new JButton ("Back");
        panelSub.add(buttonBack);
        buttonBack.setBounds(20,650,80,80);
        buttonBack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                cardLayout.show(cardPanels,"infoMenu");
            }
        });
    
        allContentPanel.setBackground(Color.WHITE);
    
        BoxLayout boxlayout = new BoxLayout(allContentPanel, BoxLayout.Y_AXIS); 
        allContentPanel.setLayout(boxlayout);
    
        JTextArea outcomeTitle = new JTextArea(" Learning Outcome");
        JTextArea spacing1 = new JTextArea("  ");
        JTextArea spacing2 = new JTextArea("  ");
        JTextArea introTitle = new JTextArea(" Subject Introduction");
        JTextArea spacing3 = new JTextArea("  ");
    
        infoFormat(outcomeTitle,"title");
        infoFormat(spacing1,"spacing");
        infoFormat(info.get(0),"content");
        infoFormat(info.get(1),"content");
        infoFormat(info.get(2),"content");
        infoFormat(info.get(3),"content");
        infoFormat(info.get(4),"content");
        infoFormat(info.get(5),"content");
        infoFormat(info.get(6),"content");
        infoFormat(spacing2,"content");
        infoFormat(introTitle,"title");
        infoFormat(spacing3,"spacing");
        infoFormat(info.get(7),"content");
    
        scrollpane1 = new JScrollPane(allContentPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollpane1.setBounds(250,150,1000,500);
        panelSub.add(scrollpane1);
    }

    public void infoFormat(JTextArea text, String type)
    {
        if (type.equals("title"))
            text.setFont(titleFont);
        else if (type.equals("content"))
            text.setFont(contentFont);
        else if (type.equals("spacing"))
            text.setFont(spacingFont);
    
        text.setEditable(false);
        text.setLineWrap(true);
        text.setWrapStyleWord(true);
        allContentPanel.add(text);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().equals("Leadership Training"))
        {
            info = leadershipInfo;
        }
        else if (e.getActionCommand().equals("Time Management"))
        { //will continue when get the first successful
        }
        else if (e.getActionCommand().equals("Effective Communication"))
        { //will continue when get the first successful
        }
        else if (e.getActionCommand().equals("Project Management"))
        { //will continue when get the first successful
        }
        else if (e.getActionCommand().equals("Diversity Training"))
        { //will continue when get the first successful
        }
        showPanelSub();
        cardLayout.show(cardPanels,"subInfo");
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
lalala
  • 15
  • 7
  • I cannot reproduce your problem. The Back button always works for me. However, your comparison of strings using `==` may be the source of your problem; see https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java. – VGR Aug 02 '20 at 16:06
  • Sorry, what I meant is after I clicked back and get back to the subject menu, when I click "Leadership Training" again, the information does not show up. – lalala Aug 02 '20 at 16:21

1 Answers1

2
public class execute extends JFrame implements ActionListener

1 - Class names should start with an upper case character. All JDK class follow this standard. Learn by example.

2 - You should not extend JFrame. You extend a class when you want to add new functionality to that class. Add components to a frame or logic related to you application does not change the functionality of the frame.

private static CardLayout cardLayout = new CardLayout();

Don't use static variables. That is not what the static keyword is used for. The variables should be instance variables in your class.

public static void main(String[] args)
{
    new execute();
}

All Swing components should be created on the Event Dispatch Thread (EDT)

panelMenu = new JPanel(null);
...
buttonLT.setBounds(550,120,400,80);

Don't use null layout. Swing was designed to be used with layout managers.

public void actionPerformed(ActionEvent e)

How does the code in this method even compile? I see lots of opening "{" but no ending "}".

if (type == "title")

Don't use "==" for object comparison. Instead you use the equals(...) method.

This could be the problem since the if condition will not work the way you expect

I suggest you start by reading the Swing Tutorial for Swing basics to help with the above suggestions.

In particular the sections on:

  1. Concurrency in Swing - for information about the EDT
  2. How to Use CardLayout - for examples on how to better structure your code so you don't extend a JFrame and the proper usage of static variables.
  3. A Visual Guide to Layout Managers

Edit:

The first change I made was to add a removeAll() statement in the showSubPane() method:

panelSub.setBackground(new Color(1,121,111));
panelSub.removeAll(); // added

That did something, although it actually showed more information at the top.

Next I then added:

allContentPanel = new JPanel(); // added
allContentPanel.setBackground(Color.WHITE);

Now the content looks the same.

However, I think the overall approach needs to be changed.

You should not need to be continually adding/removing or creating new components to dynamically rebuild the panels.

A better approach would be to store the text in an HTML file and then just load a JEditorPane with the data from the appropriate file. This will allow for easier maintenance and updating of the text displayed.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 2
    I respect your work and contributions, but is this an answer though? Seems like general guidelines, rather than providing a solution to his issue – Vince Aug 02 '20 at 16:10
  • @Dioxin, I made my suggestion about what the potential problem could be (added highlighting to make it clearer). In any case I posted it as an answer (instead of a comment) since there are so many issues and the comments would not be readable. – camickr Aug 02 '20 at 16:15
  • @camickr Noted and thanks for telling the problems. I know most of them except for the layout and EDT but I will try to google and improve my codes. But for now, I need to know why the Leadership Training information won't show up after the first time. – lalala Aug 02 '20 at 16:31
  • 1
    *I know most of them* - then your code should already be using the suggestions. We should not have to spend time to remind you. *But for now,...* - I highlighted the probable problem. Make the suggested change and retest. If it still doesn't work then update the posted code with your change as an [mre]. That is the code should compile. The code should use the JButon, not your custom class since your custom class is irrelevant to the stated problem. – camickr Aug 02 '20 at 16:37
  • @camickr So sorry that I copied less library than it should be. I have made some changes and it should be able to compile now. Please have a look. – lalala Aug 02 '20 at 16:50
  • The key problem is adding components to `allContentPanel` and `panelSub` over and over again. By removing them at the top of `showPanelSub` via calls to `allContentPanel.removeAll()` and `panelSub.removeAll()`, it works. With that said, it would be best to take the advice from the remainder of the post and redesign things so you aren't constructing Swing components on the fly. That is a valid approach, but I wouldn't expect to see it in a starter Swing project. – Tad Harrison Aug 02 '20 at 17:27