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

huangapple go评论31阅读模式
英文:

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

问题

我是新手使用Java GUI,正在学习创建JPanel,然后使用同一个面板在其上切换不同的内容。当我第一次单击按钮时,信息显示出来,如果我单击"返回"按钮然后再次单击"领导力培训"按钮,什么都不会显示出来。我尝试在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. 理解情感智能及如何在职场中展示。"));
        leadershipInfo.add(new JTextArea(" 2. 培养自我意识,学习如何建立有意义的人际关系。"));
        leadershipInfo.add(new JTextArea(" 3. 理解如何建立和维护领导力存在感。"));
        leadershipInfo.add(new JTextArea(" 4. 深入研究领导力的要点,比如如何激励团队。"));
        leadershipInfo.add(new JTextArea(" 5. 学习管理的基本要点,比如如何有效沟通。"));
        leadershipInfo.add(new JTextArea(" 6. 理解如何将领导模型在个人、地方和全球范围内付诸实践。"));
        leadershipInfo.add(new JTextArea(" 7. 更深入地了解自己的个人身份以及如何塑造自己的领导和跟随身份。"));
        leadershipInfo.add(new JTextArea(" 优秀的领导者是对自己的工作充满激情和信心的人,他们在过程中激励着其他人。提高自我意识,增强自信,能够给人留下深刻印象。掌握团队工作、沟通以及如何在工作中激励团队的实际知识。无论您是新手还是经验丰富,这门课程都是一个有用且信息丰富的指南。我们的学习材料全天候提供,随时随地供全球学生使用,非常方便。这些密集的在线课程向所有人开放,只要您对该主题感兴趣!我们提供世界一流的学习材料,因此您可以放心,材料具有高质量、准确和最新的特点。"));

        showMenu();
    }

    public void showMenu()
    {
        panelMenu.setBackground(new Color(1, 121, 111));

        JButton buttonCI = new JButton("查看课程信息");
        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("查看时间表");
        panelMenu.add(buttonTT);
        buttonTT.setBounds(550, 340, 400, 80);

        JButton buttonTMP = new JButton("跟踪我的进展");
        panelMenu.add(buttonTMP);
        buttonTMP.setBounds(550, 450, 400, 80);

        showSubMenu();
    }

    public void showSubMenu()
    {
        panelInfo.setBackground(new Color(1, 121, 111));

        JButton buttonLT = new JButton("领导力培训");
        panelInfo.add(buttonLT);
        buttonLT.setBounds(550, 120, 400, 80);
        buttonLT.addActionListener(this);

        JButton buttonTM = new JButton("时间管理");
        panelInfo.add(buttonTM);
        buttonTM.setBounds(550, 230, 400, 80);

        JButton buttonEC = new JButton("有效沟通");
        panelInfo.add(buttonEC);
        buttonEC.setBounds(550, 340, 400, 80);

        JButton buttonPM = new JButton("项目管理");
        panelInfo.add(buttonPM);
        buttonPM.setBounds(550, 450, 400, 80);

        JButton buttonDT = new JButton("多元化培训");
        panelInfo.add(buttonDT);
        buttonDT.setBounds(550, 560, 400, 80);

        JButton buttonBack = new JButton("返回");
        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("返回");
        panelSub.add(buttonBack);
        buttonBack.setBounds(20, 650, 80, 80);
        buttonBack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                cardLayout.show

<details>
<summary>英文:</summary>

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 &quot;back&quot; and click the button &quot;Leadership Training&quot; again, nothing showed up. I have tried to use `removeAll()`, `repaint()` and `revalidate()` on `allContentPanel()` but it won&#39;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&lt;JTextArea&gt; info,leadershipInfo,timeInfo;  
	
		public Execute()
		{
			super(&quot;Training Management System&quot;);
			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,&quot;menu&quot;);
			cardPanels.add(panelInfo,&quot;infoMenu&quot;);
			cardPanels.add(panelSub,&quot;subInfo&quot;);
		
			add(cardPanels);
		
			leadershipInfo = new ArrayList &lt;JTextArea&gt; ();
			leadershipInfo.add(new JTextArea(&quot; 1. Understand emotional intelligence and how to demonstrate it in the workplace.&quot;));
			leadershipInfo.add(new JTextArea(&quot; 2. Become self-aware and learn how to build meaningful relationships.&quot;));
			leadershipInfo.add(new JTextArea(&quot; 3. Understand how to build and maintain leadership presence.&quot;));
			leadershipInfo.add(new JTextArea(&quot; 4. Study in depth the essentials of leadership, like how to motivate your team.&quot;));
			leadershipInfo.add(new JTextArea(&quot; 5. Go through management essentials, like how to communicate effectively.&quot;));
			leadershipInfo.add(new JTextArea(&quot; 6. Understand how leadership models are put into practice personally, locally, and globally.&quot;));
			leadershipInfo.add(new JTextArea(&quot; 7. Gain a greater understanding of their own personal identities and how their identities shape their leadership &quot; + &quot;\n     and followership.&quot;));
			leadershipInfo.add(new JTextArea(&quot; Great leaders are individuals who are passionate and confident about their work, and they inspire others in the &quot; + 
										  &quot;\n process. Become self-aware, confident and able to make a great first impression. Gain practical knowledge of &quot; + 
										  &quot;\n team work, communication and how to motivate your team at work. Whether you are new to  management  or &quot; + 
										  &quot;\n have plenty of experience, this course is a helpful and informative guide. Our learning material  is  available  to &quot; + 
										  &quot;\n students 24/7 anywhere in the world, so it is extremely convenient. These intensive online courses are open to &quot; + 
										  &quot;\n everyone, as long as you have an interest in the topic! We provide world-class learning, so you can be assured &quot; + 
										  &quot;\n that the material is high quality, accurate and up-to-date.&quot;));
										  
			showMenu();
		}
	
		public void showMenu()
		{
			panelMenu.setBackground(new Color(1,121,111));
		
			JButton buttonCI = new JButton (&quot;View Course Info&quot;);
			panelMenu.add(buttonCI);
			buttonCI.setBounds(550,230,400,80);
			buttonCI.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e)
				{
					cardLayout.show(cardPanels,&quot;infoMenu&quot;);
				}
			});
		
			JButton buttonTT = new JButton (&quot;View Timetable&quot;);
			panelMenu.add(buttonTT);
			buttonTT.setBounds(550,340,400,80);
			
			JButton buttonTMP = new JButton (&quot;Track My Progress&quot;);
			panelMenu.add(buttonTMP);
			buttonTMP.setBounds(550,450,400,80);
		
			showSubMenu();
		}

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

		public void showPanelSub()
		{
			panelSub.setBackground(new Color(1,121,111));
		
			JButton buttonBack = new JButton (&quot;Back&quot;);
			panelSub.add(buttonBack);
			buttonBack.setBounds(20,650,80,80);
			buttonBack.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e)
				{
					cardLayout.show(cardPanels,&quot;infoMenu&quot;);
				}
			});
		
			allContentPanel.setBackground(Color.WHITE);
		
			BoxLayout boxlayout = new BoxLayout(allContentPanel, BoxLayout.Y_AXIS); 
			allContentPanel.setLayout(boxlayout);
		
			JTextArea outcomeTitle = new JTextArea(&quot; Learning Outcome&quot;);
			JTextArea spacing1 = new JTextArea(&quot;  &quot;);
			JTextArea spacing2 = new JTextArea(&quot;  &quot;);
			JTextArea introTitle = new JTextArea(&quot; Subject Introduction&quot;);
			JTextArea spacing3 = new JTextArea(&quot;  &quot;);
		
			infoFormat(outcomeTitle,&quot;title&quot;);
			infoFormat(spacing1,&quot;spacing&quot;);
			infoFormat(info.get(0),&quot;content&quot;);
			infoFormat(info.get(1),&quot;content&quot;);
			infoFormat(info.get(2),&quot;content&quot;);
			infoFormat(info.get(3),&quot;content&quot;);
			infoFormat(info.get(4),&quot;content&quot;);
			infoFormat(info.get(5),&quot;content&quot;);
			infoFormat(info.get(6),&quot;content&quot;);
			infoFormat(spacing2,&quot;content&quot;);
			infoFormat(introTitle,&quot;title&quot;);
			infoFormat(spacing3,&quot;spacing&quot;);
			infoFormat(info.get(7),&quot;content&quot;);
		
			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(&quot;title&quot;))
				text.setFont(titleFont);
			else if (type.equals(&quot;content&quot;))
				text.setFont(contentFont);
			else if (type.equals(&quot;spacing&quot;))
				text.setFont(spacingFont);
		
			text.setEditable(false);
			text.setLineWrap(true);
			text.setWrapStyleWord(true);
			allContentPanel.add(text);
		}

		public void actionPerformed(ActionEvent e)
		{
			if (e.getActionCommand().equals(&quot;Leadership Training&quot;))
			{
				info = leadershipInfo;
			}
			else if (e.getActionCommand().equals(&quot;Time Management&quot;))
			{ //will continue when get the first successful
			}
			else if (e.getActionCommand().equals(&quot;Effective Communication&quot;))
			{ //will continue when get the first successful
			}
			else if (e.getActionCommand().equals(&quot;Project Management&quot;))
			{ //will continue when get the first successful
			}
			else if (e.getActionCommand().equals(&quot;Diversity Training&quot;))
			{ //will continue when get the first successful
			}
			showPanelSub();
			cardLayout.show(cardPanels,&quot;subInfo&quot;);
		}
	}

