JFileChooser set Control Buttons Are Shown are false and 1 - java

I'm having difficulty getting the file back from a JFileChooser when setControlButtonsAreShown() is set to false.
If the user makes a selection of an exisiting file I can get this file with getSelectedFile(), but when they type in a new file name getSelectedFile() returns null.
When I use a JFileChooser with setControlButtonsAreShown(true) and I click on the Save button any filename the user has typed can be obtained with getSelectedFile() as expected, but when setControlButtonsAreShown(false) is used I just can't seem to get this file returned.
This happens even if I call approveSelection(), which supposedly does the same as clicking on the Save button if it had been show.
What am I doing wrong? Or any another way to assign JfileChooser open button action event to customized personal Jbutton?

This the workaround I came up with.
This will iterate through all the components inside FileChooser Container and get the text from the JTextField and set as selection in the FileChooser
Call this after some button click or any event.
private void failProofSetPath(JFileChooser chooser) {
File selectedFileFromTextBox = null;
String text = getTextOfFileViewer(chooser);
if (text != null && new File(text).exists()) {
selectedFileFromTextBox = new File(text);
}
if (selectedFileFromTextBox != null
&& (chooser.getSelectedFile() == null
|| !selectedFileFromTextBox.equals(chooser.getSelectedFile()))) {
chooser.setSelectedFile(selectedFileFromTextBox);
}
}
private String getTextOfFileViewer(Container c) {
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JTextField) {
JTextField b = (JTextField) comp;
return b.getText();
} else if (comp instanceof Container) {
String val = getTextOfFileViewer((Container) comp);
if (val != null) {
return val;
}
}
}
return null;
}

Related

How to identify button click using android accessibility?

I have located a button using accessibility, now I need to identify when it is pressed.
List<AccessibilityNodeInfo> sendMessageNodeList = getRootInActiveWindow().findAccessibilityNodeInfosByViewId("com.whatsapp:id/send");
if(sendMessageNodeList == null || sendMessageNodeList.isEmpty()){
return;
}
AccessibilityNodeInfo sendMessage = sendMessageNodeList.get(0);
if(!sendMessage.isVisibleToUser()){
return;
}

Java Array Index Out Of Bounds Exception: -1

