Getting data from JTextField that is one of severa

2019-07-15 09:25发布

问题:

So I am reading a file and I get the amount of lines in that file. Based on that I generate my interface. Now I need to have the ability to edit valus trougth UI . Rows is the variable that has how lines the input document has . Of course the code below doesnt work . I want to write new values to the array from which i read .

for(int i=0;i<Rows;i++)
{
    //System.out.println("!"+Symbol[1]+"!");
    //if(Symbol[i]!=""&&Symbol[i]!=null)
    // {
    JTextField symbol = new JTextField(6);
    symbol.setText(Symbol[i]);
    symbol.setBounds(10,25*i+10 , 75, 20);
    symbol.setEditable(false);
    frame.add(symbol);
    JTextField buyf = new JTextField(4);
    buyf.setText(String.valueOf(buy[i]));
    buyf.setBounds(95, 25*i+10, 50, 20);
    buyf.setEditable(true);
    buyf.addActionListener(new java.awt.event.ActionListener() { 
         public void actionPerformed(ActionEvent ae) {  
              buy[i]=Integer.parseInt(buyf.getText());
         }
    });                      
    frame.add(buyf);
} 

回答1:

  1. don't use AbsoluteLayout e.g. symbol.setBounds(10,25*i+10 , 75, 20); use proper LayoutManager, maybe GridLayout is best for your ...

  2. use DocumentListener for listening of changes in JTextComponents

  3. use JFormattedTextField with Number formatter, rather than plain JTextField, then you can remove everything about parseWhatever

  4. you can to use plain JTextField but with DocumentFilter (remove non numberic chars)

  5. ActionListener could be correct Listener an alternative is DocumentListener in point second

  6. for better help sooner post an SSCCE, but I think that DocumentListener can solve that