我如何将数据从一个 JPanel 传递到另一个 JPanel...?

发布于 2024-11-26 12:07:35 字数 168 浏览 2 评论 0原文

我有一个 JFrame,其中包含 3 个 JPanel。我想将一个面板的 JTextField 值传递给另一个面板。每个面板均使用 JTabbedPane 显示。当我访问其他文本字段的值时,我得到空值。我怎样才能访问?

I have a JFrame which contains 3 JPanels. I want to pass the JTextField value of one panel to other. Each panel is shown using JTabbedPane. I am getting null when i access the value of other text field. How can i access?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

等风来 2024-12-03 12:07:35

您没有显示任何代码,因此不可能知道为什么会得到“空”值。如果您希望所有三个 JPanel 都保存具有相同内容的 JTextField,则有两种可能的解决方案:

  • 将共享 JTextField 放在 JTabbedPane 保存的 JPanel 之外,而放在保存 JTabbedPane 的 JPanel 中,以便无论哪个选项卡该字段始终可见显示,或
  • 使用多个 JTextField 但让它们共享相同的文档或“模型”。

例如,

import java.awt.Dimension;
import javax.swing.*;
import javax.swing.text.PlainDocument;

public class SharedField extends JTabbedPane {
   private static final int TAB_COUNT = 5;
   private static final int MY_WIDTH = 600;
   private static final int MY_HEIGHT = 300;
   PlainDocument doc = new PlainDocument();

