How to copy column data in excel by Apache poi? - apache-poi

Does anybody know how to copy a existing column data into a new sheet in a excel file or a new workbook by Apache poi? The data type is double and date.

I attached the link below. They also provide mutiple different ways of doing it.
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.util.CellRangeAddress;
/**
*
* #author jk
* getted from http://jxls.cvs.sourceforge.net/jxls/jxls/src/java/org/jxls/util/Util.java?revision=1.8&view=markup
* by Leonid Vysochyn
* and modified (adding styles copying)
* modified by Philipp Löpmeier (replacing deprecated classes and methods, using generic types)
*/
public class Util {
public static void copySheets(HSSFSheet newSheet, HSSFSheet sheet){
copySheets(newSheet, sheet, true);
}
public static void copySheets(HSSFSheet newSheet, HSSFSheet sheet, boolean copyStyle){
int maxColumnNum = 0;
Map<Integer, HSSFCellStyle> styleMap = (copyStyle) ? new HashMap<Integer, HSSFCellStyle>() : null;
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
HSSFRow srcRow = sheet.getRow(i);
HSSFRow destRow = newSheet.createRow(i);
if (srcRow != null) {
Util.copyRow(sheet, newSheet, srcRow, destRow, styleMap);
if (srcRow.getLastCellNum() > maxColumnNum) {
maxColumnNum = srcRow.getLastCellNum();
}
}
}
for (int i = 0; i <= maxColumnNum; i++) {
newSheet.setColumnWidth(i, sheet.getColumnWidth(i));
}
}
public static void copyRow(HSSFSheet srcSheet, HSSFSheet destSheet, HSSFRow srcRow, HSSFRow destRow, Map<Integer, HSSFCellStyle> styleMap) {
Set<CellRangeAddress> mergedRegions = new TreeSet<CellRangeAddress>();
destRow.setHeight(srcRow.getHeight());
for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {
HSSFCell oldCell = srcRow.getCell(j);
HSSFCell newCell = destRow.getCell(j);
if (oldCell != null) {
if (newCell == null) {
newCell = destRow.createCell(j);
}
copyCell(oldCell, newCell, styleMap);
CellRangeAddress mergedRegion = getMergedRegion(srcSheet, srcRow.getRowNum(), (short)oldCell.getColumnIndex());
if (mergedRegion != null) {
CellRangeAddress newMergedRegion = new CellRangeAddress(mergedRegion.getFirstRow(), mergedRegion.getFirstColumn(), mergedRegion.getLastRow(), mergedRegion.getLastColumn());
if (isNewMergedRegion(newMergedRegion, mergedRegions)) {
mergedRegions.add(newMergedRegion);
destSheet.addMergedRegion(newMergedRegion);
}
}
}
}
}
public static void copyCell(HSSFCell oldCell, HSSFCell newCell, Map<Integer, HSSFCellStyle> styleMap) {
if(styleMap != null) {
if(oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()){
newCell.setCellStyle(oldCell.getCellStyle());
} else{
int stHashCode = oldCell.getCellStyle().hashCode();
HSSFCellStyle newCellStyle = styleMap.get(stHashCode);
if(newCellStyle == null){
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
newCell.setCellStyle(newCellStyle);
}
}
switch(oldCell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
newCell.setCellType(HSSFCell.CELL_TYPE_BLANK);
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
default:
break;
}
}
public static CellRangeAddress getMergedRegion(HSSFSheet sheet, int rowNum, short cellNum) {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress merged = sheet.getMergedRegion(i);
if (merged.isInRange(rowNum, cellNum)) {
return merged;
}
}
return null;
}
private static boolean isNewMergedRegion(CellRangeAddress newMergedRegion, Collection<CellRangeAddress> mergedRegions) {
return !mergedRegions.contains(newMergedRegion);
}
}
http://www.coderanch.com/t/420958/open-source/Copying-sheet-excel-file-another

Related

Apache POI : Copy data to Particular sheet at particular cell with Merged Columns in Source Sheet

