当前位置: 首页 > 知识库问答 >
问题:

显示下一个面板时更新CardLayout中的JLables

秦锐
2023-03-14

我有一个CardLayout,由许多不同的JPanels组成,我可以随意显示。该GUI链接到后端,并且GUI的目的是允许用户操作存储在后端中的数据。

问题是,当用户更改后端中的一些数据时,我的JLabels没有反映该数据中的更改。我明白这是因为JLabels初始化了一次,当我更新它们初始化到的变量时,我必须再次调用setText,以便它们体验更改。

示例:我的JLabel是如何初始化的

CurrentBAName = new javax.swing.JLabel();
CurrentBAName.setText(GUI.currentBankAccount.getAccountName());

问题是,当我更改GUI的值时。活期银行账户。getAccountName(),我的JLabel上的文本不会更新。我到处都有这样的jlabel,每次用户进行任何更改时,都必须通过并手动调用所有这些jlabel,这将是一种痛苦。有没有什么方法可以让JLabel在变量值发生变化时自动更新自身?

也许我可以实施某种观察者模式?我将如何使用JLabels做到这一点?
或者我可以使用一个焦点获取事件,这样每次我切换到面板时,焦点获取事件就会触发,这样我就可以更新东西了。我不知道如何做到这一点,虽然,我不知道重点如何与CardLayout工作。也许只是一个每次我显示带有layout.show(...)的面板时都会调用的方法。我将如何实现这一点?
还有更好的方法吗?

更新:示例代码

桂。java是我的主要GUI类,它将由一个JPanel组成,我的所有页面都将被随意添加和显示。

import javax.swing.*;

public class GUI extends javax.swing.JFrame
{
    public static String item;
    private javax.swing.JPanel MainPanel;

    public GUI()
    {
        // creates a JPanel called MainPanel which will hold the cards
        // in my CardLayout
        initComponents();
    }

    private void initComponents()
    {

        MainPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        MainPanel.setBackground(new java.awt.Color(198, 118, 38));
        MainPanel.setMaximumSize(new java.awt.Dimension(1000, 1000));
        MainPanel.setName(""); // NOI18N
        MainPanel.setPreferredSize(new java.awt.Dimension(1024, 768));
        MainPanel.setLayout(new java.awt.CardLayout());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(MainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(MainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);

    }

    // Grab the panel that was created in initComponents() so that I can add
    // other panels to it
    public JPanel getMainPanel()
    {
        return MainPanel;
    }

    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                GUI mainGUI = new GUI();

                // The JLabel in DisplayPanel.java will initially say root
                item = "root";

                JPanel cardHolder = mainGUI.getMainPanel();
                //This panel contains a button which will update the name of
                //the currentUserAccount
                MainMenuPanel mainMenu = new MainMenuPanel(cardHolder);
                cardHolder.add(mainMenu, "MainMenu");

                //This panel holds a JLabel that I want to have updated automatically
                //when the user presses the button on MainMenuPanel
                DisplayPanel display = new DisplayPanel(cardHolder);
                cardHolder.add(display, "Display");

                mainGUI.pack();
                mainGUI.setVisible(true);
            }
        });
    }
}

显示面板。java将是一个带有JLabel的JPanel,我希望在其上进行更新

import java.awt.*;
import javax.swing.*;

public class DisplayPanel extends javax.swing.JPanel
{
    private JPanel MainPanel;

    public DisplayPanel(JPanel MainPanel)
    {

        this.MainPanel = MainPanel;
        initComponents(); // Creates my panel with the JLabels/buttons etc
    }

    @SuppressWarnings("unchecked")                 
    private void initComponents()
    {

        jLabel1 = new javax.swing.JLabel();
        GoToMainMenuButton = new javax.swing.JButton();

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText(GUI.item); // sets the JLabel to the GUI.item variable

        GoToMainMenuButton.setText("Go to MainMenuPanel");
        GoToMainMenuButton.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                GoToMainMenuButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(269, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(GoToMainMenuButton)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(266, 266, 266))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(168, 168, 168)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(83, 83, 83)
                .addComponent(GoToMainMenuButton)
                .addContainerGap(116, Short.MAX_VALUE))
        );
    }                       

    private void GoToMainMenuButtonMouseClicked(java.awt.event.MouseEvent evt)                                                
    {
        // go back to the MainPanel                                        
        CardLayout layout = (CardLayout) (MainPanel.getLayout());
        layout.show(MainPanel, "MainMenu");
    }                                               

    private javax.swing.JButton GoToMainMenuButton;
    private javax.swing.JLabel jLabel1;

}