</details>


# 答案1
**得分**: 2

public class execute extends JFrame implements ActionListener

1 - 类名应以大写字母开头所有JDK类都遵循此标准通过示例来学习

2 - 你不应该扩展JFrame只有在你想要向该类添加新功能时才扩展类向框架添加组件或与应用程序相关的逻辑不会改变框架的功能

private static CardLayout cardLayout = new CardLayout();

不要使用静态变量这不是static关键字的用途这些变量应该是类的实例变量

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

所有Swing组件应该在事件分发线程EDT)”上创建

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

不要使用null布局Swing设计用于与布局管理器一起使用

public void actionPerformed(ActionEvent e)

这个方法中的代码如何编译我看到很多{”,但没有}”。

if (type == "title")

不要使用==进行对象比较而是使用`equals(...)`方法

**这可能是问题的原因因为if条件将不会按照您的期望工作**

我建议您首先阅读[Swing教程](https://docs.oracle.com/javase/tutorial/uiswing/TOC.html),以了解Swing基础知识,以帮助您应对上述建议。

特别是以下部分

1. `Swing中的并发性` - 有关EDT的信息
2. `如何使用CardLayout` - 有关如何更好地组织代码以避免扩展JFrame和正确使用静态变量的示例
3. `布局管理器的可视化指南`

编辑

我所做的第一个更改是在showSubPane()方法中添加了一个removeAll()语句

panelSub.setBackground(new Color(1,121,111));
panelSub.removeAll(); // 添加了

这确实有所作为尽管它实际上在顶部显示了更多信息

接下来我添加了

allContentPanel = new JPanel(); // 添加了
allContentPanel.setBackground(Color.WHITE);

现在内容看起来一样

然而我认为整体方法需要更改

你不应该需要不断添加/删除或创建新组件来动态重建面板

更好的方法是将文本存储在HTML文件中然后只需加载带有来自适当文件的数据的JEditorPane这将使文本显示更容易维护和更新

<details>
<summary>英文:</summary>

    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&#39;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&#39;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 &quot;{&quot; but no ending &quot;}&quot;.

    if (type == &quot;title&quot;)

Don&#39;t use &quot;==&quot; 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](https://docs.oracle.com/javase/tutorial/uiswing/TOC.html) 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&#39;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.



</details>



huangapple
  • 本文由 发表于 2020年8月2日 23:42:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63217956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定