java - 获取用户在其他类中输入的文本

标签 java swing

好吧,所以我创建了一个类来制作自定义文本字段。 该类扩展了 JPanel,因此我可以设置边框的颜色。

看起来像这样:

public class textfield {

    public static JTextField textF = new JTextField();


    public static class TextField extends JPanel{

        public  TextField(int x, int y, int width, int height, String bgColor, String brColor, String fgColor){

            this.setLayout(null);
            this.setBounds(x, y, width, height);
            this.setBackground(new Color(Integer.parseInt(bgColor.substring(0, 3)), Integer.parseInt(bgColor.substring(3, 6)), Integer.parseInt(bgColor.substring(6, 9))));
            this.setBorder(BorderFactory.createLineBorder(new Color(Integer.parseInt(brColor.substring(0, 3)), Integer.parseInt(brColor.substring(3, 6)), Integer.parseInt(brColor.substring(6, 9)))));


            textF.setBorder(javax.swing.BorderFactory.createEmptyBorder());
            textF.setOpaque(false);
            textF.setBounds(width / 20, 0, width, height);
            textF.setForeground(new Color(Integer.parseInt(fgColor.substring(0, 3)), Integer.parseInt(fgColor.substring(3, 6)), Integer.parseInt(fgColor.substring(6, 9))));
            add(textF);

        }

    }

} 

这是一个例子:

TextField userName = new textfield.TextField(1073, 177, 190, 31, "000003006", "120090040", "255255255");
add(userName);

我现在的问题是,如何获取用户在文本字段中输入的文本?如果我只使用 1 个文本字段,我知道该怎么做,但我使用多个文本字段。

提前致谢!

最佳答案

你的结构对我来说非常奇怪,我怀疑你错过了一些基本的面向对象的概念,并且可能只是对此进行了修改,直到你“让它发挥作用”。

对于初学者来说,我认为这些东西不应该是静态的。这意味着永远只能有其中之一。此外,这可能应该只是一个简单的类,而不是这个嵌入的类。类上的字段应该是私有(private),并且仅在需要时通过 setter/getter 方法公开访问。

考虑这样的事情:

public class TextField extends JPanel{

    private JTextField textF = new JTextField();

    // the constructor you already have goes here
    // replace "textF" references with "this.textF" as needed

}

现在您有一个 TextField 类,它一个 JPanel 并且(作为内部成员)一个JTextField。它们都不是静态,因此您可以根据需要创建任意数量的它们,并且每个都完全封装。

然后,要访问该 JTextField 对象中的内容,您可以在 TextField 对象上公开更多方法:

public class TextField extends JPanel{

    private JTextField textF = new JTextField();

    // the constructor you already have goes here
    // replace "textF" references with "this.textF" as needed

    public String getText() {
        return textF.getText();
    }

}

我们公开的 getText() 方法实际上只是对 JTextField 上已有的 getText() 方法的传递。我们可以通过创建更多方法来公开任意数量的操作。如果有很多这样的方法,直接为textF变量公开一个getter可能是实用的,尽管这在技术上违反了德米特定律。

关于java - 获取用户在其他类中输入的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40770117/

相关文章:

swing - JNLP FileSaveService 打开文件打开对话框

java - HtmlUnit 通过它的值从表单获取提交按钮?

java - 从另一个类运行 servlet 类

java - jOOQ - 按原样渲染而不是 EXISTS

java - 调整 JPanel 的高度

java - 每当将新数据点添加到 jfreechart 中的现有数据集时,xy 折线图如何自动更新/重绘

java - 从 ANT 任务执行 Bower 更新

java - 如何自动关闭自定义对话框

java - JFrame 的无响应 KeyListener

java - 图像未从 jar 加载