2016-11-23 46 views
0

好的,所以我創建了一個課程來製作自定義文本框。 該類擴展了一個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個文本框,但我使用多個。

在此先感謝!

回答

1

你的結構對我來說很奇怪,我懷疑你錯過了一些基本的面向對象的概念,可能只是對它進行修改,直到你「完成了某種工作」。

對於初學者,我不認爲這些東西應該是static。這意味着只能有其中之一。另外,這應該只是一個簡單的類而不是這個嵌入類。並且類上的字段應該是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。它們都不是static,因此您可以根據需要創建儘可能多的,並且每個都完全封裝。

然後訪問該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()方法,我們揭露僅僅是一個直通到getText()方法上已有JTextField。我們可以通過創建更多方法來公開儘可能多的我們想要的操作。如果有這種方法的很多,可能直接暴露一個吸氣劑的變量是可行的,儘管這在技術上會違反Demeter法則。

+0

感謝您的幫助!它現在工作正常! –

相關問題