Javafx 2 : How do I delete a row or column in Gridpane - javafx-2

If I want to add a row of text fields programatically in JavaFx, i can simply use the gridpane add method
This adds a set of text fields to row 1.
for (int i = 0; i < Fields.size(); i++) {
gridpane.add(new TextField(), i, 1);
}
Similarly, How do I delete a row?. I dont find a suitable method to delete a row/column conveeniently in JavaFX.

There's no directly equivalent method. To remove nodes, just use
gridpane.getChildren().remove(...); or gridpane.getChildren().removeAll(...); and pass in the nodes you want to remove from the pane.

In Java 8+, you can use removeIf:
gridPane.getChildren().removeIf(node -> GridPane.getRowIndex(node) == rowNumber);
Caveat
If removing items from the 0th row, also check GridPane.getRowIndex(node) == null, i.e.,
node -> GridPane.getRowIndex(node) == null || GridPane.getRowIndex(node) == 0
(I think this is JavaFX leaving the row number as null when no row number is given in the corresponding element in FXML, even though giving no row number in FXML means the element is in the 0th row, since the default row is the 0th row.)

This works pretty well:
while(MainGridPane.getRowConstraints().size() > 0){
MainGridPane.getRowConstraints().remove(0);
}
while(MainGridPane.getColumnConstraints().size() > 0){
MainGridPane.getColumnConstraints().remove(0);
}

JavaFX APIs are pretty lacking (like easily removing rows from GridPane) and unintuitive (like returning null instead 0 for GridPane.getRowIndex). Here is solution I came up with:
Utils:
package io.github.againpsychox.javaspeedrunsapp.utils;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
public class GridPaneUtils {
/**
* Gets row index constrain for given node, forcefully as integer: 0 as null.
* #param node Node to look up the constraint for.
* #return The row index as primitive integer.
*/
public static int getRowIndexAsInteger(Node node) {
final var a = GridPane.getRowIndex(node);
if (a == null) {
return 0;
}
return a;
}
/**
* Removes row from grid pane by index.
* Note: Might not work correctly if row spans are used.
* #param grid Grid pane to be affected.
* #param targetRowIndexIntegerObject Target row index to be removed. Integer object type, because for some reason `getRowIndex` returns null for children at 0th row.
*/
public static void removeRow(GridPane grid, Integer targetRowIndexIntegerObject) {
final int targetRowIndex = targetRowIndexIntegerObject == null ? 0 : targetRowIndexIntegerObject;
// Remove children from row
grid.getChildren().removeIf(node -> getRowIndexAsInteger(node) == targetRowIndex);
// Update indexes for elements in further rows
grid.getChildren().forEach(node -> {
final int rowIndex = getRowIndexAsInteger(node);
if (targetRowIndex < rowIndex) {
GridPane.setRowIndex(node, rowIndex - 1);
}
});
// Remove row constraints
grid.getRowConstraints().remove(targetRowIndex);
}
}
Example usage:
GridPaneUtils.removeRow(this.grid, GridPane.getRowIndex(this.idTextField));
Posting my solution for further readers...

Related

Find position of item in list using Binary Search

The question is:
Given a list of String, find a specific string in the list and return
its index in the ordered list of String sorted by mergesort. There are
two cases:
The string is in the list, return the index it should be in, in the ordered list.
The String is NOT in the list, return the index it is supposed to be in, in the ordered list.
Here is my my code, I assume that the given list is already ordered.
For 2nd case, how do I use mergesort to find the supposed index? I would appreciate some clues.
I was thinking to get a copy of the original list first, sort it, and get the index of the string in the copy list. Here I got stuck... do I use mergesort again to get the index of non-existing string in the copy list?
public static int BSearch(List<String> s, String a) {
int size = s.size();
int half = size / 2;
int index = 0;
// base case?
if (half == 0) {
if (s.get(half) == a) {
return index;
} else {
return index + 1;
}
}
// with String a
if (s.contains(a)) {
// on the right
if (s.indexOf(s) > half) {
List<String> rightHalf = s.subList(half + 1, size);
index += half;
return BSearch(rightHalf, a);
} else {
// one the left
List<String> leftHalf = s.subList(0, half - 1);
index += half;
return BSearch(leftHalf, a);
}
}
return index;
}
When I run this code, the index is not updated. I wonder what is wrong here. I only get 0 or 1 when I test the code even with the string in the list.
Your code only returns 0 or 1 because you don't keep track of your index for each recursive call, instead of resetting to 0 each time. Also, to find where the non-existent element should be, consider the list {0,2,3,5,6}. If we were to run a binary search to look for 4 here, it should stop at the index where element 5 is. Hope that's enough to get you started!