Main MenuPanel.java将是一个带有按钮的JPanel,当按下按钮时,将更新显示面板中JLabel文本设置的变量

import java.awt.*;
import javax.swing.*;

public class MainMenuPanel extends javax.swing.JPanel
{

    private JPanel MainPanel;

    public MainMenuPanel(JPanel MainPanel)
    {

        this.MainPanel = MainPanel;
        initComponents(); // Creates my panel with the JLabels/buttons etc
    }

    @SuppressWarnings("unchecked")                        
    private void initComponents()
    {

        GoToDisplayPanelButton = new javax.swing.JButton();

        GoToDisplayPanelButton.setText("Press Me");
        GoToDisplayPanelButton.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                GoToDisplayPanelButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(252, 252, 252)
                .addComponent(GoToDisplayPanelButton)
                .addContainerGap(260, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(198, Short.MAX_VALUE)
                .addComponent(GoToDisplayPanelButton)
                .addGap(175, 175, 175))
        );
    }                      

    private void GoToDisplayPanelButtonMouseClicked(java.awt.event.MouseEvent evt)                                                    
    {                                                        
        // Changes the value of item. I want this change to be reflected on my
        // JLabel in DisplayPanel.java, but it is not because I do not explicitly
        // call setText on the JLabel here. I am wondering if there is a way to 
        // have my JLabel automatically update when the variable in its setText
        // is changed, without having to directly call setText. Or some other 
        // way to update it without calling setText every time I change something.
        GUI.item = "new value";

        // Switches to my DisplayPanel which should show the updated name in its JLabel
        CardLayout layout = (CardLayout)(MainPanel.getLayout());
        layout.show(MainPanel, "Display");
    }                                                   

    private javax.swing.JButton GoToDisplayPanelButton;                   
}

共有1个答案

何长恨
2023-03-14

您需要使用通知系统,让模型(“后端”)在数据更改时通知视图(图形用户界面)。然后视图可以请求更新的信息,并使用它来更新JLabel显示。这方面的细节将取决于您的代码的细节,但我经常给我的模型(或模型周围的包装器)一个SwingProperty tyChangeSupport字段以及addProperty tyChangeListener(...)和类似的删除监听器方法,然后在模型的在更改属性(绑定属性)的方法中,触发SwingProperty tyChangeSupport的通知方法。有关实现的更多细节,您应该考虑显示代码的一些细节,最好是一个最小的示例程序。

举个例子

编辑

请注意,如果您只需要通知何时调用show,则始终可以扩展CardLayout并覆盖其show(…) 方法。但是如果你这么做了,别忘了调用super。秀(…) 方法。

编辑
注意对/]指示的代码所做的更改

import java.awt.CardLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class GUI extends javax.swing.JFrame {
   public static final String ITEM = "item";
   public String item; // !! this should not be static!
   private javax.swing.JPanel MainPanel;

   public GUI() {
      // creates a JPanel called MainPanel which will hold the cards
      // in my CardLayout
      initComponents();
   }

   // !!
   public void setItem(String item) {
      String oldValue = this.item;
      String newValue = item;
      this.item = item;
      firePropertyChange(ITEM, oldValue, newValue);
   }

   //!!
   public String getItem() {
      return item;
   }

   private void initComponents() {

      MainPanel = new javax.swing.JPanel();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

      MainPanel.setBackground(new java.awt.Color(198, 118, 38));
      MainPanel.setMaximumSize(new java.awt.Dimension(1000, 1000));
      MainPanel.setName(""); // NOI18N
      MainPanel.setPreferredSize(new java.awt.Dimension(1024, 768));
      MainPanel.setLayout(new java.awt.CardLayout());

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
            getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(layout.createParallelGroup(
            javax.swing.GroupLayout.Alignment.LEADING).addGroup(
            javax.swing.GroupLayout.Alignment.TRAILING,
            layout.createSequentialGroup()
                  .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE)
                  .addComponent(MainPanel,
                        javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addContainerGap()));
      layout.setVerticalGroup(layout.createParallelGroup(
            javax.swing.GroupLayout.Alignment.LEADING).addGroup(
            javax.swing.GroupLayout.Alignment.TRAILING,
            layout.createSequentialGroup()
                  .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE)
                  .addComponent(MainPanel,
                        javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addContainerGap()));

      pack();
      setLocationRelativeTo(null);

   }

   // Grab the panel that was created in initComponents() so that I can add
   // other panels to it
   public JPanel getMainPanel() {
      return MainPanel;
   }

   public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         @Override
         public void run() {
            final GUI mainGUI = new GUI();

            // The JLabel in DisplayPanel.java will initially say root
            // !! item = "root";
            mainGUI.setItem("root"); // !!

            JPanel cardHolder = mainGUI.getMainPanel();
            // This panel contains a button which will update the name of
            // the currentUserAccount
            final MainMenuPanel mainMenu = new MainMenuPanel(cardHolder,
                  mainGUI); // !!
            cardHolder.add(mainMenu, "MainMenu");

            // This panel holds a JLabel that I want to have updated
            // automatically
            // when the user presses the button on MainMenuPanel
            final DisplayPanel display = new DisplayPanel(cardHolder, mainGUI); // !!
            cardHolder.add(display, "Display");

            mainGUI.pack();
            mainGUI.setVisible(true);

            // !!
            mainGUI.addPropertyChangeListener(ITEM,
                  new PropertyChangeListener() {

                     @Override
                     public void propertyChange(PropertyChangeEvent pcEvt) {
                        String itemText = mainGUI.getItem();
                        display.setJLabel1Text(itemText);
                     }
                  });
         }
      });
   }
}

