| stringtokenizer that traps ASCII linebreaks |
|
 |
Index ‹ java-programmer
|
- Previous
- 7
- java.util.zip not handling Unicode filenamesI have a zip file that contains files with Asian filenames.
java.util.zip.ZipFile opens it, but the filenames are garbled. Is there any
way to handle filenames that contain unicode characters?
- 8
- Help! Where's my UIManagerOn 29 avr, 16:19, Zerex71 <email***@***.com> wrote:
> Greetings,
>
> I spent a frustrating amount of time yesterday trying to figure out
> how to get access to the UIManager class. I am dusting off my Swing
> skills after a number of years and I shouldn't have to be fighting the
> compiler - the Swing paradigm is enough of a challenge as it is.
>
> I am simply trying to set the LAF of my app to use the cool Java metal
> look instead of the default Windows LAF. Here's the offending LOC:
>
> import javax.swing.UIManager;
>
> UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
>
> It throws the four exceptions listed in the Java documentation at Sun,
> leading me to believe it simply does not know where to find the
> UIManager class. I have a normal Java 1.6.0_05 installation.
>
How could it throw the 4 exceptions? Only one exception may be thrown
by a method at runtime, but not 4 at once.
I suspect that the *compiler* refuses to compile your code because the
method *might* throw one of these 4 exceptions, and you don't catch
them or rethrow them.
Since the call should never throw any of the exceptions (the class
name returned by getCrossPlatformLookAndFeelClassName() being of
course perfectly valid for any platform), I suggest you just catch
them and rethrow them as a runtime exception:
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}
catch(ClassNotFoundException e) {
// should never happen
throw new RuntimeException(e);
}
catch(InstantiationException e) {
// should never happen
throw new RuntimeException(e);
}
catch(IllegalAccessException e) {
// should never happen
throw new RuntimeException(e);
}
catch(UnsupportedLookAndFeelException e) {
// should never happen
throw new RuntimeException(e);
}
JB.
- 9
- Reading only numbers from a filehi all
i need a code for reading only numbers from file and not the
letters.
for ex if i have emp name and salary i have to reda only salary.
- 9
- cannot run javac commandHi,
Complete newbie to Java.
I installed JDK 5.0 Update 9 with NetBeans 5.5 and started the tutorial.
No problems with using Netbeans--but can't compile the hello world prog
using command line.
I also want to write the program from scratch using text editor.
That's done but when I go to javac helloworldapp.java as system does
not recognize command "javac"
Error message: Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>javac
'javac' is not recognized as an internal or external command,
operable program or batch file.
C:\>
Here is my Class path: .;C:\Program
Files\Java\jre1.5.0_06\lib\ext\QTJava.zip
QTJAVA C:\Program Files\Java\jre1.5.0_06\lib\ext\QTJava.zip
I'm sure I'm doing something wrong here....
Any help?
Thanks!
--
- 9
- Little problem with ant install taskHi,
I found out that i can use ant for installing my web application.
great, I have copied some code from an example and added the taskdef's
to the top of my build.xml.
Then I copied the catalina-ant.jar into my java classpath.
But when I run it, I get :
"A class needed by class org.apache.catalina.ant.InstallTask cannot be
found: org/apache/tools/ant/Task"
I looked into the catalina-ant.jar and could not find a Task class
indeed, but then, where is it...?
Taskdef:
<taskdef name="install"
classname="org.apache.catalina.ant.InstallTask" />
<taskdef name="remove"
classname="org.apache.catalina.ant.RemoveTask" />
Target:
<target name="install" depends="war" description="Install servlet
on tomcat.kochan.de">
<install url="${tomcat.url}" username="${manager.username}"
password="${manager.password}" path="${app.path}"
war="jar:file:/${war.dir}/${project}.war!/" />
<sleep seconds="2"/>
</target>
Thanks for help!
Werner
- 9
- POSSIBLE SECURITY PROBLEM in Java 5!This happened accidentally, but an attacker might use this
intentionally in a hostile applet to perpetrate a denial of service
attack.
I had a Java app compile and run that generated ~200 threads accessing
the network. It suddenly stopped functioning; it hadn't hung -- the UI
still worked -- but the network activity dropped to zero and it
wouldn't do anything. (Picture a Web browser that works, except every
attempt to go to a page produces a timeout or the browser just spins.
Sort of like that: the UI is working but the backend isn't.)
Naturally, suspecting a bug, I exited and went to rerun the app, this
time attaching a debugger process. Failed. Eclipse showed "Launching
(83%)..." and stuck there. Details showed "searching for free socket"
or some such.
At this point I discovered that almost every other network using app on
the system had locked up. Shareaza, MSN messenger, etc. -- Firefox was
the only survivor, and it would not function (see above description of
semi-functional Web browser; this was Firefox after the accident).
Task Manager showed two Java tasks, one with over 100 threads;
presumably the app that was supposed to have exited. I repeatedly
attacked it with "End Process" and "End Process Tree"; no effect.
Eclipse, when exited, likewise remained as a headless zombie: no
visible UI but still an Eclipse process and a Java task with a couple
of threads. Neither could be killed.
After over half an hour, none of the tasks had exited that had been
told in various increasingly imperative ways to terminate, and the
network remained unusable. I concluded I had to reboot.
To top it off, a clean reboot wasn't possible -- the system would close
a couple apps then just sit there. I had to power-cycle the fucking
box! This on an NT kernel OS and with the trigger being Java, the
paragon of security and non-crashingness? What the fuck?!
Now I've lost all my open Explorer folders and various other
inconveniences can all be laid at the doorstep of ... whatever the fuck
it was that happened.
Can anyone explain this event? Opening a lot of network connections
shouldn't be a problem on XP, and it sure as hell shouldn't render the
system unusable to the point of forcing a cold boot. Even if the Java
app ate all the free network sockets, it should have been terminatable,
and killing it should have released the sockets. Even terminating other
tasks (such as the nonresponsive Shareaza) that used the network didn't
free any up (Shareaza, when end-tasked, disappeared promptly from all
task and process lists, but Firefox didn't magically start working
again).
Annoyingly, the system help also stopped working(!); I was desperate
enough to actually resort to Help and Support Center to find info on
terminating processes and/or freeing sockets, given that the usual
first-resort, Google, was rendered unavailable by the problem.
This Should Not Have Happened.
We have at least 3 separate problems:
* Java can do things that DoS a Win32 box, without doing anything but
open sockets.
Applets can open sockets (though only back to the originating site);
Win32 boxen are
extremely commonplace. You do the math.
* Windows XP SP2, with all the latest updates (including and especially
security updates),
allows a single app to hog all the network sockets, and apps that
want a socket but
can't get one seem usually to hang rather than gracefully report an
error condition to the
user.
* And it does not seem to properly "terminate with prejudice" an
unresponsive process or
free up resources one had when it does terminate it successfully. Is
there no equivalent of
"kill -9", via Task Manager or otherwise, even when you're logged on
as administrator?
It looks like some problems (can't kill processes, processes can kill
parts of the system's overall functionality, killed tasks don't always
have their resources released by the OS) from the bad old days of
Windows 3.1 are still present and accounted for...
Win32 SP2 with all security fixes;
JDK/JRE 1.5.0_06 (latest, as of a couple weeks ago anyway)
- 9
- KeyRelease Event affects next Internal FrameHi,
I am working on an MDI application using JInternalFrames. I have
forms to fill that have the 'Next', 'Back' and 'Cancel' buttons. I am
assigning key presses (Enter, Alt+left and Esc respectively) through
KeyRelease event. In addition, the 'Next' button is assigned as the
default button using
this.getRootPane().setDefaultButton(btnOK). However, I find that when
I run the program and press the Enter key, after accepting the enter
and processing the button action, it loads the next JInternalFrame and
appears to call the KeyRelease event for this form too. Since I have
entries that must be filled, this raises errors that entries are not
filled.
Can anyone tell me what I am doing wrong.
Thanks in advance,
Arun Kumar Srinivasan
- 10
- XML Validation with JavaHi
For several days I've been trying to validate a very simple XML-Document
against an XML Schema - so far without success. I've tried several
approaches, using libraries like Xerces, JAXP and an Oracle-library, but
none of those worked the way for example XML Spy works.
Here is my Schema:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="root"/>
</xsd:schema>
This is the (invalid) XML-File that references the schema: <?xml
version="1.0" encoding="UTF-8"?> <root
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='test.xsd'> <a></a> </root>
This is my first try to validate the Document against the schema:
try { DOMParser parser = new DOMParser();
parser.setFeature("http://xml.org/sax/features/validation",true);
parser.setFeature("http://apache.org/xml/features/validation/schema",true);
parser.setFeature("http://apache.org/xml/features/validation/schema-full-che
cking",true); parser.parse("C:\\test.xml"); }
catch(Exception ex) { ex.printStackTrace(); }
This runs without problems, however, it doesn't report a validation-error.
My second try:
try { SAXParserFactory parserFct =
SAXParserFactory.newInstance(); parserFct.setValidating(true);
parserFct.setFeature("http://xml.org/sax/features/validation", true);
parserFct.setFeature("http://apache.org/xml/features/validation/schema",
true);
parserFct.setFeature("http://apache.org/xml/features/validation/schema-full-
checking",true); javax.xml.parsers.SAXParser parser =
parserFct.newSAXParser(); parser.parse("C:\\test.xml", new
MyHandlerBase()); } catch(Exception ex)
{ ex.printStackTrace(); }
This is the Errorhandler I used:
class MeinErrorHandler implements ErrorHandler{ boolean b = false;
public void warning(SAXParseException e) throws SAXException {
System.out.println("WARNUNG: " + e); b = true; } public void
error(SAXParseException e) throws SAXException {
System.out.println("FEHLER: " + e); b = true; } public void
fatalError(SAXParseException e) throws SAXException {
System.out.println("LEIDER, LEIDER, AUS: " + e); } public boolean
warninghappened(){ return b; }}
Again, no validation-error.
My third try:
InputSource is = null; DOMParser parser = new DOMParser();
Document doc = null; try {
parser.setFeature("http://xml.org/sax/features/validation",true);
parser.setFeature("http://apache.org/xml/features/validation/schema",true);
parser.setFeature("http://apache.org/xml/features/validation/schema-full-che
cking",true);
parser.setProperty("http://apache.org/xml/properties/schema/external-noNames
paceSchemaLocation", "C:\\test.xsd" ); is = new
InputSource(new FileReader("C:\\test.xml"));
parser.parse(is); } catch(Exception ex)
{ ex.printStackTrace(); }
Again, no validation-error.
My fourth try involved the oracle.xml.parser.schema and
oracle.xml.parser.v2-packages.
Here is the code:
public void process(String xsdURI, String xmlURI) throws Exception
{
XSDBuilder builder = new XSDBuilder();
URL url = createURL(xsdURI);
// Build XML Schema Object
XMLSchema schemadoc = (XMLSchema) builder.build(url);
DOMParser dp = new DOMParser();
url = createURL(xmlURI);
// Set Schema Object for Validation
dp.setXMLSchema(schemadoc);
dp.setValidationMode(XMLParser.SCHEMA_VALIDATION);
dp.setPreserveWhitespace(true);
dp.setErrorStream(System.out);
try
{
System.out.println("Parsing " + xmlURI);
dp.parse(url);
System.out.println("The input file <" + xmlURI + "> parsed
without errors");
}
catch (XMLParseException pe)
{
System.out.println("Parser Exception: " + pe.getMessage());
}
catch (Exception e)
{
System.out.println("NonParserException: " + e.getMessage());
}
}
This worked fine with the test.xml-Document, however, when I tried to
validate a more complex document which used keys and key-references, it
couldn't validate the Document although XML-Spy had no problem with it.
Am I missing something here? Does anybody know those problems and has a
solution for it, or perhaps a sample-code that works? Any help would be
greatly appreciated.
Thanks in advance
Mathias Winklhofer
- 10
- OutOfMemoryError problemHi,
I am a user of cruisecontrol ( continuous integration server). As long
as I have used it I have had problems with
java.lang.OutOfMemoryError's. I have gotten numerous ideas on how to
handle it. Some
resonable and some more unrealistic. However lately I dicided that I
need to dig deeper into this.
I use two ways to perform build and test. Both ways use the same 'ant'
and the same 'build file'.
The difference is in how the build is triggered.
Shell script
=========
Here I use a shell script to start ant.
java -Xms512M -Xmx756M -classpath .......
Cruisecontrol
==========
Here I start cruisecontrol ( a java program) that starts ant.
I set Xms and Xmx for cruisecontrol as well as ant.
When I execute the shell script the 'junit' and 'junitreport' tasks
execute nicely.
On the other hand when I execute 'cruisecontrol' I get a
java.lang.OutOfMemoryError when I execute the 'junit-report'.
Trace:
--------
BUILD FAILED
java.lang.OutOfMemoryError
at
org.apache.tools.ant.Project.executeSortedTargets(Project.java:1225)
at
org.apache.tools.ant.Project.executeTarget(Project.java:1185)
at
org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecut
or.java:40)
at
org.apache.tools.ant.Project.executeTargets(Project.java:1068)
at org.apache.tools.ant.Main.runBuild(Main.java:668)
at org.apache.tools.ant.Main.startAnt(Main.java:187)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67)
Caused by: java.lang.OutOfMemoryError
--- Nested Exception ---
java.lang.OutOfMemoryError
I did some investigation in ant ( source code ) and found out the each
junit test suite result ( xml-file) is merged into one big xml file.
There are two steps in the code. Step 1 works ok! Step 2 is failing
siince the big merged file is not complete. Could it be something with
the jvm?
All hints are welcome.
cheers,
//mikael
Step 1 - creating the dom document
-------------------------------------------
protected Element createDocument() {
// create the dom tree
DocumentBuilder builder = getDocumentBuilder();
Document doc = builder.newDocument();
Element rootElement = doc.createElement(TESTSUITES);
doc.appendChild(rootElement);
generatedId = 0;
// get all files and add them to the document
File[] files = getFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
try {
log("Parsing file: '" + file + "'",
Project.MSG_VERBOSE);
if(file.length()>0) {
Document testsuiteDoc
=
builder.parse(FileUtils.getFileUtils().toURI(files[i].getAbsolutePath()));
Element elem = testsuiteDoc.getDocumentElement();
// make sure that this is REALLY a testsuite.
if (TESTSUITE.equals(elem.getNodeName())) {
addTestSuite(rootElement, elem);
generatedId++;
} else {
//wrong root element name
// issue a warning.
log("the file " + file
+ WARNING_INVALID_ROOT_ELEMENT,
Project.MSG_WARN);
}
} else {
log("the file " + file
+ WARNING_EMPTY_FILE,
Project.MSG_WARN);
}
} catch (SAXException e) {
// a testcase might have failed and write a zero-length
document,
// It has already failed, but hey.... mm. just put a
warning
log("The file " + file + WARNING_IS_POSSIBLY_CORRUPTED,
Project.MSG_WARN);
log(StringUtils.getStackTrace(e), Project.MSG_DEBUG);
} catch (IOException e) {
log("Error while accessing file " + file + ": "
+ e.getMessage(), Project.MSG_ERR);
}
}
return rootElement;
}
Step 2 - write the DOM Tree to file
----------------------------------------
protected void writeDOMTree(Document doc, File file) throws IOException
{
OutputStream out = null;
PrintWriter wri = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
wri = new PrintWriter(new OutputStreamWriter(out, "UTF8"));
wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
(new DOMElementWriter()).write(doc.getDocumentElement(),
wri, 0, " ");
wri.flush();
// writers do not throw exceptions, so check for them.
if (wri.checkError()) {
throw new IOException("Error while writing DOM
content");
}
} finally {
FileUtils.close(wri);
FileUtils.close(out);
}
}
- 11
- Registering Connector/J driverHi. I have
- mySQL 1.4
- Connector/J 3.0.15
I want to use Java to query mySQL database via Connector/J.
Connector/J documentation at
http://dev.mysql.com/doc/connector/j/en/index.html instructs to
compile and run the following Java code to register the Connector/J
driver:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
}
// Error:
// SQLJConnectorRegister1failed.java:8:
// class LoadDriver is public, should be declared in a file named
// LoadDriver.java
Where should I have this LoadDriver class/java file? It doesn't come
with any of the packages I have (java.sql.* or connector/J driver
classes). Hence I can't "supply a class that implements Driver
interface" which would I gather register the driver. I have set the
classpath to the driver's jar, so it should find that class.
*
And then SQL queries would be possible. That would be an achievement
as such, never loaded/registered a driver in my life, or programmed
much anyway.
Appreciate any help over this.
Best, Harri S
Finland
language technologist
- 11
- question about RMIHi,
What is the best data type to transfer a resultset from server to
client using RMI ?
Thanks
- 11
- Searching ProgramI have to create a "Search Engine Program" in Java. I'm using Java /
Struts and XML.
Thanking you
- 12
- what's wrong with my component? i make a new component which is a dragable icon here is my piece of
code
//class: DragAbleComponent.the father of my component
import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.accessibility.Accessible;
import javax.swing.JComponent;
public abstract class DragAbleComponent extends JComponent implements
MouseListener,
FocusListener, Accessible ,MouseMotionListener{
private int X;
private int Y;
/**
*
*/
private static final long serialVersionUID = 1L;
public void mouseClicked(MouseEvent e) {
this.requestFocusInWindow();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void focusGained(FocusEvent e) {
this.repaint();}
public void focusLost(FocusEvent e) {
this.repaint();}
protected abstract void paintComponent(Graphics graphics);
public int getX() {
return X;
}
public void setX(int x) {
X = x;
}
public int getY() {
return Y;
}
public void setY(int y) {
Y = y;
}
}
//class:DragableIcon the component
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.TransferHandler;
public class DragableIcon extends DragAbleComponent {
private Image image;
private MouseEvent firstMouseEvent = null;
private static boolean installKeyBordMapings = true;
/**
*
*/
private static final long serialVersionUID = 1L;
public DragableIcon(Image image) {
super();
this.image = image;
this.setFocusable(true);
this.addMouseListener(this);
this.addFocusListener(this);
this.addMouseMotionListener(this);
this.initKeyBordMaping();
}
private void initKeyBordMaping(){
if (installKeyBordMapings) {
InputMap imap = this.getInputMap();
// imap.put(KeyStroke.getKeyStroke("ctrl X"),
//
TransferHandler.getCutAction().getValue(Action.NAME));
imap.put(KeyStroke.getKeyStroke("ctrl C"),
TransferHandler.getCopyAction().getValue(Action.NAME));
imap.put(KeyStroke.getKeyStroke("ctrl V"),
TransferHandler.getPasteAction().getValue(Action.NAME));
}
ActionMap map = this.getActionMap();
//
map.put(TransferHandler.getCutAction().getValue(Action.NAME),
// TransferHandler.getCutAction());
map.put(TransferHandler.getCopyAction().getValue(Action.NAME),
TransferHandler.getCopyAction());
map.put(TransferHandler.getPasteAction().getValue(Action.NAME),
TransferHandler.getPasteAction());
}
@Override
protected void paintComponent(Graphics graphics) {
Graphics g = graphics.create();
//Draw in our entire space, even if isOpaque is false.
g.setColor(Color.WHITE);
g.fillRect(0, 0, image == null ? 125 : image.getWidth(this),
image == null ? 125 : image.getHeight(this));
if (image != null) {
//Draw image at its natural size of 125x125.
g.drawImage(image, 0, 0, this);
}
//Add a border, red if picture currently has focus
if (isFocusOwner()) {
g.setColor(Color.RED);
} else {
g.setColor(Color.BLACK);
}
g.drawRect(0, 0, image == null ? 125 : image.getWidth(this),
image == null ? 125 : image.getHeight(this));
// g.drawImage(image, 0, 0, this);
g.dispose();
}
public void mouseDragged(MouseEvent e) {
//Don't bother to drag if the component displays no image.
if (image == null) return;
if (firstMouseEvent != null) {
e.consume();
//If they are holding down the control key, COPY rather
than MOVE
int ctrlMask = InputEvent.CTRL_DOWN_MASK;
int action = ((e.getModifiersEx() & ctrlMask) == ctrlMask)
?
TransferHandler.COPY : TransferHandler.MOVE;
int dx = Math.abs(e.getX() - firstMouseEvent.getX());
int dy = Math.abs(e.getY() - firstMouseEvent.getY());
//Arbitrarily define a 5-pixel shift as the
//official beginning of a drag.
if (dx > 5 || dy > 5) {
//This is a drag, not a click.
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
//Tell the transfer handler to initiate the drag.
handler.exportAsDrag(c, firstMouseEvent, action);
firstMouseEvent = null;
}
}
}
public void mouseMoved(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
//Don't bother to drag if there is no image.
if (image == null) return;
firstMouseEvent = e;
e.consume();
}
public void mouseReleased(MouseEvent e) {
firstMouseEvent = null;
}
public static boolean isInstallKeyBordMapings() {
return installKeyBordMapings;
}
public static void setInstallKeyBordMapings(boolean
installKeyBordMapings) {
DragableIcon.installKeyBordMapings = installKeyBordMapings;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
}
//and here is my pane
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import cn.com.ynld.bms.applet.gui.handler.IconTransferHandler;
import cn.com.ynld.bms.applet.service.TransfAble;
import cn.com.ynld.bms.applet.service.UpdateAble;
public class ElectronicPane extends JPanel
implements ItemListener,UpdateAble{
private UpdateAble updateAble = null;
private ScrollAbleImage image;
private JToolBar toolBar;
private IconTransferHandler handler;
/**
*
*/
private static final long serialVersionUID = 1L;
public ElectronicPane(){
super(new BorderLayout());
handler = new IconTransferHandler();
this.creatToolBar();
this.add(this.toolBar);
this.setTransferHandler(handler);
}
public void itemStateChanged(ItemEvent e) {}
public void addTransferAble(String key, TransfAble transferAble) {
// TODO
}
public TransfAble getTransferAble(String key) {
// TODO
return null;
}
public void removeTransferAble(String key) {
this.updateAble.removeTransferAble(key);
}
public void update(UpdateAble updateAble) {
this.updateAble = updateAble;
this.init();
}
private void init(){
this.image = new ScrollAbleImage();
this.image.update(updateAble);
this.add(image,BorderLayout.CENTER);
this.repaint();
//this.image.repaint();
}
private void creatToolBar(){
this.toolBar = new JToolBar();
DragableIcon alarm = new
DragableIcon(createImageIcon("/root/Desktop/drawing/png-0003.png",
"alarm").getImage());
alarm.setTransferHandler(handler);
DragableIcon damage = new
DragableIcon(createImageIcon("/root/Desktop/drawing/png-0007.png",
"device").getImage());
alarm.setTransferHandler(handler);
this.toolBar.add(alarm);
this.toolBar.addSeparator();
this.toolBar.add(damage);
this.toolBar.setFloatable(false);
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path,
String description) {
// java.net.URL imageURL =
DragPictureDemo.class.getResource(path);
if (path == null) {
System.err.println("Resource not found: "
+ path);
return null;
} else {
return new ImageIcon(path, description);
}
}
}
the problem is i add DragableIcons to my toolbar but only the first
icon can be seen!!!!
what's wrong
thanks for any help!
- 12
- bypassing IISHi
We have an architecture where users log in to their
"windows" pcs using Microsoft Active Directory
and requests are then sent as follows:
client -> IIS -> Tomcat
An isapi redirector resides at IIS which forwards the request to
Tomcat.
isapi redirect would appear to populate the HTTP header with
the user's credentials.
My question is: how can we avoid the overhead of IIS
and send requests directly to Tomcat for authentication against the
ldap server as before.
(The issue I see is how to populate the HTTP header with the
user details?)
Regards
- 14
- ports/java cleanup/re-org (was: freebsd eclipse plugins & mailingOn Aug 25, 2005, at 10:00 PM, Greg Lewis wrote:
> and the fact that the devel category is already huge.
Devel is ripe for splitting ala the x11-* categories. And I suspect a
not insubstantial portion of devel could be moved elsewhere (e.g.
devel/mime -> mail/mime).
And this whole thread should be moved to the ports list. Please note
the reply-to.
--lyndon
_______________________________________________
email***@***.com mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-java
To unsubscribe, send any mail to "email***@***.com"
|
| Author |
Message |
wnstnsmith

|
Posted: 2004-2-12 3:43:00 |
Top |
java-programmer, stringtokenizer that traps ASCII linebreaks
Dear all,
How do i define a stringtokenizer that traps chr13, chr10 combinations?
tia
WS
|
| |
|
| |
 |
Adam Jenkins

|
Posted: 2004-2-12 4:00:00 |
Top |
java-programmer >> stringtokenizer that traps ASCII linebreaks
email***@***.com wrote:
> Dear all,
>
> How do i define a stringtokenizer that traps chr13, chr10 combinations?
>
> tia
> WS
You can't exactly do this with StringTokenizer, since it doesn't support
splitting on specific multi-char patterns. You could say
StringTokenizer stok = new StringTokenizer(string, "\r\n");
which would split "string" at each \013\010, but it would also split on
just a \013 or \010 or \013\013, etc. If you really need to split at
each \r\n, then you can use String.split, as in
String[] tokens = string.split("\r\n");
Adam
|
| |
|
| |
 |
wnstnsmith

|
Posted: 2004-2-12 6:04:00 |
Top |
java-programmer >> stringtokenizer that traps ASCII linebreaks
Thanks very much indeed, that does it. Guess my mistake was to have the
tokenizer look for '\r' + '\n' + "blablabla", instead of "\r\n". You can
imagine that had me wondering...
WS
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- problems with getting blob from databaseI`m writing from file to blob. Than I need to get blob content again
and write it to file. When I open this file, I see the wrong symbols.
Can anybody help me?
Here is my code:
////////////////////////////
to update file content
///////////////////////////
private void updateFileContent(File serverFile, java.io.File
clientContentFile) throws MainException
{
PreparedStatement preparedStatement = null;
try
{
connection = connect();
String query = "update panta_file_substance\n" +
"set content = ?\n" +
"where\n" +
" file_id = ?"
preparedStatement = getPreparedStatement
(query, connection);
int fileLenght = (int) clientContentFile.length();
InputStream is = new FileInputStream(clientContentFile);
preparedStatement.setBinaryStream(1, is, fileLenght);
preparedStatement.setLong( 2,
serverFile.getId().longValue() );
int result = preparedStatement.executeUpdate();
is.close();
}
catch (SQLException e)
{ throw new MainException(e.getMessage(), e); }
catch (FileNotFoundException e)
{ throw new MainException(e.getMessage(), e); }
catch (IOException e)
{ throw new MainException(e.getMessage(), e); }
finally
{
disconnect(null, preparedStatement, null);
}
}
//////////////////////////////////////////////////////////////////////////
to get file
/////////////////////////////////////////////////////////////////////////
public static void getFile(Connection connection) throws
SQLException
{
String query = "select \n" +
" panta_file_substance.content \n" +
"from \n" +
" panta_file_substance\n" +
"where \n" +
" file_id=?";
PreparedStatement preparedStatement = connection.
prepareStatement(ServerSQLProjectDAO.getFileContent());
preparedStatement.setLong(1, 7801295236381635588l);
ResultSet resultSet = preparedStatement.executeQuery();
Blob content = null;
if (resultSet.next())
{
content = (Blob) resultSet.getBlob("CONTENT");
}
java.io.File contentffFile = new java.io.File("C:\\Temp\\new");
try
{
OutputStream os = new FileOutputStream(contentffFile);
int bufferSize = 2048;
byte[] array = new byte[bufferSize];
BufferedOutputStream bos = new BufferedOutputStream(os,
bufferSize);
InputStream is = content.getBinaryStream();
BufferedInputStream bis = new BufferedInputStream(is);
int nBytes;
while ((nBytes = bis.read(array)) != -1)
bos.write(array, 0, nBytes);
bos.close();
bis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
- 2
- Server-side tools surveyI'm currently working with JBoss/Tomcat, PostgreSQL, NetBeans, Struts,
XDoclet, Ant, JUnit, JUnitEE...and a few things I've probably forgotten
to mention.
What tools do *you* consider necessary for web application development?
--
Phillip Mills
Multi-platform software development
(416) 224-0714
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 100,000 Newsgroups - 19 Different Servers! =-----
- 3
- Problems with tomcatHi guys, I have some problems, I'm trying to run tomcat in windows
2000 pro and actually it runs but when I use the browser http://localhost:
doesn't work, What should be the problem? I've changed the port to 80
but still having the same problem. Thx in advance
- 4
- use my JSP custom tag on click of buttonI have written a custom tag in a jsp
<test:attribs attribNames="<%=aenum%>">
<li> <b><%=aenum.nextElement()%></b>
</test:attribs>
It lists the request attributes.
Now i want the to list the same on click of a button or say on clicking
on an image( or consider for some specified event of a HTML component)
Can i use the custom tag for the same and if yes how?
Regards,
- 5
- As an added bonus, cacti come in unique shapes and sizes, and many even show off colorful blooms.Those unevolved men truly irritate me.
Having twice defeated the counterrevolution, the revolution is faced
with a new and furious offensive. Perhaps unbeknownst to him, the stance
he has adopted seems to reinforce the negative image of Islam, that of
rabid militancy against all other faiths. This week, I have some great
ideas on how to make your own plant markers from common household items.
If you haven't noticed, a lot of garden centers and nurseries are
running clearance sales on plants and other garden supplies.
ss
*** CNHC *** CNHC *** CNHC ***
Trade Date: Friday, November 24, 2006
Company: China Health Management Corp.
Symbol: CNHC
Price: $1.34
Target: $10
CNHC BREAKING NEWS:
China Health Management Corp. Announces the Hospital's Setup Proposal
Received Additional Approval from Kunming City, Yunnan, China
CNHC IS BOUND TO BLOW UP! THIS AMAZING NEWS ALONG WITH HEAVY PR PROMOS
ARE DRIVING IT NUTS! WATCH CNHC GO OFF THE CHAIN ON FRIDAY NOV 24!
ss
Does the mere mention of these ailments make your skin itch? His efforts
were all the more heroic for being nonviolent. As an added bonus, cacti
come in unique shapes and sizes, and many even show off colorful blooms.
That's why I was so thrilled when I came across this tip that makes slow
watering my plants easier than ever. Zakaria might not be enhancing the
global image of Islam in the manner majority world Muslims would prefer:
an image of peace.
Sometimes they were sweet, sometimes they were bitter, and they were
always difficult to harvest after a snowfall.
But US scientists report they have now isolated these cell-like
structures in tissue from diseased human arteries.
Well, don't head to your local drugstore for relief - go to your garden.
Find out how to make a charming and unique windchime that will make your
garden a haven for your senses.
His efforts were all the more heroic for being nonviolent. The article
published in The Toronto Star describes the harsh reality that millions
of poor are facing in India.
Zakaria might not be enhancing the global image of Islam in the manner
majority world Muslims would prefer: an image of peace.
His efforts were all the more heroic for being nonviolent.
Daffodils, also known as jonquils or narcissus, are my favorites.
Daffodils, also known as jonquils or narcissus, are my favorites.
The wives or kiths and kin of the Ministers or MPs, her beloved
sycophants are flocking in her or the BNP offices may be at Hawa Bhaban
also, to try their luck.
Click on the link below for more poinsettia information. Does the mere
mention of these ailments make your skin itch? Click on the link below
to find a great way to reuse your tree in the garden.
If the allegations in this article are true, things look bleak for peace
in the Middle-East.
That's why I was so thrilled when I came across this tip that makes slow
watering my plants easier than ever. So the Americans are cutting off
money to Chalabi. The moral of the story, according to Aesop: it is
easier to get into the enemys toils than out again. The article
published in The Toronto Star describes the harsh reality that millions
of poor are facing in India. This week I'll show you four simple things
you can add to get your soil started down the road to perfection.
Zakaria might not be enhancing the global image of Islam in the manner
majority world Muslims would prefer: an image of peace.
I beg your Majesty's pardon, replied the fox, but I noticed the track of
the animals that have already come to you, and while I see many hoof
marks going in, I see none coming out. How come they were so gullible
that they had overlooked his scam filled past and now all of a sudden
the good man is becoming an evil man? If the allegations in this article
are true, things look bleak for peace in the Middle-East. Here are four
simple things that can help you keep your garden balanced visually. But
a little basic know-how can make the job a breeze.
--
To UNSUBSCRIBE, email to email***@***.com
with a subject of "unsubscribe". Trouble? Contact email***@***.com
- 6
- best approach for transaprent boxes
I'm hoping for some guidance on the best way to do the following, since I am fairly new to the Java language.
I am building an applet that uses a canvas to show a map (awt only - no swing). I want to display semi-transaparent boxes over the top of the map to show things like status, or have options, and the boxes should be able to process mouse events. The canvas is using a double-buffered strategy and uses Graphics2D.
My first thought was to simply design lightweight components - but they require a container, which the Canvas is not.
So then I thought I would extend the Canvas class to work with another completely custom "decorator" class that would be able to buffer the area of the canvas it covers for quick updating if it changes, and draw it's own info on top - but I just can't figure out how to grab a part of the rendered parent canvas to store offscreen and paint again later.
So my question is: Is the second method a good way to go about this, or is there a better "Java" way of doing this (I'm still probably thinking in a Delphi mindset)? And if the second way is ok, then how do I buffer just part of the parent canvas?
Phil.
- 7
- How to stop output to stdoutHi,
I am using RXTXcomm to communicate with the serial interface. My
programs output this everytime the RXTXcomm library is loaded:
Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version = RXTX-2.1-7
I don't like this output anytime the program runs. I tried to redirect
System.out but it didn't work. Does anybody know how to put RXTXcomm
into "silent mode"?
Thanks, Juergen
- 8
- SourceDataLine ProblemA while back I implemented sound using javax.sound.sampled into my Tandy
Color Computer 2 applet.
The Color Computer had a 6-bit DAC used to generate audio. I basically
take the values written to the DAC and then feed them (although at a
much higher rate) into a SourceDataLine.
The problem is that the sound can crackle or break up depending on the
program emulated. I can prevent this by either feeding the data to the
SorceDataLine at a higher rate or by reducing the sample rate on the
AudioFormat. Both of these methods fix the breakups but then the pitch
drops enough that the sound is no longer accurately emulated.
I just don't understand the workings of javax.sound.sampled well enough
to figure out a workaround for this problem - it seems like it should be
possible.
Any ideas?
Brad
Mocha - The Tandy Color Computer 2 Applet
http://members.cox.net/javacoco/
- 9
- Open Source Distributive Cache solutionHi,
I am looking for an open source's distributive cache solution. One that
can be used for a clustered weblogic servers environment, the cache has
to be read and write, and the cache itself need to be fail-safe.
Anyone has some recommandations?
Thanks,
Edmond
- 10
- Trying to create a database in a MS Access DB via JDBC drivers. I am trying to create a database in a MS Access DB via JDBC drivers.
I have tried both sun.jdbc.odbc.JdbcOdbcDriver and ids.sql.IDSDriver
From some reason both drivers Exceptions tell me 'Syntax error in
CREATE TABLE statement' even though I am not creating a table, but a
Database
// - - - - - - - - - - - - sun.jdbc.odbc.JdbcOdbc
aSQL=CREATE DATABASE dbtest;
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]
Syntax error in CREATE TABLE statement.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(Unknown
Source)
at JDBCDL00.createCtlg(JDL00.java:200)
at JDL00.main(JDL00.java:505)
// - - - - - - - - - - - - ids.sql
aSQL=CREATE DATABASE dbtest;
java.sql.SQLException: [42000][Microsoft][ODBC Microsoft Access
Driver] Syntax error in CREATE TABLE statement
at ids.sql.IDSSocket.error(IDSSocket.java:374)
at ids.sql.IDSSocket.verify(IDSSocket.java:320)
at ids.sql.IDSStatement.submit(IDSStatement.java:157)
at ids.sql.IDSStatement.execute(IDSStatement.java:479)
at ids.sql.IDSStatement.executeUpdate(IDSStatement.java:270)
at JDBCDL00.createCtlg(JDL00.java:200)
at JDL00.main(JDL00.java:505)
Does it mean MS Access does not have a concept of a BD, since it is
kind of a file base Data Store?
There is also something I don't quite know how to interpret.
When you ask the JdbcOdbc driver for Catalogs it gives you
. . .\Office\Samples\ADDRBOOK
. . .\Office\Samples\CONTACT
. . .\Office\Samples\INVENTRY
. . .\Office\Samples\Northwind
even if you declare the a USer DSN only to
. . .\Office\Samples\Northwind
Experimentally I dropped a copy of
. . .\Office\Samples\Northwind.mdb
in
. . .\IDS\File\examples
and set up a system DSN to got IDSExamples.mdb
However, while query the DBMS for catalogs, I got
. . .\IDS\File\examples\IDSExamples
. . .\IDS\File\examples\Northwind
Does it mean Access considers the folder containing the '.mdb' file
as sort of a 'schema'?
How could u still create a Database using JDBC in a MSAccess DB?
- 11
- Cannot draw on mutable imageHi,
I got a problem with drawing on an image created with the
createImage(int width, int height) method. I use MIDP 1.0 and
everything works fine in the emulator. But when running it on my
T-630, I just get a white image with the defined size. It doesn't
matter what I draw on the Graphics-object, my phone just displays a
white rectangle.
The code should be ok, since it works in the emulator. I also used
several examples from the internet - all with the same result.
Any ideas what might be wrong?
Thanks in advance
Dirk
- 12
- integration with JSTL
Hallo, here is my question. I have a Java API
to access some data (collections and strings).
How do I make sure that my API is such that i can access data trhough
the JSTL?
I want to be able to do things like the following
in my JSPs:
<c:if test="$someobj.property == 'john'">
Hallo John
</c:if>
Thanks
Luca
- 13
- Basic java program structure; Was: Problems with multidimensional arrays and global variables<top posting seemed more appropriate for this post>.
Being a Java newbie and having been struggling with the basic concepts of
the structure of a java program (as well as "static") I would like to say
that this is the best example I have seen so far of the basic form of a java
program. Nice, simple and after reading it I think I finally understand
what is going on. I have read far too many books and examples that seem to
enjoy obfuscating the concept they are trying to explain with way too many
extraneous details.
Thank you.
Don Freeman
If this group has a FAQ I nominate the following for entry:
"Carl" <email***@***.com> wrote in message
news:fS8Pd.3241$email***@***.com...
> In short, static members do not belong to an object. You do not need to
> create an object to access the members. The main() method must be static
> since it will be the first method called and there will not yet have been
> a chance for you to create any objects. IMO, the main method should then
> proceed to operate on OBJECTS, unless you have a good reason for using
> static.
>
> A simple class example would be as follows:
> // code -->
> public class Foo {
>
> // this can be accessed by any of Foo's methods
> private int someVariable;
>
> // This gets called when a new Foo object is created.
> public Foo(){
> // do initial setup
> }
>
> public void runProgram(){
> // start doing your processing
> }
>
> public static void main(String[] args) {
> // process args[]
>
> Foo foo = new Foo(); // create an instance of the Foo class.
> foo.runProgram(); // start running the Foo class.
> }
> }
> // <-- end code
- 14
- Mac version of IE tires to download sounds rather than playing them.
I've done a web site which encorporates javascripted sound behaviors.
On the PC version of Internet Explorer they do what they're supposed
to do. That is, play the sound on both "mouse over" and "mouse up"
events.
On the Macintosh version of IE it triggers off an automatic download
attempt. I have also seen this on some PC's running Netscape, but
rarely.
Opera doesn't even seem to do anything with the sound events on the
Mac. The PC version of Opera seems to work correctly.
So, my question: is there a way to code this using Dreamweaver or
some other authoring program, so it can be controlled on these
different combinations of browsers, and Computer Platforms?
I've found this most frustrating.
Thanks for any help you might give on this.
S.
- 15
- Using a JList with a cell renderer within an applet/cell renderer not workingI have a cell renderer for a JList that is supposed to render the foreground
color in blue, and also insert tabs into the lines. When this code is
changed to run as an application, the cell renderer performs as expected.
When the code is run as an applet, the cell renderer has no impact at all.
Any help would be appreciated.
I am using SDK 1.4.0, Windows XP Professional.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import javax.swing.text.MaskFormatter;
import java.text.ParseException;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.util.StringTokenizer;
public class TempConvert extends JApplet {
public JFormattedTextField low;
public JFormattedTextField high;
public JFormattedTextField incr;
public TempConvert() {
getContentPane().setLayout(new BorderLayout());
createGrid();
setSize(270,400);
}
private void createGrid() {
JPanel panel = new JPanel(new BorderLayout());
// add selection panel
MaskFormatter mf1 = null;
MaskFormatter mf2 = null;
try
{
mf1 = new MaskFormatter("####");
mf1.setPlaceholderCharacter('_');
//mf1.setCommitsOnValidEdit(true);
mf2 = new MaskFormatter("###");
mf2.setPlaceholderCharacter('_');
//mf2.setCommitsOnValidEdit(true);
}
catch (ParseException e){
}
low = new JFormattedTextField(mf1);
low.setFocusLostBehavior(JFormattedTextField.COMMIT);
high = new JFormattedTextField(mf1);
high.setFocusLostBehavior(JFormattedTextField.COMMIT);
incr = new JFormattedTextField(mf2);
incr.setFocusLostBehavior(JFormattedTextField.COMMIT);
JPanel select = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;
addgbc(select, new JLabel("Low Temperature Range . . ."),gbc,0,0);
addgbc(select, low,gbc,1,0);
addgbc(select, new JLabel("High Temperature Range . ."),gbc,0,1);
addgbc(select, high,gbc,1,1);
addgbc(select, new JLabel("Increment Degrees . . . . ."),gbc,0,2);
addgbc(select, incr,gbc,1,2);
panel.add(select, BorderLayout.NORTH);
// add temperature list
final JList list = new JList();
TabListCellRenderer renderer = new TabListCellRenderer();
//renderer.setTabs(new int[] {50,200,300,});
list.setCellRenderer(renderer);
JScrollPane scroller = new JScrollPane();
scroller.getViewport().add(list);
panel.add(scroller, BorderLayout.CENTER);
// add buttons
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
JButton ok = new JButton("OK");
JButton cancel = new JButton("Cancel");
buttons.add(ok);
buttons.add(cancel);
panel.add(buttons, BorderLayout.SOUTH);
getContentPane().add(panel);
//pack();
setVisible(true);
// register action listeners for the buttons
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (verifyData())
{
list.setListData(calculateTemps());
list.revalidate();
list.repaint();
}
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// stop();
// destroy();
}
});
}
private int getIntValue(JFormattedTextField field)
{
try
{
return Integer.parseInt(field.getText().toString().replace('_','
').trim());
}
catch (NumberFormatException e){}
return 0;
}
private boolean verifyData()
{
int lowTemp = getIntValue(low);
int highTemp = getIntValue(high);
int incrTemp = getIntValue(incr);
if (lowTemp < 0)
{
JOptionPane.showMessageDialog(this, "If low temperature is entered, must
be greater than zero");
return false;
}
if (highTemp == 0)
{
JOptionPane.showMessageDialog(this, "High temperature must be entered");
return false;
}
if (highTemp <= lowTemp)
{
JOptionPane.showMessageDialog(this, "High temperature must be greater
than low temperature");
return false;
}
if (incrTemp == 0)
{
JOptionPane.showMessageDialog(this, "Increment degrees must be
entered.");
return false;
}
return true;
}
private void addgbc(Container cont, JComponent comp, GridBagConstraints
gbc, int x, int y) {
gbc.gridx=x; gbc.gridy=y;
cont.add(comp,gbc);
}
private TempData[] calculateTemps() {
int lowTemp = getIntValue(low);
int highTemp = getIntValue(high);
int incrTemp = getIntValue(incr);
int range = highTemp-lowTemp;
TempData[] tempdata = new TempData[range/incrTemp +1];
int j=0;
for (int i=lowTemp; i<=highTemp; i+=incrTemp) {
tempdata[j] = new TempData(i);
j++;
}
return tempdata;
}
public static void main (String[] args) {
new TempConvert();
}
public class TempData {
int fahrenheit;
int celsius;
public TempData(int fahrenheit) {
this.fahrenheit = fahrenheit;
calculateTemp();
}
private void calculateTemp() {
double temp = 5/9 * (fahrenheit-32);
celsius = (int)temp;
}
public String toString() {
return fahrenheit + "\t" + celsius;
}
}
}
class TabListCellRenderer
extends JLabel
implements ListCellRenderer {
protected static Border m_noFocusBorder;
protected FontMetrics m_fm = null;
protected Insets m_insets = new Insets(0, 0, 0, 0);
protected int m_defaultTab = 50;
protected int[] m_tabs = null;
public TabListCellRenderer() {
m_noFocusBorder = new EmptyBorder(1, 1, 1, 1);
setOpaque(true);
setBorder(m_noFocusBorder);
}
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
setText(value.toString());
System.out.println("getText = " + getText());
setBackground(isSelected ? list.getSelectionBackground() :
list.getBackground());
//setForeground(isSelected ? list.getSelectionForeground() :
list.getForeground());
setForeground(Color.blue);
//setBackground(Color.blue);
setFont(list.getFont());
setBorder((cellHasFocus) ?
UIManager.getBorder("List.focusCellHighlightBorder") : m_noFocusBorder);
return this;
}
public void setDefaultTab(int defaultTab) {
m_defaultTab = defaultTab;
}
public int getDefaultTab() {
return m_defaultTab;
}
public void setTabs(int[] tabs) {
m_tabs = tabs;
}
public int[] getTabs() {
return m_tabs;
}
public int getTab(int index) {
if (m_tabs == null)
return m_defaultTab*index;
int len = m_tabs.length;
if (index>=0 && index<len)
return m_tabs[index];
return m_tabs[len-1] + m_defaultTab*(index-len+1);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Color colorRetainer = g.getColor();
m_fm = g.getFontMetrics();
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
getBorder().paintBorder(this, g, 0, 0, getWidth(), getHeight());
g.setColor(getForeground());
g.setFont(getFont());
m_insets = getInsets();
int x = m_insets.left;
int y = m_insets.top + m_fm.getAscent();
StringTokenizer st = new StringTokenizer(getText(), "\t");
while (st.hasMoreTokens()) {
String sNext = st.nextToken();
System.out.println("next token = " + sNext);
g.drawString(sNext, x, y);
x += m_fm.stringWidth(sNext);
if (!st.hasMoreTokens())
break;
int index = 0;
while (x >= getTab(index))
index++;
x = getTab(index);
}
g.setColor(colorRetainer);
}
}
|
|
|