Problem
How to add some part of data from source excel sheet to the destination excel sheet using Apache POI(XSSF Format)?Excel sheet contains merged columns.
Requirement:
Requirement is not only to copy the row but also to put the data into desired Excel cell(desired column) of the destination sheet.
Note
-Copying row to desired row location in destination excel sheet is achievable. Problem is to first merge the cell as per source sheet in destination sheet and then put data into desired merged excel cell.
- Merged Columns could vary in a row.
Here is the source code, half referred and half written.
public static void copyNodeFrmtSrcToDest(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRowStart,XSSFRow srcRowEnd
,XSSFRow destRowStart, int destCellStart, Map<Integer, XSSFCellStyle> styleMap){
/*Check if there is only one row to be pasted*/
int noOfRows = srcRowEnd.getRowNum() - srcRowStart.getRowNum();
/*Check if there is only one row to be pasted*/
if(noOfRows == 0)
{
/*Copy a single row*/
copyRow(srcSheet,destSheet,srcRowStart,destRowStart,destCellStart,styleMap);
return;
}
for (int i = 0;i <= noOfRows ;i++)//For every row
{
/*Get rows from source sheet and increment it*/
XSSFRow srcIntermediateRow = srcSheet.getRow(srcRowStart.getRowNum() + i);
if(destRowStart == null)
{
try {
throw new RowNotFoundError("Row has not been found in the sheet.Kindly create a row.");
} catch (RowNotFoundError e) {
e.printStackTrace();
System.out.println(e.toString());
}
}
if(i!=0)//Assuming destRowStart has been created by user of the API
{
/*Create a new row*/
destRowStart = destSheet.createRow(destRowStart.getRowNum()+1);
}
copyRow(srcSheet,destSheet,srcIntermediateRow,destRowStart,destCellStart,styleMap);
}
}
public static void copyRow(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRow, XSSFRow destRow, int destCellStart,
Map<Integer, XSSFCellStyle> styleMap) {
int count = 1;
Set<CellRangeAddress> mergedRegions = new HashSet<CellRangeAddress>();
CellRangeAddress previousMergedRegion =null;
destRow.setHeight(srcRow.getHeight());
for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {
int mergedDiff;
XSSFCell oldCell = srcRow.getCell(j);
XSSFCell newCell;
if(j == srcRow.getFirstCellNum()){
newCell = destRow.getCell(destCellStart);}
else
{
newCell = destRow.getCell(destCellStart + count);
}
if (oldCell != null) {
if (newCell == null) {
if(j == srcRow.getFirstCellNum()){
newCell = destRow.createCell(destCellStart);//Keeping the new cell as the first one.
copyCell(oldCell, newCell, styleMap);
}
else{
newCell = destRow.createCell(destCellStart + count);
count = count + 1;
copyCell(oldCell, newCell, styleMap);}
}
CellRangeAddress mergedRegion = getMergedRegion(srcSheet, srcRow.getRowNum(),oldCell.getColumnIndex());
if(previousMergedRegion != null && mergedRegion != null)
{
mergedDiff = mergedRegion.getLastColumn() - mergedRegion.getFirstColumn();
if(!previousMergedRegion.equals(mergedRegion))
{
destCellStart = destCellStart + mergedDiff + 1;
count = 1;
}
}
if (mergedRegion != null) {
previousMergedRegion = mergedRegion.copy();
mergedDiff = mergedRegion.getLastColumn() - mergedRegion.getFirstColumn();
CellRangeAddress newMergedRegion = new CellRangeAddress(destRow.getRowNum(),destRow.getRowNum()
,destCellStart,destCellStart + mergedDiff);
if (isNewMergedRegion(newMergedRegion, mergedRegions))
{
mergedRegions.add(newMergedRegion);
destSheet.addMergedRegion(newMergedRegion);
}
}
}
}
}
public static void copyCell(XSSFCell oldCell, XSSFCell newCell, Map<Integer, XSSFCellStyle> styleMap) {
if(styleMap != null) {
if(oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()){
newCell.setCellStyle(oldCell.getCellStyle());
} else{
int stHashCode = oldCell.getCellStyle().hashCode();
XSSFCellStyle newCellStyle = styleMap.get(stHashCode);
if(newCellStyle == null){
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
newCell.setCellStyle(newCellStyle);
}
}
switch(oldCell.getCellTypeEnum()) {
case STRING:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case BLANK:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
default:
break;
}
}
public static CellRangeAddress getMergedRegion(XSSFSheet sheet, int rowNum, int cellNum) {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress merged = sheet.getMergedRegion(i);
if (merged.isInRange(rowNum, cellNum)) {
return merged;
}
}
return null;
}
private static boolean isNewMergedRegion(CellRangeAddress newMergedRegion, Set<CellRangeAddress> mergedRegions)
{
if(mergedRegions.isEmpty())
{
return true;
}
return !mergedRegions.contains(newMergedRegion);
}
}
It is working fine for some testcases but not for all.

NullPointerException in working with JButtons