   public SharedField() {
      for (int i = 0; i < TAB_COUNT; i++) {
         JTextField tField = new JTextField(10);
         tField.setDocument(doc);
         JPanel panel = new JPanel();
         panel.add(tField);
         add("Panel " + i, panel);

         // to demonstrate some of the JTextFields acting like 
         // a label
         if (i % 2 == 1) { // if i is odd
            tField.setEditable(false);
            tField.setBorder(null);
         }
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(MY_WIDTH, MY_HEIGHT);
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("SharedField");
      frame.getContentPane().add(new SharedField());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

编辑 1
我看到您已将其交叉发布在 java-forums.org/ 您在其中显示了一些代码:

软件包演示工具;
类别:主机
这是第一个面板的 actionPerformed 代码
str 和 scrTxt 都是(公共静态)

   public void actionPerformed(ActionEvent e)
    {
        String act=e.getActionCommand();

        if(act.equals("ADD"))
        {
            str=scrnTxt.getText();
            System.out.println("Hi :"+str);
            Demotool.DemoTool.jtp.setSelectedIndex(1);   
        }
    }

使用亲爱的代码,我尝试访问数据,但我得到空字符串:

 System.out.println("Hello:"+Demotool.MainFrame.str);

问题:

  • 不要使用静态变量或方法,除非你有充分的理由这样做。在这里你不知道。
  • 您可能在将任何内容放入其中之前尝试访问 MainFrame.str 变量,使其为空,您正在第二个类中创建一个新的 MainFrame 对象,该对象不是显示,因此其 str 变量为空或 null — 很难说。

不管怎样,这个设计都不好。您最好向我们展示一个小型演示程序,该程序通过编译和运行的代码显示您的问题,sscce,因此我们可以使用和修改您的代码,并且能够更好地向您展示一个不错的解决方案。

一种不错的解决方案是向 JTextField 添加一个 DocumentListener ,以便将 JTextField 所保存的文本的更改“推送”到观察者中正在监听变化(你的其他类)。

例如,使用文档监听器:

import java.awt.Dimension;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

public class SharedField2 extends JTabbedPane {
   private static final int LABEL_PANEL_COUNT = 4;
   private static final int MY_WIDTH = 600;
   private static final int MY_HEIGHT = 300;

   public SharedField2() {
      TextFieldPanel tfPanel = new TextFieldPanel();
      LabelPanel[] labelPanels = new LabelPanel[LABEL_PANEL_COUNT];

      add("TextFieldPanel", tfPanel);
      for (int i = 0; i < labelPanels.length; i++) {
         labelPanels[i] = new LabelPanel();
         // add each label panel's listener to the text field
         tfPanel.addDocumentListenerToField(labelPanels[i].getDocumentListener());
         add("Label Panel " + i, labelPanels[i]);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(MY_WIDTH, MY_HEIGHT);
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("SharedField2");
      frame.getContentPane().add(new SharedField2());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

class TextFieldPanel extends JPanel {
   private JTextField tField = new JTextField(10);

   public TextFieldPanel() {
      add(tField);
   }

   public void addDocumentListenerToField(DocumentListener listener) {
      tField.getDocument().addDocumentListener(listener);
   }
}

class LabelPanel extends JPanel {
   private DocumentListener myListener;

   private JLabel label = new JLabel();

   public LabelPanel() {
      add(label);
      myListener = new DocumentListener() {

         @Override
         public void changedUpdate(DocumentEvent e) {
            updateLabel(e);
         }

         @Override
         public void insertUpdate(DocumentEvent e) {
            updateLabel(e);
         }

         @Override
         public void removeUpdate(DocumentEvent e) {
            updateLabel(e);
         }

         private void updateLabel(DocumentEvent e) {
            try {
               label.setText(e.getDocument().getText(0,
                        e.getDocument().getLength()));
            } catch (BadLocationException e1) {
               e1.printStackTrace();
            }
         }

      };
   }

   public DocumentListener getDocumentListener() {
      return myListener;
   }
}

You don't show any code, and so it's impossible to know why you're getting "null" values. Two possible solutions if you want all three JPanels to hold JTextFields with the same content:

  • Put the shared JTextField outside of the JPanels held by the JTabbedPane and instead in a JPanel that holds the JTabbedPane, so that the field is always visible no matter what tab is displayed, or
  • Use several JTextFields but have them share the same Document or "model".

e.g.,

import java.awt.Dimension;
import javax.swing.*;
import javax.swing.text.PlainDocument;

public class SharedField extends JTabbedPane {
   private static final int TAB_COUNT = 5;
   private static final int MY_WIDTH = 600;
   private static final int MY_HEIGHT = 300;
   PlainDocument doc = new PlainDocument();

   public SharedField() {
      for (int i = 0; i < TAB_COUNT; i++) {
         JTextField tField = new JTextField(10);
         tField.setDocument(doc);
         JPanel panel = new JPanel();
         panel.add(tField);
         add("Panel " + i, panel);

         // to demonstrate some of the JTextFields acting like 
         // a label
         if (i % 2 == 1) { // if i is odd
            tField.setEditable(false);
            tField.setBorder(null);
         }
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(MY_WIDTH, MY_HEIGHT);
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("SharedField");
      frame.getContentPane().add(new SharedField());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

Edit 1
I see that you've cross-posted this on java-forums.org/ where you show some of your code:

pacage Demotool;
Class:MainFrame
This is the actionPerformed code of first panel
both str and scrTxt is (public static)

   public void actionPerformed(ActionEvent e)
    {
        String act=e.getActionCommand();

        if(act.equals("ADD"))
        {
            str=scrnTxt.getText();
            System.out.println("Hi :"+str);
            Demotool.DemoTool.jtp.setSelectedIndex(1);   
        }
    }

using the belove code i tried to access the data but I am getting null String:

 System.out.println("Hello:"+Demotool.MainFrame.str);

Problems:

  • Don't use static variables or methods unless you have a good reason to do so. Here you don't.
  • You're may be trying to access the MainFrame.str variable before anything has been put into it, making it null, or you are creating a new MainFrame object in your second class, one that isn't displayed, and thus one whose str variable is empty or null -- hard to say.

Either way, this design is not good. You're better off showing us a small demo program that shows your problem with code that compiles and runs, an sscce, so we can play with and modify your code and better be able to show you a decent solution.

One such decent solution is to add a DocumentListener to the JTextField so that changes to the text held by the JTextField are "pushed" into the observers that are listening for changes (your other classes).

For example, using DocumentListeners:

import java.awt.Dimension;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

public class SharedField2 extends JTabbedPane {
   private static final int LABEL_PANEL_COUNT = 4;
   private static final int MY_WIDTH = 600;
   private static final int MY_HEIGHT = 300;

   public SharedField2() {
      TextFieldPanel tfPanel = new TextFieldPanel();
      LabelPanel[] labelPanels = new LabelPanel[LABEL_PANEL_COUNT];

      add("TextFieldPanel", tfPanel);
      for (int i = 0; i < labelPanels.length; i++) {
         labelPanels[i] = new LabelPanel();
         // add each label panel's listener to the text field
         tfPanel.addDocumentListenerToField(labelPanels[i].getDocumentListener());
         add("Label Panel " + i, labelPanels[i]);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(MY_WIDTH, MY_HEIGHT);
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("SharedField2");
      frame.getContentPane().add(new SharedField2());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

class TextFieldPanel extends JPanel {
   private JTextField tField = new JTextField(10);

   public TextFieldPanel() {
      add(tField);
   }

   public void addDocumentListenerToField(DocumentListener listener) {
      tField.getDocument().addDocumentListener(listener);
   }
}

class LabelPanel extends JPanel {
   private DocumentListener myListener;

   private JLabel label = new JLabel();

   public LabelPanel() {
      add(label);
      myListener = new DocumentListener() {

         @Override
         public void changedUpdate(DocumentEvent e) {
            updateLabel(e);
         }

         @Override
         public void insertUpdate(DocumentEvent e) {
            updateLabel(e);
         }

         @Override
         public void removeUpdate(DocumentEvent e) {
            updateLabel(e);
         }

         private void updateLabel(DocumentEvent e) {
            try {
               label.setText(e.getDocument().getText(0,
                        e.getDocument().getLength()));
            } catch (BadLocationException e1) {
               e1.printStackTrace();
            }
         }

      };
   }

   public DocumentListener getDocumentListener() {
      return myListener;
   }
}
帅的被狗咬 2024-12-03 12:07:35

一种简单的解决方案是将 JTextField 设为全局,以便所有面板都可以访问它。

确保您的所有面板都可以访问 JTextField,即 textField 是全局可访问的。

以下代码演示了这一点:

JTextField textField = new JTextField(25);
JLabel labelForPanel2 = new JLabel(),labelForPanel3 = new JLabel();
private void panelDemo() {
    JFrame frame = new JFrame();
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel panel3 = new JPanel();

    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("Tab 1", panel1);
    tabbedPane.addTab("Tab 2", panel2);
    tabbedPane.addTab("Tab 3", panel3);

    panel1.add(textField);
    panel2.add(labelForPanel2);
    panel3.add(labelForPanel3);

    textField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            labelForPanel2.setText(textField.getText());
            labelForPanel3.setText(textField.getText());
        }
    });

    frame.add(tabbedPane);
    frame.setVisible(true);
}

One simple solution will be making JTextField global so all panel can access it.

Make sure all your panel can access JTextField that is textField is globally accessible.

Following code demonstrate this:

JTextField textField = new JTextField(25);
JLabel labelForPanel2 = new JLabel(),labelForPanel3 = new JLabel();
private void panelDemo() {
    JFrame frame = new JFrame();
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel panel3 = new JPanel();

    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("Tab 1", panel1);
    tabbedPane.addTab("Tab 2", panel2);
    tabbedPane.addTab("Tab 3", panel3);

    panel1.add(textField);
    panel2.add(labelForPanel2);
    panel3.add(labelForPanel3);

    textField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            labelForPanel2.setText(textField.getText());
            labelForPanel3.setText(textField.getText());
        }
    });

    frame.add(tabbedPane);
    frame.setVisible(true);
}
挽袖吟 2024-12-03 12:07:35

我不知道你到底要实现什么,但也许尝试数据绑定?

查看 BetterBeansBinding 库。

I don't know what exactly are you going to achieve, but maybe try data binding?

Take a look at BetterBeansBinding library.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文