@SuppressWarnings("serial")
class DisplayPanel extends javax.swing.JPanel {
   private JPanel mainPanel;
   private GUI mainGui; // !!

   public DisplayPanel(JPanel mainPanel, GUI mainGui) { // !!

      this.mainPanel = mainPanel;
      this.mainGui = mainGui;// !!
      initComponents(); // Creates my panel with the JLabels/buttons etc
   }

   // !! added
   public void setJLabel1Text(String text) {
      jLabel1.setText(text);
   }

   private void initComponents() {

      jLabel1 = new javax.swing.JLabel();
      GoToMainMenuButton = new javax.swing.JButton();

      jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
      // !! jLabel1.setText(GUI.item); // sets the JLabel to the GUI.item
      // variable
      jLabel1.setText(mainGui.getItem()); // !!

      GoToMainMenuButton.setText("Go to MainMenuPanel");
      GoToMainMenuButton.addMouseListener(new java.awt.event.MouseAdapter() {
         public void mouseClicked(java.awt.event.MouseEvent evt) {
            GoToMainMenuButtonMouseClicked(evt);
         }
      });

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
      this.setLayout(layout);
      layout.setHorizontalGroup(layout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                  javax.swing.GroupLayout.Alignment.TRAILING,
                  layout.createSequentialGroup()
                        .addContainerGap(269, Short.MAX_VALUE)
                        .addGroup(
                              layout.createParallelGroup(
                                    javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(GoToMainMenuButton)
                                    .addComponent(
                                          jLabel1,
                                          javax.swing.GroupLayout.PREFERRED_SIZE,
                                          145,
                                          javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(266, 266, 266)));
      layout.setVerticalGroup(layout.createParallelGroup(
            javax.swing.GroupLayout.Alignment.LEADING).addGroup(
            layout.createSequentialGroup()
                  .addGap(168, 168, 168)
                  .addComponent(jLabel1,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 63,
                        javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addGap(83, 83, 83).addComponent(GoToMainMenuButton)
                  .addContainerGap(116, Short.MAX_VALUE)));
   }

   private void GoToMainMenuButtonMouseClicked(java.awt.event.MouseEvent evt) {
      // go back to the MainPanel
      CardLayout layout = (CardLayout) (mainPanel.getLayout());
      layout.show(mainPanel, "MainMenu");
   }

   private javax.swing.JButton GoToMainMenuButton;
   private javax.swing.JLabel jLabel1;

}

@SuppressWarnings("serial")
class MainMenuPanel extends javax.swing.JPanel {

   private JPanel MainPanel;
   private GUI mainGui; // !!

   public MainMenuPanel(JPanel MainPanel, GUI mainGui) { // !!

      this.MainPanel = MainPanel;
      this.mainGui = mainGui; // !!
      initComponents(); // Creates my panel with the JLabels/buttons etc
   }

   private void initComponents() {

      GoToDisplayPanelButton = new javax.swing.JButton();

      GoToDisplayPanelButton.setText("Press Me");
      GoToDisplayPanelButton
            .addMouseListener(new java.awt.event.MouseAdapter() {
               public void mouseClicked(java.awt.event.MouseEvent evt) {
                  GoToDisplayPanelButtonMouseClicked(evt);
               }
            });

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
      this.setLayout(layout);
      layout.setHorizontalGroup(layout.createParallelGroup(
            javax.swing.GroupLayout.Alignment.LEADING).addGroup(
            layout.createSequentialGroup().addGap(252, 252, 252)
                  .addComponent(GoToDisplayPanelButton)
                  .addContainerGap(260, Short.MAX_VALUE)));
      layout.setVerticalGroup(layout.createParallelGroup(
            javax.swing.GroupLayout.Alignment.LEADING).addGroup(
            javax.swing.GroupLayout.Alignment.TRAILING,
            layout.createSequentialGroup()
                  .addContainerGap(198, Short.MAX_VALUE)
                  .addComponent(GoToDisplayPanelButton).addGap(175, 175, 175)));
   }

   private void GoToDisplayPanelButtonMouseClicked(java.awt.event.MouseEvent evt) {
      // Changes the value of item. I want this change to be reflected on my
      // JLabel in DisplayPanel.java, but it is not because I do not explicitly
      // call setText on the JLabel here. I am wondering if there is a way to
      // have my JLabel automatically update when the variable in its setText
      // is changed, without having to directly call setText. Or some other
      // way to update it without calling setText every time I change something.
      // !! GUI.item = "new value";
      mainGui.setItem("new value"); // !!

      // Switches to my DisplayPanel which should show the updated name in its
      // JLabel
      CardLayout layout = (CardLayout) (MainPanel.getLayout());
      layout.show(MainPanel, "Display");
   }

   private javax.swing.JButton GoToDisplayPanelButton;
}

 类似资料:
  • 问题内容: 我试图用来显示两个,一个主菜单和一个控件屏幕。当我将两张卡片添加到卡中时,它只会显示两张闪烁的图像。这是我的代码: MazeGamePanel: 公共类MazeGamePanel扩展了JPanel实现Runnable { } MazeControlsPanel: 包装屏幕; 问题答案: 这是一个问题: 不要在Swing程序中使用java.util.Timer,因为您会遇到线程问题。而是

  • 在我的程序中,我有一个基于向导的布局。由CardLayout实现。因此,有一组类扩展了JPanel。我想在每个面板上都有按钮来导航到其他面板。例如,当程序显示第一面板时,我想有一个按钮来显示第二面板。 我试图在main cardlayout panel holder中创建一个方法,以便任何其他类都可以通过该方法更改显示面板,但它不起作用,并且出现了stackoverflow错误。 这是我的课程 基

  • 问题内容: 您好,我正在创建一个ASP.NET/C#应用程序,我有一个更新面板,该面板需要花费一些时间进行更新。在计算期间,是否可以显示“正在加载…请稍候”消息? 目前,我正在使用AJAX面板动画淡入/淡出,以使面板在计算时消失,然后在完成时重新出现。但这不是很实际。 如果可能,我需要显示一条消息。 感谢您的任何帮助。 这是我的面板的代码: 和Ajax Panel动画扩展器 问题答案: 您可以在以

  • 我创建了一个类,它有一个名为cards的面板,其布局是CardLAyout。我添加了卡片项目。在这个类中,我想通过调用layout来创建一个单独的方法,该方法将切换到下一张卡片。 } 正如你所看到的,我在卡片上添加了其他类的面板。我想做的是创建getNextCard()方法,该方法将当前活动的面板作为其参数。当我调用此功能时,它应该将当前活动的面板切换到我的CardLayout列表中的下一个面板。

  • 几天来,我一直在努力更新卡式布局中的JText field和Jbox数据。我创建了小演示来解释我的问题...当我点击“开始”按钮时,它应该显示另一个面板,它正在工作,但是当我回到主页时,我希望我的JText field和jbox从“世界”更新为“你好”,但这不起作用。任何帮助和建议将不胜感激。很抱歉代码缩进,我不知道为什么复制粘贴不能正常工作)。

  • 问题内容: 我在JSF页面中有这3个字段 我也有一个具有以下属性的后备豆: 我希望在将某些值插入字段val1和val2中而不刷新页面时,outputText元素自动更改其值。结果变量应以这种方式计算(它正在计算百分比):(val1 * val2)/ 100 您能帮我解决我的一些疑问吗?: 我知道为此,我需要javascript或AJAX之类的东西。您认为最好的方法是什么? 我很想知道我如何使用AJ