public class Node extends JButton {
private Node rightConnection ;
private Node downConnection ;
private Node rightNode ,downNode, leftNode ,upNode;
private ArrayList<String> buttonImages = new ArrayList<String>();
public static void connectNodes(ArrayList<Node> nodes) {
for (int i = 0; i < nodes.size(); i++) {
nodes.get(i).setRightNode((nodes.get(i).getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + 1) : null);
nodes.get(i).setDownNode((nodes.get(i).getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + Integer.parseInt(SetMap.getMapSize())) : null);
nodes.get(i).setLeftNode((nodes.get(i).getLocation().x / 150 > 0) ? nodes.get(i - 1) : null);
nodes.get(i).setUpNode((nodes.get(i).getLocation().y / 150 > 0) ? nodes.get(i - Integer.parseInt(SetMap.getMapSize())) : null);
}
}
public class SetContent {
private JPanel contentPanel;
private int imgNum;
public SetContent() {
contentPanel = new JPanel(null);
contentPanel.setLocation(1166, 0);
contentPanel.setSize(200, 768);
makeOptionNodes();
}
private void makeOptionNodes() {
MouseListener mouseListener = new DragMouseAdapter();
for (int row = 0; row < 13; row++) {
for (int col = 0; col < 2; col++) {
Node button = new Node();
button.setSize(100, 50);
button.setLocation(col * 100, row * 50);
ImageIcon img = new ImageIcon("src/com/company/" + this.imgNum++ + ".png");
button.setIcon(new ImageIcon(String.valueOf(img)));
// to remote the spacing between the image and button's borders
//button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
//button.setBackground( ... );
button.setTransferHandler(new TransferHandler("icon"));
button.addMouseListener(mouseListener);
contentPanel.add(button);
}
}
}
}
public class DragMouseAdapter extends MouseAdapter{
String name= new String();
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
name = handler.getDragImage().toString();// here is another nullpointerException
for(int i = 0 ; i< Integer.parseInt(SetMap.getMapSize()) ; i++) {
if (c.getName().equals(String.valueOf(i))) {
((Node) c).getButtonImages().add(name);
}
}
}
}
public class SetMap {
private static String mapSize;
private JPanel nodesPanel;
private ArrayList<Node> nodes;
public SetMap() {
nodes = new ArrayList<Node>();
for (Node node : nodes) {
node = new Node();
}
nodesPanel = new JPanel(null);
nodesPanel.setLocation(0, 0);
nodesPanel.setSize(1166, 768);
this.mapSize = JOptionPane.showInputDialog(null, "enter map size:");
makeMapNodes();
Node.connectNodes(this.nodes);
makeConnections();
}
private void makeMapNodes() {
for (int row = 0; row < Integer.parseInt(this.mapSize); row++) {
for (int col = 0; col < Integer.parseInt(this.mapSize); col++) {
final Node button = new Node();
button.setRightNode(null);
button.setDownNode(null);
button.setLeftNode(null);
button.setUpNode(null);
button.setRightConnection(null);
button.setDownConnection(null);
button.setTransferHandler(new TransferHandler("icon"));
button.setSize(100, 100);
button.setLocation(col * 150, row * 150);
this.nodes.add(button);
nodesPanel.add(button);
Node.setNodeName(this.nodes, this.nodes.indexOf(button));
button.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
int index = nodes.indexOf(button);
nodes.remove(button);
Node.setNodeName(nodes, index);
button.invalidate();
button.setVisible(false);
if (button.getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) {
button.getRightConnection().invalidate();
button.getRightConnection().setVisible(false);
}
if (button.getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) {
button.getDownConnection().invalidate();
button.getDownConnection().setVisible(false);
}
if (button.getLocation().x / 150 > 0) {
button.getLeftNode().getRightConnection().invalidate();
button.getLeftNode().getRightConnection().setVisible(false);
}
if (button.getLocation().y / 150 > 0) {
button.getUpNode().getDownConnection().invalidate();
button.getUpNode().getDownConnection().setVisible(false);
}
}
});
}
}
}
private void makeConnections() {
for (Node button : this.nodes){
final Node rightConnection = new Node();
final Node downConnection = new Node();
rightConnection.setSize(50, 35);
downConnection.setSize(35, 50);
rightConnection.setLocation(button.getLocation().x + 100, button.getLocation().y + 35);
downConnection.setLocation(button.getLocation().x + 35, button.getLocation().y + 100);
button.setRightConnection(rightConnection);
button.setDownConnection(downConnection);
ImageIcon imgH = new ImageIcon("src/com/company/horizontal.png");
rightConnection.setIcon(new ImageIcon(String.valueOf(imgH)));
ImageIcon imgV = new ImageIcon("src/com/company/vertical.png");
downConnection.setContentAreaFilled(false);
downConnection.setIcon(new ImageIcon(String.valueOf(imgV)));
if(button.getLocation().x / 150 != Integer.parseInt(this.mapSize)-1) {
nodesPanel.add(rightConnection);
}
if(button.getLocation().y / 150 != Integer.parseInt(this.mapSize)-1) {
nodesPanel.add(downConnection);
}
rightConnection.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
rightConnection.invalidate();
rightConnection.setVisible(false);
}
});
downConnection.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
downConnection.invalidate();
downConnection.setVisible(false);
}
});
}
}
}
public class File {
public static void writeInFile(ArrayList<Node> nodes) {
try {
FileWriter fileWriter = new FileWriter("G:\\file.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("[" + SetMap.getMapSize() + "]" + "[" + SetMap.getMapSize() + "]");
bufferedWriter.newLine();
Iterator itr = nodes.iterator();
while (itr.hasNext()) {
Node node = (Node) itr.next();
if (node != null) {
bufferedWriter.write(node.getText());
bufferedWriter.newLine();
bufferedWriter.write("R" + ((node.getRightConnection() != null) ? node.getRightNode().getText() : null) + " D" + ((node.getDownConnection() != null) ? node.getDownNode().getText() : null) + " L" + ((node.getLeftNode().getRightConnection() != null) ? node.getLeftNode().getText() : null) + " U" + ((node.getUpNode().getDownConnection() != null) ? node.getUpNode().getText() : null));//here is the NullPOinterException
bufferedWriter.newLine();
bufferedWriter.write("image");
bufferedWriter.newLine();
Iterator it = node.getButtonImages().iterator();
while (it.hasNext()){
String images = (String) it.next();
bufferedWriter.write(" " + images);
}
}
}
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
public class Main {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(null);
final SetMap map = new SetMap();
SetContent options = new SetContent();
mainFrame.add(map.getNodesPanel());
mainFrame.add(options.getContentPanel());
JButton saveButton = new JButton("save");
saveButton.setSize(100, 25);
saveButton.setLocation(1050, 10);
saveButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
File.writeInFile(map.getNodes());
}
});
map.getNodesPanel().add(saveButton);
mainFrame.setVisible(true);
JOptionPane.showMessageDialog(null, "choose nodes and connections you want to remove");
}
}
I'm trying to write the changes that are made on some nodes I added in mapPanel but in the File class the line (which is commented), I get NullPointerException and also for another line in class DragMouseAdapter I get this exception again.
I've omitted some unimportant part of code. I know it's a lot to check code but I would be thankful for any simple help in this case cause I'm a real noob in programming.

