2015-02-07 2 views
1

Я внедрил лист распространения с помощью jTable. Теперь мне нужно получить значение ячейки этого листа распространения из экземпляра другого класса.Получите значение переменной экземпляра класса, находясь в экземпляре другого класса

Я попытался расширить класс текущего объекта классу, который содержит jTable, но он дает мне еще один экземпляр класса, который содержит jTable.

Есть ли способ получить доступ к переменной в экземпляре другого класса без расширения класса текущего объекта для этого класса?

Спасибо заранее :)


package spreadsheet; 

import java.awt.Dimension; 
import java.awt.Toolkit; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.DefaultCellEditor; 
import javax.swing.JFrame; 
import javax.swing.JTable; 
import javax.swing.JTextField; 
import javax.swing.ListSelectionModel; 
import javax.swing.Timer; 
import javax.swing.event.*; 
import javax.swing.text.BadLocationException; 

public class SpreadSheetUI extends javax.swing.JFrame implements TableModelListener { 

public NewCell[][] cellArray=new NewCell[20][9]; 

public SpreadSheetUI() { 

    initComponents(); 

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] { 
     {1, null, null, null, null, null, null, null, null, null}, 
     {2, null, null, null, null, null, null, null, null, null}, 
     {3, null, null, null, null, null, null, null, null, null}, 
     {4, null, null, null, null, null, null, null, null, null}, 
     {5, null, null, null, null, null, null, null, null, null}, 
     {6, null, null, null, null, null, null, null, null, null}, 
     {7, null, null, null, null, null, null, null, null, null}, 
     {8, null, null, null, null, null, null, null, null, null}, 
     {9, null, null, null, null, null, null, null, null, null}, 
     {10, null, null, null, null, null, null, null, null, null}, 
     {11, null, null, null, null, null, null, null, null, null}, 
     {12, null, null, null, null, null, null, null, null, null}, 
     {13, null, null, null, null, null, null, null, null, null}, 
     {14, null, null, null, null, null, null, null, null, null}, 
     {15, null, null, null, null, null, null, null, null, null}, 
     {16, null, null, null, null, null, null, null, null, null}, 
     {17, null, null, null, null, null, null, null, null, null}, 
     {18, null, null, null, null, null, null, null, null, null}, 
     {19, null, null, null, null, null, null, null, null, null}, 
     {20, null, null, null, null, null, null, null, null, null} 
    }, 
    new String [] { 
     "", "A", "B", "C", "D", "E", "F", "G", "H", "I" 
    } 
    ) { 
     boolean[] canEdit = new boolean [] { 
      false, true, true, true, true, true, true, true, true, true 
     }; 

     @Override 
     public boolean isCellEditable(int rowIndex, int columnIndex) { 
      return canEdit [columnIndex]; 
     } 
    }); 

    jTable1.getModel().addTableModelListener(new TableModelListener() { 
     @Override 
     public void tableChanged(TableModelEvent e) { 
      updateCellAddressText(); 
      updateFormulaBarText(); 
     } 
    }); 
    jTable1.setCellSelectionEnabled(true); 
    jTable1.getModel().addTableModelListener(this); 
    jTable1.getColumnModel().getColumn(0).setPreferredWidth(20); 
    jTable1.getColumnModel().getColumn(0).setResizable(false); 

    //Create a column selection listener 
    final ListSelectionModel sel = jTable1.getColumnModel().getSelectionModel(); 
    sel.addListSelectionListener(new ListSelectionListener(){ 
     @Override 
     public void valueChanged(ListSelectionEvent e) {     
      //If a cell in column[0] is selected, deselect it and select the respecting row 
      if (sel.isSelectedIndex(0)) 
       sel.setSelectionInterval(9,1); 
      //System.out.println(sel.getMinSelectionIndex()); 

     } 
    }); 

    ((JTextField) ((DefaultCellEditor) jTable1.getDefaultEditor(Object.class)).getComponent()).getDocument().addDocumentListener(
      new DocumentListener() { 

       @Override 
       public void insertUpdate(DocumentEvent de) { 
        try { 
         jTextFieldFormula.setText(de.getDocument().getText(0, de.getDocument().getLength())); 
        } catch (BadLocationException ex) { 
         Logger.getLogger(SpreadSheetUI.class.getName()).log(Level.SEVERE, null, ex); 
        } 
       } 

       @Override 
       public void removeUpdate(DocumentEvent de) { 
        try { 
         jTextFieldFormula.setText(de.getDocument().getText(0, de.getDocument().getLength())); 
        } catch (BadLocationException ex) { 
         Logger.getLogger(SpreadSheetUI.class.getName()).log(Level.SEVERE, null, ex); 
        } 
       } 

       @Override 
       public void changedUpdate(DocumentEvent de) { 
        try { 
         jTextFieldFormula.setText(de.getDocument().getText(0, de.getDocument().getLength())); 
        } catch (BadLocationException ex) { 
         Logger.getLogger(SpreadSheetUI.class.getName()).log(Level.SEVERE, null, ex); 
        } 
       } 

      } 
    ); 

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
    this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);//location 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setVisible(true); 
} 