AS3 "Advanced" string manipulation

I'm making an air dictionary and I have a(nother) problem. The main app is ready to go and works perfectly but when I tested it I noticed that it could be better. A bit of context: the language (ancient egyptian) I'm translating from does not use punctuation so a phrase canlooklikethis. Add to that the sheer complexity of the glyph system (6000+ glyphs).
Right know my app works like this :
user choose the glyphs composing his/r word.
app transforms those glyphs to alphanumerical values (A1 - D36 - X1A, etc).
the code compares the code (say : A5AD36) to a list of xml values.
if the word is found (A5AD36 = priestess of Bast), the user gets the translation. if not, s/he gets all the possible words corresponding to the two glyphs (A5A & D36).
If the user knows the string is a word, no problem. But if s/he enters a few words, s/he'll have a few more choices than hoped (exemple : query = A1A5AD36 gets A1 - A5A - D36 - A5AD36).
What I would like to do is this:
query = A1A5AD36 //word/phrase to be translated;
varArray = [A1, A5A, D36] //variables containing the value of the glyphs.
Corresponding possible words from the xml : A1, A5A, D36, A5AD36.
Possible phrases: A1 A5A D36 / A1 A5AD36 / A1A5A D36 / A1A5AD36.
Possible phrases with only legal words: A1 A5A D36 / A1 A5AD36.
I'm not I really clear but to things simple, I'd like to get all the possible phrases containing only legal words and filter out the other ones.
(example with english : TOBREAKFAST. Legal = to break fast / to breakfast. Illegal = tobreak fast.
I've managed to get all the possible words, but not the rest. Right now, when I run my app, I have an array containing A1 - A5A - D36 - A5AD36. But I'm stuck going forward.
Does anyone have an idea ? Thank you :)
function fnSearch(e: Event): void {
var val: int = sp.length; //sp is an array filled with variables containing the code for each used glyph.
for (var i: int = 0; i < val; i++) { //repeat for every glyph use.
var X: String = ""; //variable created to compare with xml dictionary
for (var i2: int = 0; i2 < val; i2++) { // if it's the first time, use the first glyph-code, else the one after last used.
if (X == "") {
X = sp[i];
} else {
X = X + sp[i2 + i];
}
xmlresult = myXML.mot.cd; //xmlresult = alphanumerical codes corresponding to words from XMLList already imported
trad = myXML.mot.td; //same with traductions.
for (var i3: int = 0; i3 < xmlresult.length(); i3++) { //check if element X is in dictionary
var codeElement: XML = xmlresult[i3]; //variable to compare with X
var tradElement: XML = trad[i3]; //variable corresponding to codeElement
if (X == codeElement.toString()) { //if codeElement[i3] is legal, add it to array of legal words.
checkArray.push(codeElement); //checkArray is an array filled with legal words.
}
}
}
}
var iT2: int = 500 //iT2 set to unreachable value for next lines.
for (var iT: int = 0; iT < checkArray.length; iT++) { //check if the word searched by user is in the results.
if (checkArray[iT] == query) {
iT2 = iT
}
}
if (iT2 != 500) { //if complete query is found, put it on top of the array so it appears on top of the results.
var oldFirst: String = checkArray[0];
checkArray[0] = checkArray[iT2];
checkArray[iT2] = oldFirst;
}
results.visible = true; //make result list visible
loadingResults.visible = false; //loading screen
fnPossibleResults(null); //update result list.
}
I end up with an array of variables containing the glyph-codes (sp) and another with all the possible legal words (checkArray). What I don't know how to do is mix those two to make legal phrases that way :
If there was only three glyphs, I could probably find a way, but user can enter 60 glyphs max.

How to Multiply Data Gridview two columns and show the result in another column

