Mouse Click Events on JTable - java-8

I want to get the index of selected row when user double clicks on a row.
Here is my code:
tab.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int selectedRow = tab.getSelectedRow();
try {
String file = rows[selectedRow][2];
String path = "C:\\Users\\raj kumar\\Gallery\\" + file;
JLabel fileLable = new JLabel();
fileLable.setBounds(500, 600, 300, 300);
fileLable.setIcon(new ImageIcon(path));
pan.add(fileLable);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
But the tab.getSelectedRow() returns -1 even though I double clicked the row in the table.

You want to know on which row your mouse points, but you ask which row is selected. So the simple solution is, instead of
int selectedRow = tab.getSelectedRow();
you can use
int row = tab.rowAtPoint(e.getPoint());
to get the wanted row. The Event e has every necessary information you need. The e.getPoint() returns the exact Point your cursor is currently located. And the rowAtPoint() should be self explaining.
This also makes sure that you only work with one row at a time, if this is important to you. I don't know how getSelectedRow() works if multiple rows are selected.

Related

How to add multiple Textfields in single or multiple pages in a Loop

I am Using Itext 5 maven and I want to add multiple textfields in multiple pdf pages. like page 1 need 3 fields, page 2 need 4 fields etc.
I have write the below code
public byte[] setupDocument(EditPdfDTO editPdfDTOList, MultipartFile attachment)
{
WritePDF obj = new WritePDF();
Document document = null;
PdfWriter writer = null;
PdfImportedPage page = null;
PdfReader reader = null;
try
{
// Create output PDF
document = new Document(PageSize.A4);
document.setMargins(0, 0, 0, 0);
writer = PdfWriter.getInstance(document,
new FileOutputStream("D:/test.pdf"));
document.open();
PdfContentByte cb = writer.getDirectContent();
// Load existing PDF
reader = new PdfReader(attachment.getBytes());
int totalPages = reader.getNumberOfPages();
for (int i = 0; i < totalPages; i++)
{
page = writer.getImportedPage(reader, i + 1);
document.newPage();
cb.addTemplate(page, 0, 0);
for (int j = 0; j < editPdfDTOList.getPdf().size(); j++)
{
if (i + 1 == editPdfDTOList.getPdf().get(j).getPageNo())
{
BaseFont baseFont = null;
try
{
baseFont = BaseFont.createFont();
}
catch (DocumentException | IOException e1)
{
e1.printStackTrace();
}
int a, b;
a = editPdfDTOList.getPdf().get(j).getxCoordinate();
b = editPdfDTOList.getPdf().get(j).getyCoordinate();
String str = editPdfDTOList.getPdf().get(j).getTextContent();
Rectangle linkLocation =
new Rectangle(a, b + baseFont.getDescentPoint(str, 10),
a + 10 + baseFont.getWidthPoint(str, 10),
b + baseFont.getAscentPoint(str, 10) + 10);
TextField field =
new TextField(writer, linkLocation, "user1" + j+UUID.randomUUID());
field.setFontSize(10);
field.setOptions(TextField.MULTILINE | TextField.READ_ONLY);
field.setTextColor(BaseColor.RED);
field.setText(str);
field.setBorderWidth(1);
cb = writer.getDirectContent();
try
{
cb.addAnnotation(field.getTextField(),false);
}
catch (IOException | DocumentException e)
{
e.printStackTrace();
}
}
}
}
}
catch (DocumentException | IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
document.close();
}
return null;
}
this code is able to add only one Textfield on every expected but not to add 2 or many textfields in a single page.
there is no issue of multiple try--catch block.
The appropriate classes to use
First of, you say you "want to add multiple textfields in multiple pdf pages". When implementing tasks like this, i.e. tasks that take a single document and want to somehow manipulate it while keeping it structurally more or less as before, one should usually work with a PdfReader/PdfStamper couple. This allows you to concentrate on the manipulation and provides a copy of the original PDF with all its properties to work on.
Adding multiple fields to a page of an existing PDF
Adding multiple fields to a single existing page is trivial, e.g.:
PdfReader pdfReader = new PdfReader(resource);
PdfStamper pdfStamper = new PdfStamper(pdfReader, output);
TextField field1 = new TextField(pdfStamper.getWriter(),
new Rectangle(100, 800, 200, 820), "Field1");
field1.setBorderColor(BaseColor.CYAN);
field1.setBorderStyle(PdfBorderDictionary.STYLE_DASHED);
field1.setBorderWidth(BaseField.BORDER_WIDTH_MEDIUM);
field1.setText("Field 1");
pdfStamper.addAnnotation(field1.getTextField(), 1);
TextField field2 = new TextField(pdfStamper.getWriter(),
new Rectangle(300, 800, 400, 820), "Field2");
field2.setBorderColor(BaseColor.RED);
field2.setBorderStyle(PdfBorderDictionary.STYLE_INSET);
field2.setBorderWidth(BaseField.BORDER_WIDTH_THIN);
field2.setText("Field 2");
pdfStamper.addAnnotation(field2.getTextField(), 1);
pdfStamper.close();
(AddField test testAddMultipleFields)
Applied to my example document
the code generates
Thus, there is no conceptual problem adding multiple text fields to the same document page, it works in a very natural manner.
In your case I would switch to using a PdfReader/PdfStamper couple. If some issue still remain, I would inspect your data. Probably they simply contain only a single field dataset per page. Or two textfields have the same coordinates and, therefore, look like one. Or some text fields have off-screen coordinates. Or... Or... Or...
The original answer
Originally the code in the question looked differently. This original answer focused on issues of that code.
You claim your code
is able to add only one Textfield on every expected but not to add 2 or many textfields in a single page
I doubt that because
you have two distinct objects writing to the same file "D:/TemplateFilePDf/" + attachment.getOriginalFilename() concurrently, the PdfWriter writer and the PdfStamper stamper. If you get something sensible as a result of your code, then only by pure luck; and
additionally stamper is instantiated for a null instance of PdfReader. This actually will cause a NullPointerException in the constructor which will keep your textfield adding code from being executed at all.
Thus, either the code you shared is considerably different from the code you run or your test runs actually all throw that NullPointerException and you probably find the outputs of a former, less broken version of your code which happens to have added only a single text field.
After fixing those two issues, some questions still remain (e.g. what is the intention of that cb.fill()? That instruction is only allowed directly after a path definition, the path whose inner area to fill, but I don't see you defining any path).
Furthermore, you access your editPdfDTOList for a lot of relevant values but we don't know those values. Thus, we cannot run your code to try and reproduce the issue. Probably you create only a single textfield because that object contains only values for a single textfield...

CharmListView Infinite Scroll

I need basically an event that triggers at each 200 records loaded, so more data can be loaded until the end of data.
I tried to extend CharmListCell and using the method updateItem like this:
#Override
public void updateItem(Model item, boolean empty) {
super.updateItem(item, empty);
currentItem = item;
if (!empty && item != null) {
update();
setGraphic(slidingTile);
} else {
setGraphic(null);
}
System.out.println(getIndex());
}
But the System.out.println(getIndex()); method returns -1;
I would like to call my backend method when the scroll down gets the end of last fetched block and so on, until get the end of data like the "infinite scroll" technique.
Thanks!
The CharmListCell doesn't expose the index of the underlying listView, but even if it did, that wouldn't be of much help to find out if you are scrolling over the end of the current list or not.
I'd suggest a different approach, which is also valid for a regular ListView, with the advantage of having the CharmListView features (mainly headers and the refresh indicator).
This short sample, created with a single view project using the Gluon IDE plugin and Charm 5.0.0, shows how to create a CharmListView control, and fill it with 30 items at a time. I haven't provided a factory cell, nor the headers, and for the sake of simplicity I'm just adding consecutive integers.
With a lookup, and after the view is shown (so the listView is added to the scene) we find the vertical ScrollBar of the listView, and then we add a listener to track its position. When it gets closer to 1, we simulate the load of another batch of items, with a pause transition that represents a heavy task.
Note the use of the refresh indicator. When new data is added, we scroll back to the first of the new items, so we can keep scrolling again.
public class BasicView extends View {
private final ObservableList<Integer> data;
private CharmListView<Integer, Integer> listView;
private final int batchSize = 30;
private PauseTransition pause;
public BasicView() {
data = FXCollections.observableArrayList();
listView = new CharmListView<>(data);
setOnShown(e -> {
ScrollBar scrollBar = null;
for (Node bar : listView.lookupAll(".scroll-bar")) {
if (bar instanceof ScrollBar && ((ScrollBar) bar).getOrientation().equals(Orientation.VERTICAL)) {
scrollBar = (ScrollBar) bar;
break;
}
}
if (scrollBar != null) {
scrollBar.valueProperty().addListener((obs, ov, nv) -> {
if (nv.doubleValue() > 0.95) {
addBatch();
}
});
addBatch();
}
});
setCenter(new VBox(listView));
}
private void addBatch() {
listView.setRefreshIndicatorVisible(true);
if (pause == null) {
pause = new PauseTransition(Duration.seconds(1));
pause.setOnFinished(f -> {
int size = data.size();
List<Integer> list = new ArrayList<>();
for (int i = size; i < size + batchSize; i++) {
list.add(i);
}
data.addAll(list);
listView.scrollTo(list.get(0));
listView.setRefreshIndicatorVisible(false);
});
} else {
pause.stop();
}
pause.playFromStart();
}
}
Note also that you could benefit from the setOnPullToRefresh() method, at any time. For instance, if you add this:
listView.setOnPullToRefresh(e -> addBatch());
whenever you go to the top of the list and drag it down (on a mobile device), it will make another call to load a new batch of items. Obviously, this is the opposite behavior as the "infinite scrolling", but it is possible as well with the CharmListView control.

Invalidate() and child_wnd_name.InvalidateRect (&rect) cause different results

I am writing a dialog based application which has one static control, one button and two edit controls. The static's type is class MyStatic : public CStatic which has an OnPaint() defined as follows:
void MyStatic::OnPaint()
{
CPaintDC dc(this);
int Row = pBGDlg->iRow; //pBGDlg is a pointer to the dialog
int Column = pBGDlg->iColumn; //iRow and iColumn are variables of the two edit controls
int RowHei = pBGDlg->iRowHei;
int ColumnWid = pBGDlg->iColumnWid;
if (bBuPressed)
{
for (int i = 0; i <= Row; ++i)
{
dc.MoveTo (0, i * RowHei);
dc.LineTo (Column * ColumnWid, i * RowHei);
}
}
Whenever the user input two integers and press the button, the application will draw corresponding lines on the static
void CProjDlg::OnClickedIdpreview()
{
UpdateData ();
mystatic.GetClientRect (&rtStatic); //mystatic is the name of the static
iRowHei = (rtStatic.Height () - 1) / iRow;
iColumnWid = (rtStatic.Width () - 1) / iColumn;
mystatic.bBuPressed = true;
Invalidate ();
UpdateWindow ();
}
For Example:Input 4 to the 1st edit control and then input 1 to the 1st edit control. However, if I substitute mystatic.InvalidateRect(&rtStatic); and mystatic.UpdateWindow(); for Invalidate(); and UpdateWindow(); respectively, the application fails to erase previous results. For example: Input 4 to the 1st edit control and then input 5 to the 1st edit control. I can not figure out why the second method fails. Could anyone explain for me? Thank you very much.

Datagridview Textbox Not keeping time from DateTime.Now

I'm using the following code to set the value of a textbox in a datagridview. The code does exactly what I want. However when I leave the current row, the value in CloseDate maintains the current date but discards the time and changes to "00:00:00".
The underlying SQL field is set to datetime. The DataType in the underlying data source is system.DateTime, DateTimeMode is set to UnspecifiedLocal.
What am I missing?
tbl_TransactionsDataGridView.CurrentRow.Cells["CloseDate"].Value = DateTime.Now;
From the EditingControlShowing action of my datagridview, I'm looking to see which field is being changed. In this instance I want 6.
private void tbl_TransactionsDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null && tbl_TransactionsDataGridView.CurrentCell.ColumnIndex == 3)
{
// Remove an existing event-handler, if present, to avoid
// adding multiple handlers when the editing control is reused.
combo.SelectedIndexChanged -=
new EventHandler(ComboBox_SelectedIndexChanged);
// Add the event handler.
combo.SelectedIndexChanged +=
new EventHandler(ComboBox_SelectedIndexChanged);
}
if (combo != null && tbl_TransactionsDataGridView.CurrentCell.ColumnIndex == 6)
{
// Remove an existing event-handler, if present, to avoid
// adding multiple handlers when the editing control is reused.
combo.SelectedIndexChanged -=
new EventHandler(Status_SelectedIndexChanged);
// Add the event handler.
combo.SelectedIndexChanged +=
new EventHandler(Status_SelectedIndexChanged);
}
}
When the column index is 6, the following gets fired (I'm having some difficulties with getting this to fire correctly all the time, but thats an issue for another thread.). When it fires, it fires correctly and while I stay in the current row, CloseDate has the value I want it to. However, if I go to a new row and create a new record or select another record in the datagridview, CloseDate changes from "8/18/2014 8:42:32" to "8/18/2014 00:00:00".
private void Status_SelectedIndexChanged(object sender, EventArgs e)
{
object oStatus = new object();
oStatus = ((ComboBox)sender).SelectedValue;
if (Convert.IsDBNull(oStatus) && Convert.ToInt32(oStatus) == 1)
{
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckOutEmployee"].Value = Environment.UserName;
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckInEmployee"].Value = null;
tbl_TransactionsDataGridView.CurrentRow.Cells["CloseDate"].Value = null;
SendKeys.Send("{TAB}");
}
if (!Convert.IsDBNull(oStatus) && Convert.ToInt32(oStatus) > 1)
{
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckInEmployee"].Value = Environment.UserName;
tbl_TransactionsDataGridView.CurrentRow.Cells["CloseDate"].Value = DateTime.Now;
SendKeys.Send("{TAB}");
}
}

Blackberry ListField: how to add Listener for list row click

Suppose i had a Screen class that has 10 ListField:
Vector v_prj_title,v_prj_mgr
// v_prj_title contains name of projects
// v_prj_mgr contains name of the project_manager of v_prj_title sequentially.
//Vector send_vector
//ListField myList
//ListCallBack callback
//It is clear from the code that in myList, I m inserting a vector send_vector ie callback.insert(send_vector,i), which contains 2 strings collected one from v_prj_title and other from v_prj_mgr.
for(int i=0;i<10;i++)
{
myList.insert(i);
t1 = v_prj_title.elementAt(i).toString();
send_vector = new Vector(2);
send_vector.addElement(t1);
t2 = v_prj_mgr.elementAt(i).toString();
send_vector.addElement(t2);
callback.insert(send_vector,i);
}
Now I'm getting confused how to add eventListener to particular ListField, e.g. suppose if I click the 3rd ListField,(suppose this is the displayed data below) a bitmap picture should be displayed in the 3rd ListField and the name of the project (Project_Social_Meeting) and project_manager (Tom Clerk) should be inserted into database (SQlLite)
1. a. Project_Chat_Master( project name)
b. Vyom Ryan (project manager)
2. a. Project_Online_Gaming
b. Vivek Roy
3. a. Project_Social_Meeting
b. Tom Clerk
.
.
etc.....
create a CustomField/Manager depending on your requirement.(which may contain images/strings/...)
then add them to the callback method
Ex:
step:1
//creating a custom field
class MYListFieldItem extends Field
{
//#override
paint(graphics g)
{
g.drawbitmap(bitmap,0,0);
g.drawtext(string,bitmap.getwidth()+5<padding>,Math.min(bitmap.getHeight(),getFont().getHeight()));
//#override
layout(....)
{
setExtent(Math.min(width,bitmap.getwidth()+padding+getfont.getadvance(stringtext)),
Math.min(height,Math.min(bitmap.getHeight,getFont().getHeight())));
}
}
step-2:
//create list items
MYListFieldItem [] fields[] = new MYListFieldItem [<numOfListItems>];
for(int i=0;i<fields.size;i++)
{
_callback = new MyListFieldCallBack();
_callback.insert(fields[i],i);
}
step-3:
//set listeners
mylistFielditem[i].setchangeListener(new fieldchangeListener(){
fieldChanged(field)
{
//do your action here.
});
//TIP: if the fields are just strings,
//#override
navigationclick()
{
if(status == keypadlistener.status_fourway)
{
MYListFieldItem fld = (ListField)getLiefFieldwithFocus();
//do your coding
}
}

Resources