package spreadsheet; 

import java.awt.Frame; 
import java.io.Serializable; 
import java.lang.reflect.Field; 
import java.lang.reflect.Method; 
import java.util.*; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class NewCell implements Serializable { 

//** fields 
String userInput=null,dataType=null,calculatedValue=null; 
String strArr[]; 
StringTokenizer tokenizer; 
DataType data; 

//** constructor 
public NewCell(String newData) { 
    userInput=newData; 
    // two ways of tokenizing is used as the user may input, 
    // 1.) A formula which needs to be calculated and then stored in a cell 
    // 2.) A normal data which needs to be split into datatypes and stored 
    // user input is identified as a formula if the first character is "=" 
    if(userInput.startsWith("=")) { 
     String pattern = "(.*)(\\d+)"; 
     String row,column; 
     Pattern ptn = Pattern.compile(pattern);  // Create a Pattern object 
     Matcher matcher;       // Create Matcher object. 
     tokenize("=^*/+-(),",true); 

     ArrayList<String> outputList=new ArrayList<>();    
     Stack stackOperators=new Stack(); 
     String[] duplicateArr=new String[strArr.length-1]; 
     //insert every token except the starting '=' to 'duplicateArr'    
     for(int i=0;i<duplicateArr.length;i++){ 
      duplicateArr[i]=strArr[i+1]; 
      // In here I want to get the cell value of jTable1 
      // Example: Assume duplicateArr[i]="A1" 
      // then I need the value of the cell in 1st row 2nd column 
      // and then convert it to a string and give that value back 
      // to the duplicateArr[i] 
      //********************************************************* 
      // Or else if I can get values from cellArray[][] in 
      // jTable1 that's also fine.    
     } 
     for (String strArr1 : duplicateArr) { 
      if(strArr1.matches("-?\\d+(\\.\\d+)?")) 
      //checks whether the element is numerical 
      { 
       outputList.add(strArr1); 
      }else if(strArr1.equals("(")) { 
       stackOperators.push(strArr1); 
      }else if(strArr1.equals(")")) { 
       while(!(String.valueOf(stackOperators.peek()).equals("("))){ 
        outputList.add(String.valueOf(stackOperators.pop())); 
       } 
       stackOperators.pop(); 
      }else{ 
       while(!stackOperators.empty() && (operaorPrecedence(String.valueOf(stackOperators.peek()))>operaorPrecedence(strArr1))){ 
        outputList.add(String.valueOf(stackOperators.pop())); 
       } 
       stackOperators.push(strArr1); 
      } 
     } 
     while(!stackOperators.empty()){ 
      outputList.add(String.valueOf(stackOperators.pop())); 
     } 
     int currentIndex=0; 
     float a,b; 
     while(1!=outputList.size()){ 
      if(!outputList.get(currentIndex+2).matches("-?\\d+(\\.\\d+)?")){ 
       a=Float.parseFloat(outputList.remove(currentIndex)); 
       b=Float.parseFloat(outputList.remove(currentIndex)); 
       switch(outputList.get(currentIndex)){ 
        case "+": 
         outputList.set(currentIndex,String.valueOf(a+b)); 
         break; 
        case "-": 
         outputList.set(currentIndex,String.valueOf(a-b)); 
         break; 
        case "*": 
         outputList.set(currentIndex,String.valueOf(a*b)); 
         break; 
        case "/": 
         outputList.set(currentIndex,String.valueOf(a/b)); 
         break; 
        case "^": 
         outputList.set(currentIndex,String.valueOf(Math.pow(a,b))); 
         break; 
       } 
       //check whether currentIndex+2 is larger than the maximum currentIndex of outputList 
       if(outputList.size()-1<=currentIndex+2) 
        currentIndex--; 
      }else{ 
       currentIndex++; 
      } 
     } 
     tokenizer=null; //tokenizer is made null to escape the 'NotSerializableException' 
         //when calling for 'Save' or 'Open' methods 
     calculatedValue=outputList.get(0); 
     if(Float.valueOf(calculatedValue)==Math.ceil(Float.valueOf(calculatedValue))){ 
      calculatedValue=String.valueOf((int)Math.ceil(Float.valueOf(calculatedValue))); 
      dataType="Integer Formula"; 
     }else{ 
      dataType="Float Formula"; 
     } 

     //System.out.println(outputList.toString()); 
     /* 
     if(strArr[1].equals("sum")) {} 
     else if(strArr[1].equals("avg")) {} 
     else if(strArr[1].equals("concat")) {} 
     else { 
     }*/ 
    }else{ 
     String datePattern="\\d{4}/\\d{1,2}/\\d{1,2}"; 
     if (userInput.matches(datePattern)) { 
       //** Find DateDT inside the input 
       data=new DateDT(userInput); 
       dataType="Date"; 
     }else{ 
      try{ 
       //**Find IntegerDT inside the input 
       data=new IntegerDT(Integer.parseInt(userInput)); 
       dataType="Integer"; 
      }catch(NumberFormatException nfe1){ 
       try{ 
        //** Find FloatDT inside the input 
        data=new FloatDT(Float.valueOf(userInput)); 
        dataType="Float"; 
       }catch(NumberFormatException nfe2){ 
        //** Obviously userInput is StringDT 
        data=new StringDT(userInput); 
        dataType="String"; 
       } 
      } 
     } 
    } 
} 

//** getters & setters 
public String getUserInput() { 
    return userInput; 
} 

public void setCalculatedValue(String calculatedValue) { 
    this.calculatedValue = calculatedValue; 
} 

public String getCalculatedValue() { 
    return calculatedValue; 
} 

public void setUserInput(String userInput) { 
    this.userInput = userInput; 
} 

//** methods 
private void tokenize(String delimiter,boolean delimStatus) { 
    int j=0; 
    tokenizer=new StringTokenizer(userInput, delimiter,delimStatus); 
    strArr=new String[tokenizer.countTokens()]; 
    while(tokenizer.hasMoreTokens()){ 
     strArr[j]=tokenizer.nextToken(); 
     j++; 
    } 
} 

private int operaorPrecedence(String Operator){ 
    switch(Operator){ 
     case "+": 
      return 0; 
     case "-": 
      return 0; 
     case "*": 
      return 1; 
     case "/": 
      return 1; 
     case "^": 
      return 2; 
     default: 
      return -1; 
    } 
} 

}

+1

Просим предоставить код, который вы используете. Это может помочь прояснить, какова ваша проблема. –

+1

«Композиция» - это способ, если вы не хотите использовать «Наследование». – RE350

+2

Публичные переменные или геттер и сеттеры – JClassic

ответ

0

OK. Я нашел ответ. Нам просто нужно сделать cellArray[][] в SpreadSheetUI класс a static переменная как это.

public static NewCell[][] cellArray=new NewCell[20][9]; 

Затем из экземпляра класса NewCell; мы можем получить доступ к значениям cellArray[][] следующим образом.

SpreadSheetUI.cellArray[row][column].userInput=<Expression>; 

Или же, используя геттеры и сеттеры;

String data=SpreadSheetUI.cellArray[row][column].getUserInput(); 
2

Вы должны попробовать эту логику.

Class Jtable 
private Object cellx; 

public Object getCellx(){ 

return this.cellx; } 
public setCellx(Object cellx){ 
this.cellx=cellx;} 
} 

и:

Class AnotherClass 
{ 
private Jtable jtable; 
getter and setter 

public void function() { 
this.jtable.getCellx(); 
    } 
} 
Смежные вопросы