通过变量在基于窗口的Java应用程序中访问对象

huangapple go评论84阅读模式
英文:

Accessing object through variable in JAVA for Window based application

问题

try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx")) {  
    Workbook wb = WorkbookFactory.create(inp);  
    Sheet sheet = wb.getSheetAt(0);  
    Row row = sheet.getRow(2);  
    Cell cell = row.getCell(2);
    if (cell != null)  
        System.out.println("Data: " + cell);  
    else  
        System.out.println("Cell is empty");  
} catch(Exception e) {  
    System.out.println(e);  
}

...

btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        lblNewLabel.setText(cell.toString());
    }
});

Rest of the GUI code remains unchanged.

英文:

So, I am developing a GUI based application that reads data from Excel using Apache POI and displays it using JAVA AWT/SWING based Window Application. So, to start with I have integrated Apache POI in GUI based JAVA project.

So, now I am trying to access a particular cell data from excel and print it in the GUI App.
I have sorted out how to get particular cell data from excel to Java and how to use Jlabel. To proceed it with I need to send the cell data to JLabel.

I have done the following to get Cell data: Clearly, we have cell object from Cell class. How do I send this cell data to JLabel?

I have the following code for JLabel.

try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx")) {  
            Workbook wb = WorkbookFactory.create(inp);  
            Sheet sheet = wb.getSheetAt(0);  
            Row row = sheet.getRow(2);  
            Cell cell = row.getCell(2);
            if (cell != null)  
                System.out.println("Data: "+cell);  
            else  
                System.out.println("Cell is empty");  
    }catch(Exception e) {  
        System.out.println(e);  
    } 

Clearly we have cell object from Cell class. How do I send this cell data to JLable?

I have the following code for JLable.

Here after we press the button the content of the Lable changes.


lblNewLabel = new JLabel("Hey there. Your GPA is");
		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
		lblNewLabel.setBounds(100, 46, 298, 55);
		frame.getContentPane().add(lblNewLabel);


JButton btnNewButton = new JButton("Show me!");
		btnNewButton.setForeground(Color.BLUE);
		btnNewButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 16));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//JOptionPane.showMessageDialog(null, "Hello World!");
				lblNewLabel.setText(cell);
			}
		});

lblNewLabel.setText(cell);

But it's showing error. I even declared a new string and passed it using cell object. But it didn't work either.

I am looking for a way to pass the output from Cell to JLabel.

Both are in the main function only.

Below is the entire code.

package com;

import java.io.FileInputStream;  
import java.io.InputStream;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.ss.usermodel.Sheet;  
import org.apache.poi.ss.usermodel.Workbook;  
import org.apache.poi.ss.usermodel.WorkbookFactory;  
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JLabel;

public class GUI {

	private JFrame frame;
	private JLabel lblNewLabel;
	private JTextField textField;
	private JTextField textField_1;
	private JLabel lblNewLabel_1;
	private JTextField textField_2;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx")) {  
            Workbook wb = WorkbookFactory.create(inp);  
            Sheet sheet = wb.getSheetAt(0);  
            Row row = sheet.getRow(2);  
            Cell cell = row.getCell(2);
            if (cell != null)  
                System.out.println("Data: "+cell);  
            else  
                System.out.println("Cell is empty");  
    }catch(Exception e) {  
        System.out.println(e);  
    }  
		
		
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GUI window = new GUI();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public GUI() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 605, 418);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		JButton btnNewButton = new JButton("Show me!");
		btnNewButton.setForeground(Color.BLUE);
		btnNewButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 16));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//JOptionPane.showMessageDialog(null, "Hello World!");
				lblNewLabel.setText(cell);
			}
		});
		btnNewButton.setBounds(147, 133, 130, 31);
		frame.getContentPane().add(btnNewButton);
		
		lblNewLabel = new JLabel("Hey there. Your GPA is");
		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
		lblNewLabel.setBounds(100, 46, 298, 55);
		frame.getContentPane().add(lblNewLabel);
		
		textField = new JTextField();
		textField.setBounds(63, 214, 96, 19);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		
		textField_1 = new JTextField();
		textField_1.setBounds(342, 214, 96, 19);
		frame.getContentPane().add(textField_1);
		textField_1.setColumns(10);
		
		lblNewLabel_1 = new JLabel("Answer-");
		lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 24));
		lblNewLabel_1.setBounds(139, 323, 122, 48);
		frame.getContentPane().add(lblNewLabel_1);
		
		textField_2 = new JTextField();
		textField_2.setBounds(301, 329, 174, 42);
		frame.getContentPane().add(textField_2);
		textField_2.setColumns(10);
		
		JButton btnNewButton_1 = new JButton("Multiply");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int a,b,ans;
				try {
					a=Integer.parseInt(textField.getText());
					b=Integer.parseInt(textField_1.getText());
					ans=a*b;
					textField_2.setText(Integer.toString(ans));
					
				}catch(Exception e1) {
					JOptionPane.showMessageDialog(null,"Enter valid number");
				}
			}
		});
		btnNewButton_1.setBounds(90, 264, 85, 21);
		frame.getContentPane().add(btnNewButton_1);
		
		JButton btnNewButton_2 = new JButton("Divide");
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int a,b,ans;
				try {
					a=Integer.parseInt(textField.getText());
					b=Integer.parseInt(textField_1.getText());
					ans=a/b;
					textField_2.setText(Integer.toString(ans));
					
				}catch(Exception e2) {
					JOptionPane.showMessageDialog(null,"Enter valid number");
				}
			}
		});
		
		btnNewButton_2.setBounds(330, 264, 85, 21);
		frame.getContentPane().add(btnNewButton_2);
	}
}