Alright , I have a problem which I can't figure out whats wrong. So I have jList and List .
I need a function that when I click on item (in jList any item ) and it would change in my label icon , (I'm dealing with images).
It works somehow, it changes my label icon to the image I pick from jList, but it throws me Exception and the program crashes , usually first 2 items cause no errors , third and further items cause it. After it crashes and throws me bunch of red text , I can still change my icon.
This is the function where I get the images and add them to List (adding path to them)
private static void getImages(String src) throws IOException {
//Exctract the name of the image from the src attribute
int indexname = src.lastIndexOf("/");
if (indexname == src.length()) {
src = src.substring(1, indexname);
}
indexname = src.lastIndexOf("/");
String name = src.substring(indexname, src.length());
//Open a URL Stream
URL url = new URL(src);
InputStream in = url.openStream();
GPath=fPath+name;
OutputStream out = new BufferedOutputStream(new FileOutputStream( GPath));
//Im adding to the list string (link to image) here
imagesListN.add(GPath);
System.out.println("list size: "+imagesListN.size());
for (int b; (b = in.read()) != -1;) {
out.write(b);
}
out.close();
in.close();
}
It adds them normally . Yes I'm downloading them , that's why I want to see them once they are downloaded.
This is where I click on jList function.
list.addListSelectionListener(new ListSelectionListener() {
private int a;
#Override
public void valueChanged(ListSelectionEvent arg0) {
if (!arg0.getValueIsAdjusting()) {
String h;
int k;
k = list.getSelectedIndex();
System.out.println("List id: "+k);
a = Main.imagesListN.indexOf(k);
System.out.println("imagesListN id: "+a);
h = Main.imagesListN.get(k);
System.out.println("h : "+h);
ImageIcon img = new ImageIcon(h);
imageReview.setIcon(img);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Here is the jList (name list) . Exception is at
a = Main.imagesListN.indexOf(k);
it gives me -1 , but the h = Main.imagesListN.get(k); gives me the link I need and gives it to ImageIcon img = new ImageIcon(h); and then imageReview.setIcon(img); . Label icon changes everytime when I click on item I need. Maybe it's not a = Main.imagesListN.indexOf(k); that I'm looking at , but something gives me -1.
Btw I'm excecuting everything in Thread.
`public class Crawler extends Thread {
Main main = new Main();
public void run(){
try {
main.download();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`
nothing fancy here. Each functions are in there own class , getImages() is in main , listListener is in class Langas (Class where are all buttons,labels , etc. are created nothing else) and Thread well , Thread. Also it works fine after everything is downloaded , no exceptions . Error appears durring downloading proccess
indexOf api accepts Object as parameter, while get accepts Object as well as primitive types. So when you call get with primitive type element, it looks for element by an index which you may have found.
But when you do indexOf, you are searching for an object within your list and hence you get -1.

Edit JTable which contains files' info

I've got a JTable that is filled by Vectors. These Vectors get their content by a loop, listing all files in a specific folder. Now I want to edit a Cell (via the GUI) that contains a filename and the real File on the HD should be renamed too. So how do I archive this?
Here's my code for the method that fills the JTable.
private void reloadFiles(){
vecVectors.clear();
if (Variables.pathToFiles != null) {
Variables.listOfFiles.clear();
Variables.listOfFiles = listFilesForFolder(Variables.pathToFiles);
for (File file : Variables.listOfFiles) {
Vector<String> temp = new Vector<String>();
temp.add(file.getName());
vecVectors.add(temp);
}
table.removeAll();
table = new JTable(vecVectors, vecHeaders);
this.remove(listScroller);
listScroller.removeAll();
listScroller = new JScrollPane(table);
listScroller.setPreferredSize(new Dimension(950, 450));
this.add(listScroller);
System.out.println("Reloaded");
}
}
Instead of using vectors to fill your table, you can use a more sophisticated table model implementation that allows you to work directly with File objects as rows in your table. I'm talking about either DataObjectTableModel or Rob Camick's RowTableModel.
So, let's say you have the table model implementation solved and each row in your table is a File object. Now, I wouldn't make any cell editable and let the table just display files info, considering:
There are many factors that can go wrong (i.e: invalid or existent file name)
It's not a TableModel responsibility to reflect the update in the HD.
It can be done using TableModelListener but the events are fired once the model has changed, so if you have troubles updating the file name in the HD then you have to revert the table model's changes. Not so easy though.
In order to re-name a file, I'd attach a MouseListener to the table and show a pop up dialog to let the user input the new file name. Finally use the File API to rename the file and update the table model reflecting these changes.
Snippet
final DataObjectTableModel<File> model = new DataObjectTableModel<File>(header) {
// Override getValueAt() and getColumnClass() here
};
final JTable table = new JTable(model);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() >= 2 && !e.isPopupTrigger()) {
int selectedRow = table.rowAtPoint(e.getPoint());
if (selectedRow != -1) {
String newName = JOptionPane.showInputDialog (
null
, "Please input the new name"
, "Rename file"
, JOptionPane.INFORMATION_MESSAGE
);
if (newName != null) {
int modelIndex = table.convertRowIndexToModel(selectedRow);
File file = model.getDataObject(modelIndex);
// Maybe this part should be done
// using a SwingWorker to avoid blocking the EDT
String newPath = file.getParent() + File.separator + newName;
File newFile = new File(newPath);
if (file.renameTo(newFile)) {
model.deleteDataObject(modelIndex); // remove the old file
model.insertDataObject(newFile, modelIndex); // insert the new file in the same index
} else {
JOptionPane.showMessageDialog (
null
, "An error happened trying to rename file " + file.getName()
, "Error!"
, JOptionPane.WARNING_MESSAGE
);
}
}
} // if (selectedRow != -1)
} // if (e.getClickCount() >= 2 && !e.isPopupTrigger())
}
});

JasperViewer - How to set file name and set the extension (format)?

I am developing Java desktop based application using Swing framework and JasperReports for reporting. I have some problems, when JasperViewer comes up and I want to save the report.
How can I set the name of the file (default is blank) in the save dialog and how to limit only Pdf format?
Here is my code:
JRBeanCollectionDataSource beanCollection=new JRBeanCollectionDataSource(matakuliahs);
Map<String,Object> map=new HashMap<String, Object>();
map.put("namaMahasiswa", mahasiswa.getNama());
InputStream input=getClass().getResourceAsStream("/reportsederhana/reportsederhana.jrxml");
JasperDesign design=JRXmlLoader.load(input);
JasperReport report=JasperCompileManager.compileReport(design);
JasperPrint jasperPrint=JasperFillManager.fillReport(report, map, beanCollection);
jasperPrint.setName("Laporan "+mahasiswa.getNama()); // it doesn't give the name
JasperViewer.viewReport(jasperPrint,false);
For setting the default extension(s) to save to, one idea is that you need to somehow get the JRViewer instance from a JasperViewer (instance) and then, on the void JRViewer instance, you can set some save contributions. Have a look at JRViewer.setSaveContributors(JRSaveContributor[] saveContribs).
For setting the file name, i am not entirely sure, but have a look at JRViewer.JRViewer(String, boolean).
Also check the JRViewer and the JasperViewer source code, it may come in handy.
It is an old post but I ran into the same problem...
I extended my viewer component from net.sf.jasperreports.view.JRViewer. After some code review I saw that it is only possible to control the 'lastFolder' but not the filename from outside. So you can set the last used folder if it is not set already by:
if (lastFolder == null) {
this.lastFolder = new File(System.getProperty("user.home"));
}
But, and thats the hint: All buttons of toolbar are public fields!
So for my solution I removed all ActionListeners of the save button (btnSave):
for (ActionListener actionListener : this.btnSave.getActionListeners()) {
this.btnSave.removeActionListener(actionListener);
}
And then added my own implementation. It is pretty like the original one only with the difference that I control the file name depending to the report name and current timestamp.
...
File file = new File(lastFolder.getPath() + System.getProperty("file.separator") + DateTime.now().toString() + "_" + jasperPrint.getName());
...
Additionally I set the pre-selected file extension from .jasperprint to .pdf which is more convenient.
...
fileChooser.setFileFilter((FileFilter) saveContributors.get(1));
...
The full ActionListener code is as follows:
this.btnSave.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setLocale(getLocale());
fileChooser.updateUI();
File file = new File(lastFolder.getPath() + System.getProperty("file.separator") + DateTime.now().toString() + "_" + jasperPrint.getName());
fileChooser.setSelectedFile(file);
for (int i = 0; i < saveContributors.size(); i++)
fileChooser.addChoosableFileFilter((FileFilter) saveContributors.get(i));
if (saveContributors.contains(lastSaveContributor))
fileChooser.setFileFilter(lastSaveContributor);
else if (saveContributors.size() > 1)
fileChooser.setFileFilter((FileFilter) saveContributors.get(1));
if (lastFolder != null)
fileChooser.setCurrentDirectory(lastFolder);
int retValue = fileChooser.showSaveDialog(JasperViewer.this);
if (retValue == 0) {
FileFilter fileFilter = fileChooser.getFileFilter();
file = fileChooser.getSelectedFile();
lastFolder = file.getParentFile();
JRSaveContributor contributor = null;
if (fileFilter instanceof JRSaveContributor) {
contributor = (JRSaveContributor) fileFilter;
} else {
int i = 0;
do {
if (contributor != null || i >= saveContributors.size())
break;
contributor = (JRSaveContributor) saveContributors.get(i++);
if (!contributor.accept(file))
contributor = null;
} while (true);
if (contributor == null)
contributor = new JRPrintSaveContributor(jasperReportsContext, getLocale(), null);
}
lastSaveContributor = contributor;
try {
contributor.save(jasperPrint, file);
} catch (JRException ex) {
logger.error("Could not save report.", ex);
JOptionPane.showMessageDialog(JasperViewer.this, trc("JasperViewer.error.save", "Could not save report."));
}
}
}
});