I have a gridview (Order) with three columns:
Price
Quantity
Total
I want to multiply Price with Quantity and show the result in Total column of dataGridview.
Remember: my dataGridview isn't bind with any table.
I am trying this code to achieve my goal but this isn't working means value isn't being returned:
private void totalcal()
{
// is the foreach condition true? Remember my gridview isn't bound to any tbl
foreach (DataGridViewRow row in gvSale.Rows)
{
int a = Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value); // value is null why??
row.Cells[5].Value = a;
}
}
This is the method which I am calling on a button click. (It is not working reason define inside of my code above)
And plus I want to know which is the suitable Datagridview event for this calculation?? I don't want to calculate the total on button click
try
int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString())
insted of
Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value)
And you know you can call this method anytime, if you dont want it to be with button click. Call it after gvSale's row populating operations finished.
EDIT
I guess you want the calculations to be done while the user is entering Price or Quanitity. For that you need to write a EditingControlShowing method for your datagridview. Here's a piece of code. I tested it actually and got it working.
Add this code in your main class definition after InitializeComponent(); line
gvSale.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.gvSale_EditingControlShowing);
And then add this methods :
TextBox tb = new TextBox(); // this is just a textbox to use in editing control
int Price_Index = 3; // set this to your Price Column Index
int Quantity_Index = 4; // set this to your Quantity Column Index
int Total_Index = 5; // set this to your Total Column Index
private void gvSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (gvSale.CurrentCell.ColumnIndex == Price_Index || gvSale.CurrentCell.ColumnIndex == Quantity_Index)
{
tb = e.Control as TextBox;
tb.KeyUp += new KeyEventHandler(Calculate_Total);
}
}
private void Calculate_Total(object sender, KeyEventArgs e)
{
int Price_Value = 0;
int Quantity_Value = 0;
int.TryParse(gvSale.CurrentCell.ColumnIndex != Price_Index ? gvSale.CurrentRow.Cells[Price_Index].Value.ToString() : tb.Text, out Price_Value);
int.TryParse(gvSale.CurrentCell.ColumnIndex != Quantity_Index ? gvSale.CurrentRow.Cells[Quantity_Index].Value.ToString() : tb.Text, out Quantity_Value);
gvSale.CurrentRow.Cells[Total_Index].Value = Price_Value * Quantity_Value;
}

Smartgwt addMember changes top of parent

I have several nested layouts (VLayouts and HLayouts), which are included inside a tab pane. In one of these layouts (VLayout), there is severall elements which are added or removed dynamically depending on a window of selection. The first time the user makes a selection, the pane moves up several pixels (and you will not see the upper part of the pane). The rest of times, the pain remains in the wrong place.
In summary, the first adding affects to the top of the pane, and the rest of adding/removing doesn't affect to it.
This only happens on Chrome. However, Firefox and IE work ok.
My code of adding is:
int total = itemsPanel.getMembers().length - 1;
while (total >=0) {
itemsPanel.removeMember(itemsPanel.getMember(total));
total--;
}
Record[] records = selectorWindow.getSelectedRows();
if (records != null) {
for (Record record : records) {
String name = record.getAttribute("keyRecord");
HLayout item = items.get(name);
itemsPanel.addMember(row);
}
}
if (itemsPanel != null) {
int r = 80;
if (Utils.isReducedHeight()) {
r = 120;
}
int visibleHeight = getVisibleHeight() - StyleUtils.HEADER_HEIGHT - r;
itemsPanel.setHeight(Math.max(1, Math.min(itemsPanel.getMembers().length * Utils.getRowHeight(), visibleHeight)));
int h = Math.min(itemsPanel.getHeight() + 10, visibleHeight);
containerItemsPanel.setHeight(h);
}
I'm using gwt 2.5.1 and smartgwt 3.0. Any idea?
Thanks in advance

AutoFit Columns Width using jxl library in java [duplicate]