Don't mind all other GUI code. They are just some bunch of buttons, text fields.

答案1

得分: 1

首先,您需要在initialize方法的范围内获取Cell cell,或者Cell cell必须作为类成员,就像JLabel lblNewLabel一样。

另一种解决方案是创建一个公共方法,从工作簿中获取单元格内容,然后可以从initialize方法内部调用该方法。

然后,JLabelsetText方法需要一个String作为参数。因此,您需要将cell的内容转换为String

因此,最简单的解决方案是:

...
String cellContent = cell.toString();
...

但这不是首选的方法。相反,使用apache poiDataFormatter来将Cell中的内容转换为StringDataFormatter会以与Excel显示单元格内容相同的方式获取该String

...
DataFormatter formatter = new DataFormatter();
...
String cellContent = formatter.formatCellValue(cell);
...

如果存在公式单元格,并且您需要获取公式的结果而不是公式本身,则还需要使用FormulaEvaluator

...
DataFormatter formatter = new DataFormatter();
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
...
String cellContent = formatter.formatCellValue(cell, evaluator);
...

因此,要扩展您的代码,您可以有以下方法:

...
public String getCellContent() {
 String cellContent = "";
 try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx"); 
      Workbook wb = WorkbookFactory.create(inp)) {  
  DataFormatter formatter = new DataFormatter();
  FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  Sheet sheet = wb.getSheetAt(0);  
  Row row = sheet.getRow(2);
  Cell cell = null;
  if (row != null) cell = row.getCell(2);
  cellContent = formatter.formatCellValue(cell, evaluator);
 } catch (Exception e) {
  e.printStackTrace();
 }
 return cellContent;
}
...

然后在您的initialize方法中:

...
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null, "Hello World!");
                lblNewLabel.setText(getCellContent());
            }
...

但是当然,这将始终从工作表中获取相同的单元格内容。因此,对于实际使用,getCellContent必须具有参数,以指定要读取的具体单元格。然后,该方法不应该每次都打开工作簿以获取单元格内容。因此,Workbook wbDataFormatter formatterFormulaEvaluator evaluator应该是类成员,并且仅在initialize时创建一次。

英文:

First you need to get the Cell cell in the scope of the initialize method or the Cell cell would must be a class member as JLabel lblNewLabel also is.

Another solution would be having a public method to get the cell content from the workbook which then can be called from within the initialize method.

Then, the setText method of a JLabel needs a String as the parameter. So you need converting the content of the cell to String.

So simplest solution would be

...
String cellContent = cell.toString();
...

But that is not the preferred way to do it. Instead do using DataFormatter of apache poi to get the cell content out of the Cell as a String. DataFormatter will get that String the same as Excel shows the cell content.

...
DataFormatter formatter = new DataFormatter();
...
String cellContent = formatter.formatCellValue(cell);
...

If there can be formula cells and you need the formula results instead of the formulas, then you will need FormulaEvaluator additionally.

...
DataFormatter formatter = new DataFormatter();
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
...
String cellContent = formatter.formatCellValue(cell, evaluator);
...

So to extend your code you could have following method:

...
public String getCellContent() {
 String cellContent = "";
 try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx"); 
      Workbook wb = WorkbookFactory.create(inp)) {  
  DataFormatter formatter = new DataFormatter();
  FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  Sheet sheet = wb.getSheetAt(0);  
  Row row = sheet.getRow(2);
  Cell cell = null;
  if (row != null) cell = row.getCell(2);
  cellContent = formatter.formatCellValue(cell, evaluator);
 } catch (Exception e) {
  e.printStackTrace();
 }
 return cellContent;
}
...

And then in your initialize method:

...
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null, "Hello World!");
                lblNewLabel.setText(getCellContent());
            }
...

But of course this will always get the same cell content from the sheet. So for practical usage the getCellContent would must have parameters to tell what concrete cell shall be read. And then the method should not open the workbook every single time a cell content shall got. So Workbook wb, DataFormatter formatter and FormulaEvaluator evaluator should be class members and created only once while initialize.

答案2

得分: 0

你正在尝试访问cell,但它是在另一个范围内定义的。
你可以创建一个方法,该方法返回单元格字符串。

public String getCell() {
    try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx")) {
        Workbook wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);
        Row row = sheet.getRow(2);
        Cell cell = row.getCell(2);
        if (cell != null)
            return cell.toString();
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}

然后可以这样访问它:

JButton btnNewButton = new JButton("Show me!");
btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //JOptionPane.showMessageDialog(null, "Hello World!");
        lblNewLabel.setText(getCell());
    }
});
英文:

You are trying to access cell, but it is defined in another scope.
You could create method, which returns the cell-string.

public String getCell() {
        try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx")) {  
        Workbook wb = WorkbookFactory.create(inp);  
        Sheet sheet = wb.getSheetAt(0);  
        Row row = sheet.getRow(2);  
        Cell cell = row.getCell(2);
        if (cell != null)  
            return cell.toString(); 
}catch(Exception e) {  
    System.out.println(e);  
}  

return null;
}
and then access it like so:

JButton btnNewButton = new JButton("Show me!");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //JOptionPane.showMessageDialog(null, "Hello World!");
            lblNewLabel.setText(getCell());
        }
    });

huangapple
  • 本文由 发表于 2020年4月4日 21:51:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/61029110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定