Lotus notes plugin to intercept outgoing emails (JAVA)

I need to develop a Lotus Notes plug-in that adds some UI to Lotus Notes main UI and does the following when user creates & sends an email:
Intercept the outgoing email to see if there are any attachments in email.
If there is any attachment found in email, cancel sending the email.
Manipulate the attachments of email and then send the email again (by calling some Notes API)
Is this doable in Lotus Notes plug-ins?
Thanks & regards,
Nadeem Ullah
package com.ibm.NotesJava.agents;
import lotus.domino.*;
import java.io.File;
import java.io.FileInputStream;
import java.lang.*;
import java.util.*;
import java.awt.*;
import java.awt.List;
import java.awt.event.*;
import java.text.SimpleDateFormat;
public class MyJavaAgent extends AgentBase {
//Main metho which is called by lotus notes
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
// (Your code goes here)
Name n = session.createName(agentContext.getEffectiveUserName());
String st = n.getCommon();
Log log=session.createLog("JAVA_AGENT");
log.openFileLog("JAVA_AGENT.log");
MessageBox mb = new MessageBox();
try{
log.logAction("");
log.logAction("******************************Starting JAVA AGENT ************************");
log.logAction("Hello " + st + "!");
log.logAction("Executing JavaAgentTest with Agent: "+agentContext.getCurrentAgent().getName());
Database db = agentContext.getCurrentDatabase();
//System.out.println("Loading emaildetails.properties file from following location:C:\\Program Files\\Lotus\\Notes\\framework\\emaildetails.properties");
log.logAction("Loading emaildetails.properties file from following location:C:\\Program Files\\Lotus\\Notes\\framework\\emaildetails.properties");
Properties pro = new Properties();
File fil = new File("C:\\Program Files\\Lotus\\Notes\\framework\\emaildetails.properties");
//***********LOGIC*********
DocumentCollection coll=agentContext.getUnprocessedDocuments();
Document doc=coll.getFirstDocument();
//get input from user about the process area
}
}
/************************Library Code ***********************************/
/*
* The MessageBox class allows you to create simple message boxes
* using only the java.awt classes. All you have to do is create an instance
* of a MessageBox and use it to call the doOkCancelDialog or the
* doInputBox methods. You can use a single MessageBox instance to
* create multiple dialogs.
*
* This class has been implemented here as an inner class, but there's
* no reason why it couldn't be a class all by itself. The functionality to
* create buttons and messageboxes has been modularized, so it should
* be easy for you to add your own methods to this class, or make global
* modifications as you desire.
*
* The only really complicated/weird thing I had to do was to write and
* include the MultiLineLabel class, which is included towards the end
* of this class as an inner class. Read the comments associated with
* that class to see what's going on there.
*
* Make sure you import java.awt.* and java.awt.event.*
*
* Julian Robichaux -- http://www.nsftools.com
*/
class MessageBox {
public final int NO_ACTION = -1;
public final int CANCEL_ACTION = 0;
public final int OK_ACTION = 1;
int actionCode = NO_ACTION;
Frame parent;
Dialog msgbox;
MultiLineLabel msglabel; // our custom class, defined later
Panel buttons;
Button ok, cancel;
TextField textbox;
Choice dropdown;
List multilist;
public MessageBox () {
// this is the invisible Frame we'll be using to call all of our Dialogs
parent = new Frame();
}
public void dispose () {
// use this when you're ready to clean up
try { msgbox.dispose(); } catch (Exception e) {}
try { parent.dispose(); } catch (Exception e) {}
}
/*
* This method will create a simple dialog box with a title, a message,
* and Ok/Cancel buttons. It will halt execution of your program until
* one of the buttons is clicked, and it will return either OK_ACTION
* if the Ok button is clicked, or CANCEL_BUTTON if the Cancel
* button is clicked.
*/
public int doOkCancelDialog (String title, String message) {
actionCode = NO_ACTION;
try {
// create the messagebox
msgbox = new Dialog(parent, title, true);
msgbox.setLayout(new BorderLayout());
// create the label
initMsglabel(message);
msgbox.add("North", msglabel);
// create the OK and Cancel buttons
buttons = new Panel();
buttons.setLayout(new FlowLayout());
initOkButton();
buttons.add(ok);
initCancelButton();
buttons.add(cancel);
msgbox.add("South", buttons);
// display everything (the system will wait until a button is pressed
// before returning)
displayMsgbox();
msgbox.dispose(); // just in case the ActionListeners didn't fire...
} catch (Exception e) {
}
return actionCode;
}
/*
* This method will create a dialog box that allows the user to enter
* text into a field. It also has a title, a message, and Ok/Cancel buttons,
* and will halt execution of your program until one of the buttons is
* clicked or the user enters text into the field and presses "Enter".
* If the user clicks the Ok button or enters text and presses "Enter",
* then the text in the field will be returned; otherwise, this method will
* return null (which usually indicates that the user clicked Cancel).
*/
public String doInputBox (String title, String message, String defaultText) {
actionCode = NO_ACTION;
try {
// create the messagebox
msgbox = new Dialog(parent, title, true);
msgbox.setLayout(new BorderLayout());
// create the label
initMsglabel(message);
msgbox.add("North", msglabel);
// create the text field
initTextbox(defaultText);
msgbox.add("Center", textbox);
// create the OK and Cancel buttons
buttons = new Panel();
buttons.setLayout(new FlowLayout());
initOkButton();
buttons.add(ok);
initCancelButton();
buttons.add(cancel);
msgbox.add("South", buttons);
// display everything (the system will wait until a button is pressed
// before returning)
displayMsgbox();
msgbox.dispose(); // just in case the ActionListeners didn't fire...
} catch (Exception e) {
}
if (actionCode == OK_ACTION)
return textbox.getText();
else
return null;
}
/*
* This method will create a dialog box that allows the user to select from
* a dropdown list. It also has a title, a message, and Ok/Cancel buttons,
* and will halt execution of your program until one of the buttons is
* clicked. If the user clicks the Ok button then the text in the field will be
* returned; otherwise, this method will return null (which usually indicates
* that the user clicked Cancel).
*/
public String doDropdownBox (String title, String message, String[] selections) {
actionCode = NO_ACTION;
try {
// create the messagebox
msgbox = new Dialog(parent, title, true);
msgbox.setLayout(new BorderLayout());
// create the label
initMsglabel(message);
msgbox.add("North", msglabel);
// create the dropdown box
initDropdown(selections);
msgbox.add("Center", dropdown);
// create the OK and Cancel buttons
buttons = new Panel();
buttons.setLayout(new FlowLayout());
initOkButton();
buttons.add(ok);
initCancelButton();
buttons.add(cancel);
msgbox.add("South", buttons);
// display everything (the system will wait until a button is pressed
// before returning)
displayMsgbox();
msgbox.dispose(); // just in case the ActionListeners didn't fire...
} catch (Exception e) {
}
if (actionCode == OK_ACTION)
return dropdown.getSelectedItem();
else
return null;
}
/*
* This method will create a dialog box that allows the user to select from
* a list of options (use the allowMultiSelect parameter to indicate whether
* the user can select multiple items from the list [true] or just one [false]).
* It also has a title, a message, and Ok/Cancel buttons, and will halt
* execution of your program until one of the buttons is clicked. If the user
* clicks the Ok button then the text in the field will be returned; otherwise,
* this method will return null (which usually indicates that the user clicked
* Cancel or didn't select anything).
*/
public String[] doMultilistBox (String title, String message, String[] selections, boolean allowMultiSelect) {
actionCode = NO_ACTION;
try {
// create the messagebox
msgbox = new Dialog(parent, title, true);
msgbox.setLayout(new BorderLayout());
// create the label
initMsglabel(message);
msgbox.add("North", msglabel);
// create the multilist field
initMultilist(4, allowMultiSelect, selections);
msgbox.add("Center", multilist);
// create the OK and Cancel buttons
buttons = new Panel();
buttons.setLayout(new FlowLayout());
initOkButton();
buttons.add(ok);
initCancelButton();
buttons.add(cancel);
msgbox.add("South", buttons);
// display everything (the system will wait until a button is pressed
// before returning)
displayMsgbox();
msgbox.dispose(); // just in case the ActionListeners didn't fire...
} catch (Exception e) {
}
if ((actionCode == OK_ACTION) &&
(java.lang.reflect.Array.getLength(multilist.getSelectedItems()) > 0))
return multilist.getSelectedItems();
else
return null;
}
/*
* The private methods below are simply reusable modular functions for
* creating various elements that may appear in a MessageBox dialog.
* They make it easier to write new public methods that create different
* kinds of dialogs, and also allow you to make global changes to all your
* dialog components pretty easily.
*/
private void initMsglabel (String message) {
// the actual message in the MessageBox (using the custom
// MultiLineLabel class, included below)
msglabel = new MultiLineLabel(message);
}
private void initOkButton () {
// the OK button
ok = new Button("OK");
ok.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionCode = OK_ACTION;
msgbox.dispose();
}
} );
}
private void initCancelButton () {
// the Cancel button
cancel = new Button("Cancel");
cancel.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionCode = CANCEL_ACTION;
msgbox.dispose();
}
} );
}
private void initTextbox (String defaultText) {
// the field that allows a user to enter text in an InputBox
textbox = new TextField(defaultText, 40);
// the ActionListener here will get called if the user presses "Enter"
textbox.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionCode = OK_ACTION;
msgbox.dispose();
}
} );
}
private void initDropdown (String[] selections) {
// a dropdown box that allows a user to select from a list of
// multiple items
dropdown = new Choice();
for (int i = 0; i < java.lang.reflect.Array.getLength(selections); i++)
dropdown.add(selections[i]);
}
private void initMultilist (int numOfLines, boolean allowMultiSelect, String[] selections) {
// a multiple selection box that allows a user to select one or
// more items. numOfLines indicates how many lines should be
// visible at a time, allowMultiSelect is a boolean value indicating
// whether or not the user should be allowed to select more than
// one item from the list, and selections is an array of Strings that
// is used to populate the selection box
multilist = new List(numOfLines, allowMultiSelect);
for (int i = 0; i < java.lang.reflect.Array.getLength(selections); i++)
multilist.add(selections[i]);
}
private void displayMsgbox () {
// once all of the components have been added to a dialog,
// use this method to display it
Dimension d = msgbox.getToolkit().getScreenSize();
msgbox.setLocation(d.width/3, d.height/3); // center the dialog (sort of)
msgbox.pack(); // organize all its components
msgbox.setResizable(false); // make sure the user can't resize it
msgbox.toFront(); // give it focus
msgbox.setVisible(true); // and display it
}
/*
* Okay, this is a pain, but java.awt doesn't natively have a Label-type class
* that allows you to display text that's more than one line. So I had to write one
* myself. The class below is a modification of some code from the fantastic
* book, "Java in a Nutshell".
*
* The big change I made was to allow this multi-line label to have a fixed width,
* so the Label wouldn't fly off the screen if you had a big paragraph of text to
* display. The width is specified in "columns", which I defined as the width of
* the letter "X" in whatever font is being used. The text that you add to the label
* is automatically split into chunks that are no longer than the number of columns
* specified (you'll see the code to do this in the parseLabel method).
*
* This sample implementation is an inner class of the MessageBox class, although
* it could also be a separate class all by itself. I made it an inner class to make it
* easier to copy and paste everything from one agent to another.
*
* Julian Robichaux -- http://www.nsftools.com
*/
class MultiLineLabel extends Canvas {
// a custom class that will display a text label at a fixed width across
// multiple lines
// (modification of MultiLineLabel class from "Java in a Nutshell")
String label;
String[] lines;
int rows = 1;
int cols = 40;
int margin = 6;
int rowHeight;
int lineAscent;
int maxWidth;
public MultiLineLabel (String text) {
// create a label with the default width
label = text;
}
public MultiLineLabel (String text, int columns) {
// create a label with the specified number of "columns" (where a column
// is the width of "X" in the font that we're using)
if (columns > 0)
cols = columns;
label = text;
}
protected void measure () {
// get the global values we use in relation to our current font
FontMetrics fm = this.getFontMetrics(this.getFont());
if (fm == null)
return;
rowHeight = fm.getHeight();
lineAscent = fm.getAscent();
maxWidth = fm.stringWidth("X") * cols;
}
private int stringWidth (String text) {
// calculate the width of a String using our current font
FontMetrics fm = this.getFontMetrics(this.getFont());
if (fm == null)
return 0;
return fm.stringWidth(text);
}
public Font getFont () {
// return the font that we're currently using
return super.getFont();
}
public void setFont (Font f) {
// change the font that we're currently using, and redraw the
// label with the new font
super.setFont(f);
repaint();
}
public void addNotify () {
// automatically invoked after our label/Canvas is created but
// before it's displayed (FontMetrics aren't available until
// super.addNotify() has been called)
super.addNotify();
measure();
}
public Dimension getPreferredSize () {
// called by the LayoutManager to find out how big we want to be
if (lines == null)
setText(label);
return new Dimension(maxWidth + (2 * margin), (rows * rowHeight) + (2 * margin));
}
public Dimension getMinimumSize () {
// called by the LayoutManager to find out what our bare minimum
// size requirements are
if (lines == null)
setText(label);
return new Dimension(maxWidth, (rows * rowHeight));
}
public void setText (String text) {
// change the text we're using for this label
label = text;
parseLabel();
}
private void parseLabel () {
// parses the text we want to display in the label, so that the lines[]
// variable contains lines of text that are no wider than maxWidth
String token, word;
StringBuffer msg = new StringBuffer("");
StringBuffer line = new StringBuffer("");
// do an initial measurement, to make sure we have maxWidth
measure();
rows = 0;
// we'll be tokenizing the label String twice, first at every end-of-line
// character ('\n') and then at every space (if the lines are too long),
// in order to generate an StringBuffer of proper length lines, all
// separated by \n
java.util.StringTokenizer st1 = new java.util.StringTokenizer(label, "\n", false);
while (st1.hasMoreTokens()) {
token = st1.nextToken();
if (stringWidth(token) <= maxWidth) {
// if the whole line is shorter than the maxWidth allowed, we can
// just add this line to the buffer and get the next one
rows++;
msg.append(token + "\n");
} else {
// if the line was too long, we'll have to break it up manually by
// tokenizing the line at every space and adding words together
// one by one until we have a line that's greater than maxWidth;
// then we can add that shorter line to the buffer and keep doing
// that until we're out of words
java.util.StringTokenizer st2 = new java.util.StringTokenizer(token, " ", false);
while (st2.hasMoreTokens()) {
word = st2.nextToken();
if ((stringWidth(line.toString()) + stringWidth(word)) > maxWidth) {
rows++;
msg.append(line.toString() + "\n");
line.setLength(0);
line.append(word + " ");
} else {
line.append(word + " ");
}
}
// after we've run out of words, add any remaining text to the buffer, too
if (line.length() > 0) {
rows++;
msg.append(line.toString() + "\n");
}
}
}
// once we're done, split the buffer into the lines[] array
java.util.StringTokenizer st = new java.util.StringTokenizer(msg.toString(), "\n");
lines = new String[rows];
for (int i = 0; i < rows; i++)
lines[i] = st.nextToken();
}
public void paint (Graphics g) {
// draw the actual label to the screen, with space around the edges
// based on the margins we've specified (for some reason, we have to
// call setLabel instead of just parseText here in order to get the size
// right, which is a little redundant, but whatever works...)
int y;
setText(label);
Dimension d = this.getSize();
y = lineAscent + (d.height - (rows * rowHeight)) / 2;
for (int i = 0; i < rows; i++, y += rowHeight)
g.drawString(lines[i], margin, y);
}
}
}// end of the MultiLineLabel class
I think you can do it using java lotus notes API.
Download the examples from here..
http://www.nsftools.com/tips/NotesTips.htm#javascraps
Download javascraps.zip file..it has example for maximum API..
To complete ur work u need to create a java agent in lotus notes and then you need to write java code as per your requirement using the java API to get the task done..

Categories

Resources