How to autofit content in cell using jxl api?
I know this is an old question at this point, but I was looking for the solution to this and thought I would post it in case someone else needs it.
CellView Auto-Size
I'm not sure why the FAQ doesn't mention this, because it very clearly exists in the docs.
My code looked like the following:
for(int x=0;x<c;x++)
{
cell=sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
c stores the number of columns created
cell is just a temporary place holder for the returned CellView object
sheet is my WriteableSheet object
The Api warns that this is a processor intensive function, so it's probably not ideal for large files. But for a small file like mine (<100 rows) it took no noticeable time.
Hope this helps someone.
The method is self explanatory and commented:
private void sheetAutoFitColumns(WritableSheet sheet) {
for (int i = 0; i < sheet.getColumns(); i++) {
Cell[] cells = sheet.getColumn(i);
int longestStrLen = -1;
if (cells.length == 0)
continue;
/* Find the widest cell in the column. */
for (int j = 0; j < cells.length; j++) {
if ( cells[j].getContents().length() > longestStrLen ) {
String str = cells[j].getContents();
if (str == null || str.isEmpty())
continue;
longestStrLen = str.trim().length();
}
}
/* If not found, skip the column. */
if (longestStrLen == -1)
continue;
/* If wider than the max width, crop width */
if (longestStrLen > 255)
longestStrLen = 255;
CellView cv = sheet.getColumnView(i);
cv.setSize(longestStrLen * 256 + 100); /* Every character is 256 units wide, so scale it. */
sheet.setColumnView(i, cv);
}
}
for(int x=0;x<c;x++)
{
cell=sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
It is fine, instead of scanning all the columns. Pass the column as a parameter.
void display(column)
{
Cell = sheet.getColumnView(column);
cell.setAutosize(true);
sheet.setColumnView(column, cell);
}
So when you wiill be displaying your text you can set the particular length. Can be helpfull for huge excel files.
From the JExcelApi FAQ
How do I do the equivilent of Excel's "Format/Column/Auto Fit Selection"?
There is no API function to do this for you. You'll need to write code that scans the cells in each column, calculates the maximum length, and then calls setColumnView() accordingly. This will get you close to what Excel does but not exactly. Since most fonts have variable width characters, to get the exact same value, you would need to use FontMetrics to calculate the maximum width of each string in the column. No one has posted code on how to do this yet. Feel free to post code to the Yahoo! group or send it directly to the FAQ author's listed at the bottom of this page.
FontMetrics presumably refers to java.awt.FontMetrics. You should be able to work something out with the getLineMetrics(String, Graphics) method I would have though.
CellView's autosize method doesn't work for me all the time. My way of doing this is by programatically set the size(width) of the column based on the highest length of data in the column. Then perform some mathematical operations.
CellView cv = excelSheet.getColumnView(0);
cv.setSize((highest + ((highest/2) + (highest/4))) * 256);
where highest is an int that holds the longest length of data in the column.
setAutosize() method WILL NOT WORK if your cell has over 255 characters. This is related to the Excel 2003 max column width specification: http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP005199291.aspx
You will need to write your own autosize method to handle this case.
Try this exemple:
expandColumns(sheet, 3);
workbook.write();
workbook.close();
private void expandColumn(WritableSheet sheet, int amountOfColumns){
int c = amountOfColumns;
for(int x=0;x<c;x++)
{
CellView cell = sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
}
Kotlin's implementation
private fun sheetAutoFitColumns(sheet: WritableSheet, columnsIndexesForFit: Array<Int>? = null, startFromRowWithIndex: Int = 0, excludeLastRows : Int = 0) {
for (columnIndex in columnsIndexesForFit?.iterator() ?: IntProgression.fromClosedRange(0, sheet.columns, 1).iterator()) {
val cells = sheet.getColumn(columnIndex)
var longestStrLen = -1
if (cells.isEmpty()) continue
for (j in startFromRowWithIndex until cells.size - excludeLastRows) {
if (cells[j].contents.length > longestStrLen) {
val str = cells[j].contents
if (str == null || str.isEmpty()) continue
longestStrLen = str.trim().length
}
}
if (longestStrLen == -1) continue
val newWidth = if (longestStrLen > 255) 255 else longestStrLen
sheet.setColumnView(columnIndex, newWidth)
}
}
example for use
sheetAutoFitColumns(sheet) // fit all columns by all rows
sheetAutoFitColumns(sheet, arrayOf(0, 3))// fit A and D columns by all rows
sheetAutoFitColumns(sheet, arrayOf(0, 3), 5)// fit A and D columns by rows after 5
sheetAutoFitColumns(sheet, arrayOf(0, 3), 5, 2)// fit A and D columns by rows after 5 and ignore two last rows

Resources