Использование JPanel для отображения различной информации, но ее можно показать только в первый раз - PullRequest
0 голосов
/ 02 августа 2020

Я новичок в Java GUI и учусь создавать JPanel, а затем использовать ту же панель для переключения на ней другого содержимого. Когда я нажимаю кнопку в первый раз, информация появляется, и если я нажимаю кнопку «назад» и снова нажимаю кнопку «Обучение лидерству», ничего не появлялось. Я пытался использовать removeAll(), repaint() и revalidate() на allContentPanel(), но это не сработало.

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");
    }
}

1 Ответ

2 голосов
/ 02 августа 2020
public class execute extends JFrame implements ActionListener

1 - имена классов должны начинаться с символа верхнего регистра. Все классы JDK соответствуют этому стандарту. Учитесь на примере.

2 - Не следует расширять JFrame. Вы расширяете класс, когда хотите добавить в этот класс новые функции. Добавление компонентов во фрейм или c относящиеся к вашему приложению компоненты не изменяют функциональность фрейма.

private static CardLayout cardLayout = new CardLayout();

Не используйте переменные stati c. Это не то, для чего используется ключевое слово stati c. Переменные должны быть переменными экземпляра в вашем классе.

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

Все компоненты Swing должны быть созданы на Event Dispatch Thread (EDT)

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

Не используйте нулевой макет. Swing был разработан для использования с менеджерами по компоновке.

public void actionPerformed(ActionEvent e)

Как код в этом методе вообще компилируется? Я вижу много открывающих «{», но без окончания «}».

if (type == "title")

Не используйте «==» для сравнения объектов. Вместо этого вы используете метод equals(...).

Это может быть проблемой, поскольку условие if не будет работать так, как вы ожидаете

Я предлагаю вам начать с чтения Учебное пособие по Swing для основ Swing, чтобы помочь с приведенными выше предложениями.

В частности, разделы по:

  1. Concurrency in Swing - для получения информации о EDT
  2. How to Use CardLayout - примеры того, как лучше структурировать код, чтобы вы не расширяли JFrame, и правильное использование переменных stati c.
  3. A Visual Guide to Layout Managers

Изменить:

Первое изменение, которое я сделал, заключалось в добавлении оператора removeAll () в метод showSubPane ():

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

Это что-то сделало, хотя на самом деле показало больше информация вверху.

Затем я добавил:

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

Теперь содержимое выглядит так же.

Однако я думаю, что общий подход необходимо изменить.

Вам не нужно постоянно добавлять / удалять или создавать новый компонент s для динамического перестроения панелей.

Лучшим подходом было бы сохранить текст в файле HTML, а затем просто загрузить JEditorPane с данными из соответствующего файла. Это упростит обслуживание и обновление отображаемого текста.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...