Selenium -Extracting data from excel and writing to web page -Issues in program

I am trying to extract data from excel and write it to a web page . As I click on a drop down"I am " provided in the link in the code below the remaining contents of the page changes .I have made certain cells as blank.I wrote the code but getting some exceptions .Please help
import java.io.*;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Copyprogram {
public static WebDriver driver=new FirefoxDriver();
public static void main(String[] args)
{
driver.get("http://www.deal4loans.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/a[1]")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try {
FileInputStream fis = new FileInputStream("C:\\Users\\user\\Documents\\Copy of Booklet1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("testdata");
// Loop through all rows in the sheet
// Start at row 1 as row 0 is our header row
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
for(int i = 1;i<=rowCount;i++)
{
Row row1 = sheet.getRow(i);
try {
Thread.sleep(2000);
} catch (Exception e)
{
// TODO: handle exception
}
runTest(row1.getCell(1).toString(),row1.getCell(2).toString(),row1.getCell(3).toString(),row1.getCell(4).toString(),row1.getCell(5).toString(),row1.getCell(6).toString(),row1.getCell(7).toString(),row1.getCell(8).toString(),row1.getCell(9).toString(),row1.getCell(10).toString(),row1.getCell(11).toString(),row1.getCell(12).toString(),row1.getCell(13).toString() );
System.out.println(row1.getCell(1).toString());
System.out.println(row1.getCell(2).toString());
System.out.println(row1.getCell(3).toString());
System.out.println(row1.getCell(4).toString());
System.out.println(row1.getCell(5).toString());
System.out.println(row1.getCell(6).toString());
System.out.println(row1.getCell(7).toString());
System.out.println(row1.getCell(8).toString());
System.out.println(row1.getCell(9).toString());
System.out.println(row1.getCell(10).toString());
if (i<rowCount)
{
driver.navigate().back();
}
System.out.println(i);
}
fis.close();
} catch (IOException e) {
System.out.println("Test data file not found");
}
driver.close();
}
public static void runTest(String name,String mailid,String query,String city,String mob,String pdt,String PL,String HL,String CL,String LA,String BL,String CC,String ass)
{
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/input")).sendKeys(name);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/input")).sendKeys(mailid);
Select listbox1 = new Select(driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[3]/td[2]/select")));
listbox1.selectByValue(query);
String selectedValue =listbox1.getFirstSelectedOption().getText();
Select listbox2 = new Select(driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[4]/td[2]/select")));
listbox2.selectByValue(city);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[6]/td[2]/input")).sendKeys(mob);
if (selectedValue=="1")
{
Select listbox3 = new Select(driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[7]/td/div[2]/table/tbody/tr/td[2]/select")));
listbox3.selectByValue(pdt);
}
else
{
if (PL == null && PL.length() == 0)
{
driver.findElement(By.cssSelector("input[value=PL]")).click();
System.out.println(PL);
}
if(HL == null && HL.length() == 0)
{
driver.findElement(By.cssSelector("input[value=HL]")).click();
}
if(CL == null && CL.length() == 0)
{
driver.findElement(By.cssSelector("input[value=CL]")).click();
}
if(LA == null && LA.length() == 0)
{
driver.findElement(By.cssSelector("input[value=LA]")).click();
}
if(BL == null && BL.length() == 0)
{
driver.findElement(By.cssSelector("input[value=BL]")).click();
}
if(CC== null && CC.length() == 0)
{
driver.findElement(By.cssSelector("input[value=CC]")).click();
}
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[7]/td/div[3]/table/tbody/tr[2]/td[2]/input")).sendKeys(ass);
}
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[9]/td/input")).click();
}
}

How to hide the controls of HTMLEditor?

is it possible to hide the controls of a HTMLEditor above the actual text? (Alignment, Copy&Paste icons, stylings etc.)
Thanks for any help
public static void hideHTMLEditorToolbars(final HTMLEditor editor)
{
editor.setVisible(false);
Platform.runLater(new Runnable()
{
#Override
public void run()
{
Node[] nodes = editor.lookupAll(".tool-bar").toArray(new Node[0]);
for(Node node : nodes)
{
node.setVisible(false);
node.setManaged(false);
}
editor.setVisible(true);
}
});
}
If you use unsupported methods, you can customize the toolbars pretty easily.
As Uluk states in his answer, the methods below aren't officially supported.
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.image.ImageView;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
public class HTMLEditorSample extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final HTMLEditor htmlEditor = new HTMLEditor();
stage.setScene(new Scene(htmlEditor));
stage.show();
hideImageNodesMatching(htmlEditor, Pattern.compile(".*(Cut|Copy|Paste).*"), 0);
Node seperator = htmlEditor.lookup(".separator");
seperator.setVisible(false); seperator.setManaged(false);
}
public void hideImageNodesMatching(Node node, Pattern imageNamePattern, int depth) {
if (node instanceof ImageView) {
ImageView imageView = (ImageView) node;
String url = imageView.getImage().impl_getUrl();
if (url != null && imageNamePattern.matcher(url).matches()) {
Node button = imageView.getParent().getParent();
button.setVisible(false); button.setManaged(false);
}
}
if (node instanceof Parent)
for (Node child : ((Parent) node).getChildrenUnmodifiable())
hideImageNodesMatching(child, imageNamePattern, depth + 1);
}
}
It seems you cannot according to this official tutorial.
The formatting toolbars are provided in the implementation of the
component. You cannot toggle their visibility. However, you still can
customize the appearance of the editor by applying CSS style ...
I've made some functions to modify the HTML-Editor (to get a minimalistic version of it), maybe someone else might want to use it too.
The Code:
import javafx.application.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import com.sun.javafx.scene.web.skin.PopupButton;
public class HTMLEditorModifyer extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final HTMLEditor htmlEditor = new HTMLEditor();
stage.setScene(new Scene(htmlEditor));
stage.setWidth(300);
stage.setHeight(200);
stage.show();
addCustomToolBarTo(htmlEditor);
printChildren(htmlEditor, 20);
moveFromTo(htmlEditor, "PopupButton", 0, "ToolBar", 2);
moveFromTo(htmlEditor, "PopupButton", 1, "ToolBar", 2);
moveFromTo(htmlEditor, "Separator", 4, "ToolBar", 2);
moveFromTo(htmlEditor, "ComboBox", 2, "ToolBar", 2);
moveFromTo(htmlEditor, "Separator", 5, "ToolBar", 2);
moveFromTo(htmlEditor, "ToggleButton", 6, "ToolBar", 2);
moveFromTo(htmlEditor, "ToggleButton", 7, "ToolBar", 2);
moveFromTo(htmlEditor, "ToggleButton", 8, "ToolBar", 2);
removeFrom(htmlEditor, "ToolBar", 1);
removeFrom(htmlEditor, "ToolBar", 0);
//printChildren(htmlEditor, 20);
}
public void moveFromTo(HTMLEditor he, String t, int c, String t2, int c2)
{
Node nCb = new Button(); //just has to be sth.
//Copy From:
int i = 0;
switch(t)
{
case "PopupButton":
for (Node candidate: (he.lookupAll("PopupButton")))
{
if (candidate instanceof PopupButton)
{
PopupButton cb = (PopupButton) candidate;
if (i == c)
{
nCb = cb;
break;
}
}
i++;
}
break;
case "Separator":
for (Node candidate: (he.lookupAll("Separator")))
{
if (candidate instanceof Separator)
{
Separator cb = (Separator) candidate;
if (i == c)
{
nCb = cb;
break;
}
}
i++;
}
break;
case "ComboBox":
for (Node candidate: (he.lookupAll("ComboBox")))
{
if (candidate instanceof ComboBox)
{
ComboBox cb = (ComboBox) candidate;
if (i == c)
{
nCb = cb;
break;
}
}
i++;
}
break;
case "ToggleButton":
for (Node candidate: (he.lookupAll("ToggleButton")))
{
if (candidate instanceof ToggleButton)
{
ToggleButton cb = (ToggleButton) candidate;
if (i == c)
{
nCb = cb;
break;
}
}
i++;
}
break;
}
//Copy To:
i = 0;
switch(t2)
{
case "ToolBar":
for (Node candidate: (he.lookupAll("ToolBar")))
{
if (candidate instanceof ToolBar)
{
ToolBar cb2 = (ToolBar) candidate;
if (i == c2)
{
cb2.getItems().add(nCb);
break;
}
}
i++;
}
break;
}
}
public void removeFrom(HTMLEditor he, String t, int c)
{
int i = 0;
switch(t)
{
case "ToolBar":
for (Node candidate: (he.lookupAll("ToolBar")))
{
if (candidate instanceof ToolBar)
{
ToolBar cb = (ToolBar) candidate;
if (i == c)
{
Node nCb = cb;
((Pane) nCb.getParent()).getChildren().remove(nCb);
break;
}
}
i++;
}
break;
case "PopupButton":
for (Node candidate: (he.lookupAll("PopupButton")))
{
if (i == c)
{
Node nCb = candidate;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
i++;
}
break;
case "ToggleButton":
for (Node candidate: (he.lookupAll("ToggleButton")))
{
if (candidate instanceof ToggleButton)
{
ToggleButton cb = (ToggleButton) candidate;
if (i == c)
{
Node nCb = cb;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
}
i++;
}
break;
case "Separator":
for (Node candidate: (he.lookupAll("Separator")))
{
if (candidate instanceof Separator)
{
Separator cb = (Separator) candidate;
if (i == c)
{
Node nCb = cb;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
}
i++;
}
break;
case "Button":
for (Node candidate: (he.lookupAll("Button")))
{
if (candidate instanceof Button)
{
Button cb = (Button) candidate;
if (i == c)
{
Node nCb = cb;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
}
i++;
}
break;
case "ComboBox":
for (Node candidate: (he.lookupAll("ComboBox")))
{
if (candidate instanceof ComboBox)
{
ComboBox cb = (ComboBox) candidate;
if (i == c)
{
Node nCb = cb;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
}
i++;
}
break;
}
}
public void printChildren(HTMLEditor he, int MAXDEPTH)
{
System.out.println("Print Children ==========>>>>");
String[] hieraArray = new String[MAXDEPTH];
int maxDepth = 0;
int lastDepth = 0;
Node parent;
/* List all elements of the HTMLeditor */
for (Node element: (he.lookupAll("*")))
{
parent = element.getParent();
if (maxDepth == 0)
{
hieraArray[0] = element.getClass().getSimpleName().toString();
System.out.print(hieraArray[0]);
System.out.println("");
maxDepth = 1;
}
else
{
int i = 0, i2 = 0;
boolean found = false;
for(i=maxDepth; i>=0; i--)
{
if (hieraArray[i] == null || parent.getClass().getSimpleName() == null) continue;
if (hieraArray[i].equals(parent.getClass().getSimpleName()))
{
for (i2 = 0; i2 <= i; i2++)
{
System.out.print("|");
}
if ((Math.abs(lastDepth-i2)) > 2) System.out.print("->" + element.getClass().getSimpleName() + " {p: " + parent.getClass().getSimpleName() + "}");
else System.out.print("->" + element.getClass().getSimpleName());
//if (element.getClass().getSimpleName().equals("PopupButton")) System.out.print(" ??: " + element + " ::: " + element.getClass());
lastDepth = i2;
hieraArray[(i+1)] = element.getClass().getSimpleName();
if (maxDepth < (i+1)) maxDepth = (i+1);
found = true;
System.out.println("");
break;
}
}
if (found == false)
{
hieraArray[(i+1)] = parent.getClass().getSimpleName();
if (maxDepth < (i+1)) maxDepth = (i+1);
}
if ((maxDepth+1) >= MAXDEPTH)
{
System.out.println("MAXDEPTH reached! increase ArraySize!");
return;
}
}
}
}
public ToolBar addCustomToolBarTo(HTMLEditor he)
{
/* Thers one GridPane to the HTMLEditor where we add the ToolBar */
ToolBar customTB = new ToolBar();
for (Node candidate: (he.lookupAll("GridPane")))
{
if (candidate instanceof GridPane)
{
((GridPane) candidate).getChildren().add(customTB);
break;
}
}
return customTB;
}
}
If someone really wants to use an unsupported way to hide the Toolbars then there is an even easier way to achieve this (I haven't tested if this causes any problems in the HTMLEditor control so use this at your own risk).
package htmleditorsample;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
public class HTMLEditorSample extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
final HTMLEditor htmlEditor = new HTMLEditor();
primaryStage.setScene(new Scene(htmlEditor));
primaryStage.show();
for (Node toolBar = htmlEditor.lookup(".tool-bar"); toolBar != null; toolBar = htmlEditor.lookup(".tool-bar")) {
((Pane) toolBar.getParent()).getChildren().remove(toolBar);
}
}
}
Try this:
.html-editor .top-toolbar
{
-fx-max-width: 0px;
-fx-min-width: 0px;
-fx-pref-width: 0px;
-fx-max-height: 0px;
-fx-min-height: 0px;
-fx-pref-height: 0px;
-fx-opacity: 0;
}
.html-editor .bottom-toolbar
{
-fx-max-width: 0px;
-fx-min-width: 0px;
-fx-pref-width: 0px;
-fx-max-height: 0px;
-fx-min-height: 0px;
-fx-pref-height: 0px;
-fx-opacity: 0;
}
You should be able to hide buttons from its toolbars, even remove them.
I'd do it this way:
final Map map = new HashMap();
for (Node candidate: (htmlEditor.lookupAll("ToolBar"))) {
List list = ((ToolBar) candidate).getItems();
for (int i = 0; i < list.size(); i++) {
Node b = (Node) list.get(i);
map.put(map.size() + 1, b);
}
}
// So we've fetch all buttons (including separators) and assigned
// each an index number. Now then to hide an item:
((Node) map.get(2)).setVisible(false); // Hides copy button
((Node) map.get(13)).setVisible(false); // Hides bullets button
// Or to just completely remove them:
map.remove(18); // Removes font-menu-button
map.remove(25); // Removes editor-strike button
.tool-bar
{
/*-fx-visibility:hidden;
-fx-display:none; */
-fx-opacity: 0;
}
opacity works, but the menu stays active.
This is a pretty old thread, but most of these answers only sort of work, especially on newer JDKs, so here is the custom HTML editor class that I wrote based on some of the concepts in this thread.
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.ToolBar;
import javafx.scene.web.HTMLEditor;
import java.util.ArrayList;
import java.util.HashSet;
public class MinimalHTMLEditor extends HTMLEditor {
public MinimalHTMLEditor() {
super();
customizeHtmlEditor(this);
}
public static void customizeHtmlEditor(final HTMLEditor editor) {
editor.setVisible(false);
Platform.runLater(() -> {
ToolBar toolBar1 = (ToolBar) editor.lookup(".top-toolbar");
ToolBar toolBar2 = (ToolBar) editor.lookup(".bottom-toolbar");
HashSet<Node> nodesToKeep = new HashSet<>();
nodesToKeep.add(editor.lookup(".html-editor-numbers"));
nodesToKeep.add(editor.lookup(".html-editor-bullets"));
nodesToKeep.add(editor.lookup(".html-editor-foreground"));
nodesToKeep.add(editor.lookup(".html-editor-background"));
nodesToKeep.add(editor.lookup(".html-editor-bold"));
nodesToKeep.add(editor.lookup(".html-editor-italics"));
nodesToKeep.add(editor.lookup(".html-editor-underline"));
nodesToKeep.add(editor.lookup(".html-editor-strike"));
toolBar1.getItems().removeIf(n -> !nodesToKeep.contains(n));
toolBar2.getItems().removeIf(n -> !nodesToKeep.contains(n));
ArrayList<Node> toCopy = new ArrayList<>();
toCopy.addAll(toolBar2.getItems());
toolBar2.getItems().clear();
toolBar1.getItems().addAll(toCopy);
toolBar2.setVisible(false);
toolBar2.setManaged(false);
editor.setVisible(true);
});
}
}
You can remove specific buttons using CSS, for example:
.html-editor-copy {
visibility: hidden;
}
The full list of the CSS button names can be found at:
Oracle CSS Reference Guide

java-me bluetooth file send

i am having two cell phones and i want to exchange file between these two.
Device A invoke java app, it will scan available bluetooth device in range, show them into list and user can select one device and click send.
i have written below code, it is not working.
package hello;
import java.io.*;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.io.StreamConnection.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.obex.*;
import javax.obex.ResponseCodes;
public class MyMidlet extends MIDlet implements CommandListener, DiscoveryListener
{
public Command cmdSend;
public Command cmdScan;
public TextBox myText;
public List devList;
public Form myForm;
private LocalDevice localDev;
private DiscoveryAgent dAgent;
private ServiceRecord servRecord;
private Vector myVector;
private ClientSession connection = null;
private String url = null;
private Operation op = null;
private boolean cancelInvoked = false;
public MyMidlet()
{
cmdSend = new Command("Send", 2, 0);
cmdScan = new Command("Scan", 5, 0);
}
public void startApp()
{
if(myText == null)
{
myText = new TextBox("Dummy Text", "Hello", 10, 0);
myText.addCommand(cmdScan);
myText.setCommandListener(this);
Display.getDisplay(this).setCurrent(myText);
}
}
public void pauseApp(){}
public void destroyApp(boolean flag) { }
public void commandAction(Command command, Displayable displayable)
{
if(command == cmdScan)
{
if(myForm == null) { myForm = new Form("Scanning"); }
else {
for(int i = 0; i < myForm.size(); i++) myForm.delete(i);
}
myForm.append("Scanning for bluetooth devices..");
Display.getDisplay(this).setCurrent(myForm);
if(devList == null)
{
devList = new List("Devices", 3);
devList.addCommand(cmdSend);
devList.setCommandListener(this);
} else
{
for(int j = 0; j < devList.size(); j++) devList.delete(j);
}
if(myVector == null) myVector = new Vector();
else myVector.removeAllElements();
try
{
if(localDev == null)
{
localDev = LocalDevice.getLocalDevice();
localDev.setDiscoverable(0x9e8b33);
dAgent = localDev.getDiscoveryAgent();
}
dAgent.startInquiry(0x9e8b33, this);
}
catch(BluetoothStateException bluetoothstateexception)
{
myForm.append("Please check your bluetooth is turn-on");
}
}
if(command == cmdSend)
{
myForm.setTitle("Sending");
for(int k = 0; k < myForm.size(); k++) myForm.delete(k);
myForm.append("Sending application..");
Display.getDisplay(this).setCurrent(myForm);
try
{
RemoteDevice remotedevice = (RemoteDevice)myVector.elementAt(devList.getSelectedIndex());
dAgent.searchServices(null, new UUID[] {new UUID(4358L)}, remotedevice, this);
return;
}
catch(BluetoothStateException bluetoothstateexception1)
{
myForm.append("could not open bluetooth: " + bluetoothstateexception1.toString());
}
}
}
public void deviceDiscovered(RemoteDevice remotedevice, DeviceClass deviceclass)
{
try
{
devList.append(remotedevice.getFriendlyName(false), null);
}
catch(IOException _ex)
{
devList.append(remotedevice.getBluetoothAddress(), null);
}
myVector.addElement(remotedevice);
}
public void servicesDiscovered(int i, ServiceRecord aservicerecord[])
{
servRecord = aservicerecord[0];
}
public void serviceSearchCompleted(int i, int j)
{
if(j != 1) myForm.append("service search not completed: " + j);
try
{
byte[] fileContent = "Raxit Sheth -98922 38248".getBytes();
String s=servRecord.getConnectionURL(0, false);
myForm.append("Debug 0");
connection = (ClientSession) Connector.open(s);
myForm.append("Debug1");
HeaderSet headerSet = connection.connect(null);
myForm.append("Debug1.1");
headerSet.setHeader(HeaderSet.NAME, "a.txt");
headerSet.setHeader(HeaderSet.TYPE, "text/plain");
headerSet.setHeader(HeaderSet.LENGTH, new Long(fileContent.length));
myForm.append("Debug1.2");
//op = connection.put(headerSet); throwing java.lang.IllegalArgument.Exception
op = connection.put(null);
myForm.append("Debug1.2.1");
op.sendHeaders(headerSet);
myForm.append("Debug1.3");
OutputStream out = op.openOutputStream();
myForm.append("Debug2");
//sending data
myForm.append("Debug3");
out.write(fileContent);
myForm.append("Debug4");
//int responseCode = op.getResponseCode();
//myForm.append("resp code="+responseCode);
out.close();
op.close();
connection.close();
myForm.append("Done");
//i was expecting this will send a.txt file with content Raxit Sheth -98922 38248
//to remote device's inbox/gallery/bluetooth folder
}
catch(Exception ex) { myForm.append(ex.toString()); }
}
public void inquiryCompleted(int i)
{
Display.getDisplay(this).setCurrent(devList);
}
}
Your problem is almost certainly the fact that you're starting your bluetooth scanning in the commandAction() method. This is a system lifecycle method, and needs to return quickly. Attempting to perform a blocking operations (such as bluetooth scanning) in this thread could tie up resources which the handset needs to do other things such as the actual scanning!
Refactor so that the scanning is performed in a new thread, then try again.

Resources