简体   繁体   English

使用 JPanel 显示不同的信息,但只能显示第一次

[英]Using a JPanel to display different info, but it can only be shown the 1st time

I am new to Java GUI, and learning to create a JPanel , then use the same panel to switch different content on it.我是 Java GUI 新手,正在学习创建JPanel ,然后使用相同的面板在其上切换不同的内容。 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.我曾尝试在allContentPanel() ) 上使用removeAll()repaint()revalidate() ,但它不起作用。

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");
    }
}
public class execute extends JFrame implements ActionListener

1 - Class names should start with an upper case character. 1 - Class 名称应以大写字符开头。 All JDK class follow this standard.所有 JDK class 都遵循这个标准。 Learn by example.以身作则。

2 - You should not extend JFrame. 2 - 您不应扩展 JFrame。 You extend a class when you want to add new functionality to that class.当您想向 class 添加新功能时,您可以扩展 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.不要使用 static 变量。 That is not what the static keyword is used for.这不是 static 关键字的用途。 The variables should be instance variables in your class.这些变量应该是 class 中的实例变量。

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

All Swing components should be created on the Event Dispatch Thread (EDT)所有 Swing 组件都应在Event Dispatch Thread (EDT)上创建

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

Don't use null layout.不要使用 null 布局。 Swing was designed to be used with layout managers. Swing 旨在与布局管理器一起使用。

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.不要使用“==”进行 object 比较。 Instead you use the equals(...) method.相反,您使用equals(...)方法。

This could be the problem since the if condition will not work the way you expect这可能是问题所在,因为 if 条件不会按您期望的方式工作

I suggest you start by reading the Swing Tutorial for Swing basics to help with the above suggestions.我建议您首先阅读 Swing 基础知识的Swing 教程,以帮助了解上述建议。

In particular the sections on:特别是以下部分:

  1. Concurrency in Swing - for information about the EDT Concurrency in Swing的并发 - 有关 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. How to Use CardLayout - 有关如何更好地构建代码以便不扩展 JFrame 以及正确使用 static 变量的示例。
  3. A Visual Guide to Layout Managers

Edit:编辑:

The first change I made was to add a removeAll() statement in the showSubPane() method:我所做的第一个更改是在 showSubPane() 方法中添加 removeAll() 语句:

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.更好的方法是将文本存储在 HTML 文件中,然后只需从相应文件中加载包含数据的 JEditorPane。 This will allow for easier maintenance and updating of the text displayed.这将使显示的文本更易于维护和更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 第一次设置JPanel / JFrame背景图片 - Setting JPanel/JFrame background image, my 1st time 我在片段中有2个RecyclerViews。 但只显示了第一个 - I have 2 RecyclerViews in a Fragment. But only the 1st one is shown Android 通知点击打开应用程序仅第一次有效 - Android notification click to open app only works 1st time 使用Java获取页面源仅读取第一行 - Get page source using Java is reading only 1st line 如何添加到 JFrame 3 JPanel:第一个 JPanel 占据框架的 90%,第二个在瘦顶上,第三个是可以关闭的抽屉面板 - How to add to a JFrame 3 JPanels: The 1st JPanel to take up 90% of the frame, the second to be on skinny top, 3rd to be drawer panel that can close KeyListener第一次没有响应吗? - KeyListener is unresponsive 1st time used? Blobstore上传文件,但只有1st 1 mb - Blobstore upload files but only the 1st 1 mb ModelAttribute仅将第一个值添加到列表中 - ModelAttribute adds only 1st value into List 扫描程序仅读取字符串的第一个标记 - Scanner only reading 1st token of a string 当软件在该系统中第一次运行时,如何使用Java显示对话框 - How to show a dialog box a software using java when the software run 1st time in that system
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM