在另一个 class 实例中获取 class 实例变量的值
Get a value of a variable of a class instance while being at another class instance
我已经使用 jTable 实现了传播 sheet。现在我需要从另一个 class 的实例中获取该传播 sheet 的单元格值。
我试图将当前对象的 class 扩展到包含 jTable 的 class,但它给了我包含 jTable 的 class 的另一个实例。
有没有办法在不将当前对象的 class 扩展到那个 class 的情况下访问另一个 class 实例中的变量?
提前谢谢你:)
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;
}
}
}
你得试试这个逻辑。
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();
}
}
好的。我找到了答案。
我们只需要将 SpreadSheetUI
class 中的 cellArray[][]
设为 static
变量即可。
public static NewCell[][] cellArray=new NewCell[20][9];
然后从NewCell
的实例class;我们可以像这样访问 cellArray[][]
的值。
SpreadSheetUI.cellArray[row][column].userInput=<Expression>;
否则,使用 getter 和 setter;
String data=SpreadSheetUI.cellArray[row][column].getUserInput();
我已经使用 jTable 实现了传播 sheet。现在我需要从另一个 class 的实例中获取该传播 sheet 的单元格值。
我试图将当前对象的 class 扩展到包含 jTable 的 class,但它给了我包含 jTable 的 class 的另一个实例。
有没有办法在不将当前对象的 class 扩展到那个 class 的情况下访问另一个 class 实例中的变量?
提前谢谢你:)
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;
}
}
}
你得试试这个逻辑。
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();
}
}
好的。我找到了答案。
我们只需要将 SpreadSheetUI
class 中的 cellArray[][]
设为 static
变量即可。
public static NewCell[][] cellArray=new NewCell[20][9];
然后从NewCell
的实例class;我们可以像这样访问 cellArray[][]
的值。
SpreadSheetUI.cellArray[row][column].userInput=<Expression>;
否则,使用 getter 和 setter;
String data=SpreadSheetUI.cellArray[row][column].getUserInput();