How do I create an image (GIF, JPEG, etc.) on the fly from a servlet?
To create an image or do image processing from Java, there are several
packages and classes available. See the Purple Servlet References for a list.
Once you have an image file in your servlet, you have two choices:
(CookieDetector (http://www.purpletech.com/code/CookieDetector.html)
has an example, with source code, of sending a redirect.)
Location: http://www.jguru.com/faq/view.jsp?EID=159
Created: Sep 3, 1999
Modified: 2001-12-16 12:47:29.26
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
(Note that in some servlet engine
setups, the servlet directory is not accessible by the web server,
only by the servlet engine, which means you won't be able to access it
through an http:// URL.) You can either send an IMG tag in
the HTML your servlet is outputting, or send an HTTP redirect to make
the browser download the image directly (as its own
page).
Pro: the image can be cached by the browser, and successive
requests don't need to execute the servlet again, reducing server
load.
Con: the image files will never be deleted from your
disk, so you'll either have to write a script to periodically clean
out the images directory, or go in and delete them by hand. (Or buy a
bigger hard disk :-) ).
Focus on Java (http://java.miningco.com/library/weekly/aa090299.htm) has a brief article describing the use of the Java 2 JPEGCodec class.
You can also use JIMI to read and write images in many formats, including GIF, JPEG, TIFF (TIF), PNG, PICT, Photoshop, BMP, Targa, ICO, CUR, Sunraster, XBM, XPM, and PCX.See also:
| Remember the IMG tag
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 16, 2001 Remember, to display an image inside an HTML page, you have to use the IMG tag, like <IMG src="/mywebapp/myimageservlet">Just writing the data to the servlet response isn't going to work, unless you're writing an entire image/gif or image/jpeg document. |
| code to write imgs on the fly from a jsp
Author: kamalesh kam (http://www.jguru.com/guru/viewbio.jsp?EID=1158032), Mar 28, 2004 <%@ page import="javax.servlet.http.*"%> <%@ page import="java.io.*"%> <%@ page import="java.awt.*"%> <%@ page import="java.util.Random"%> <%@ page import="java.awt.Color"%> <%@ page import="java.awt.image.*"%> <%@ page import="Acme.JPM.Encoders.GifEncoder"%> <%@ page import="com.sun.image.codec.jpeg.JPEGCodec"%> <%@ page import="com.sun.image.codec.jpeg.JPEGImageEncoder"%> <%BufferedImage image= new BufferedImage(500,500, BufferedImage.TYPE_INT_RGB); Graphics g=image.getGraphics(); Random r=new Random(); g.fillRect(r,r,r,r); FileOutputStream fos=new FileOutputStream("c:/ewr.jpg"); JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(fos); encoder.encode(image); %> ![]() |
| Jake stone adds source code
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 16, 2001
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
File f = new File(System.getProperty("user.home")+"\\zoewrap.jpg");
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new FileInputStream(f));
BufferedImage image =decoder.decodeAsBufferedImage() ;
// Send back image
ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(image);
}
|
| Re: Jake stone adds source code
Author: Ping Long (http://www.jguru.com/guru/viewbio.jsp?EID=799119), May 15, 2002 Alex, I got cached image problem in my application. I need to update image without changing name. Your idea may fix my problem. I would like to know when I can get those classes such as: JPEGImageDecode, JPEGImageEncoder, JPEGCodec. Thanks in advance. PL |
| Re[2]: Jake stone adds source code
Author: jpeg jones (http://www.jguru.com/guru/viewbio.jsp?EID=885462), May 20, 2002 These classes are in the com.sun.image.codec.jpeg. package; they should be in your jdk 1.3 (or whatever) src.jar |
| Re[3]: Jake stone adds source code
Author: Ohad Kravchick (http://www.jguru.com/guru/viewbio.jsp?EID=1025885), Nov 14, 2002 I have a problem with that. i made a painter applet, and i need to write the result of the painting to the server (asp). i've created an asp page which gets posted data, from the applet (ACME.GifEncoder), and it still doesnt work. will you please help me, i'm stuck badly. go and take a look at the painter: my Painter send me email for response..... |
| Regarding the cache problem
Author: Thomas Isaksen (http://www.jguru.com/guru/viewbio.jsp?EID=1132932), Dec 9, 2003 I think I had the same problem when trying to display an image fetched from a servlet talking to the db. I simply added another parameter to the url which caused the cache problem to go away: First I had: <img src="/servlet/ImageServlet?id=n"/> which didn't work, it was cached and showed the same image all the time. So I put this in: <img src="/servlet/ImageServlet?id=n&rnd=some_random_number"/> and the image caching problem is gone :-) "some_random_number" can be as simple as putting the value of System.currentTimeMillis() or using java.util.Random to come up with a value. Hope this helps. |
| Re: Jake stone adds source code
Author: dalal salih (http://www.jguru.com/guru/viewbio.jsp?EID=1535889), Feb 23, 2010 package |
| Convert image from one format to another on the fly. JAI versus ImageIO.
Author: Master Wong (http://www.jguru.com/guru/viewbio.jsp?EID=1285672), Feb 24, 2006 You can use either Java Advance Imaging JAI (com.sun.media.jai) or Java ImageIO (javax.imageio). <% for (int i=0;i<writerFormatNames.length;i++) { Here are some great references:
Hope this help. Cheers, |
| Re: Convert image from one format to another on the fly. JAI versus ImageIO.
Author: Master Wong (http://www.jguru.com/guru/viewbio.jsp?EID=1285672), Mar 15, 2006 CORRECTION: |
| Re: Convert image from one format to another on the fly. JAI versus ImageIO.
Author: KIRAN REDDY (http://www.jguru.com/guru/viewbio.jsp?EID=1287798), Apr 12, 2006 i could not convert the tiff image to jpeg can anyone help me with the example code.if possible please send me the code. i am using this application in jsp. server tomcat4 java tool kit-jdk1.4 |
| Re[2]: Convert image from one format to another on the fly. JAI versus ImageIO.
Author: Master Wong (http://www.jguru.com/guru/viewbio.jsp?EID=1285672), May 4, 2006 On top of the your regular JDK, you will need the additional "Java Advanced Imaging Image I/O Tools" to read in your TIFF file. You can get it at: |
| Re[3]: Convert image from one format to another on the fly. JAI versus ImageIO.
Author: Jaleel Ahmed (http://www.jguru.com/guru/viewbio.jsp?EID=1298427), May 26, 2006 but that will send only the image to the browser since you have set the response type to image/jpeg . how to embed the image along with other html tags. for example i want to display the image along with an html form below the image regards ab |
My graphics card only supports 16 colors. Can I still use Java?
Location: http://www.jguru.com/faq/view.jsp?EID=3826
Created: Dec 31, 1999
Modified: 2000-02-21 09:26:10.158
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
All graphical applications require at least 256 colors. Console-based programs like servlets or the compiler are not limited by this capability.Comments and alternative answers
| Some servlets will want to use the AWT - generally
to...
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911), Feb 13, 2000 Some servlets will want to use the AWT - generally to draw into offscreen images in order to generate charts and graphs. This can be a problem on platforms with poor or non-existant graphics hardware, as (somewhat illogically) some java platforms insist on initialising the graphics device before you can use the AWT, even for totally in-memory applications like drawing to offscreen images. On UNIX platforms, the solution is to use xvfb (with the DISPLAY variable pointed to the "virtual" display that program creates). |
How do I find out the screen size of the user's machine?
Location: http://www.jguru.com/faq/view.jsp?EID=4141
Created: Jan 5, 2000
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The AWT Toolkit object provides information about the user's runtime platform. To find out what size in pixels the users's screen is, use the getScreenSize() method.
import java.awt.*;
public class Size {
public static void main(String args[]) {
// Get toolkit
Toolkit toolkit = Toolkit.getDefaultToolkit();
// Get size
Dimension dimension = toolkit.getScreenSize();
// Print size
System.out.println ("Width: " + dimension.width);
System.out.println ("Height: " + dimension.height);
// Force exit
System.exit(0);
}
}
How do I find out which mouse button is pressed for a MouseEvent?
Location: http://www.jguru.com/faq/view.jsp?EID=4147
Created: Jan 5, 2000
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersFor AWT programs, you need to compare the modifiers of the event to the button masks of the INPUT_EVENT.
Left InputEvent.BUTTON1_MASK Middle InputEvent.BUTTON2_MASK Right InputEvent.BUTTON3_MASK For Swing programs, the SwingUtilities class provides three support methods to do the INPUT_EVENT mask checking for you: isLeftMouseButton(), isRightMouseButton(), and isMiddleMouseButton().
The meaning of left, middle, and right assumes a right-handed mouse.
Also, keep in mind that not all users have three-button mice. While there are keyboard alternatives for the addition buttons, consider the awkwardness for users before adding the functionality.
| hmmm...
Author: Tao Klerks (http://www.jguru.com/guru/viewbio.jsp?EID=838651), Apr 15, 2002 I still don't get it. Where do I find those modifiers? |
How do I get all the font names supported by java using jdk1.1.8?
Location: http://www.jguru.com/faq/view.jsp?EID=7938
Created: Jan 23, 2000
Modified: 2000-01-23 13:01:49.88
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
There are two "types" of font names you can deal with in Java
- Logical Font Names
- System Font Names
Logical font names are the names Java uses for platform independence. These are names like "Serif" and "Dialog". You can obtain these names by calling
String[] fontNames = Toolkit.getDefaultToolkit().getFontList();System font names are those specific to the operating system on which you are running. The code API does not provide a means to do this in JDK 1.1.8. However, this support is provided in the Java 2 Platform through class GraphicsEnvironment.
You can use Java Native Interface (JNI) to call platform-specific code to obtain the list for JDK 1.1.8, and there are probably some class libraries that provide this support, though it would be platform-specific.
How do I make text typed in a TextArea appear in uppercase only?
Location: http://www.jguru.com/faq/view.jsp?EID=8843
Created: Jan 25, 2000
Modified: 2001-10-01 07:49:41.409
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10)
Question originally posed by lyndon mendoza (http://www.jguru.com/guru/viewbio.jsp?EID=8369
Comments and alternative answersThe key to solving this problem is to subclass TextArea and intercept any KeyEvent sent. You need to check to see if the typed key is a lower case character (be careful to keep this independent of Locale!) - if it is, change it to upper case.
Here's a piece of code that will do this for you:
import java.awt.AWTEvent; import java.awt.TextArea; import java.awt.event.KeyEvent; public class UpperCaseTextArea extends TextArea { public UpperCaseTextArea() { enableEvents(AWTEvent.KEY_EVENT_MASK); } public void processKeyEvent(KeyEvent e) { if ((e.getID() == KeyEvent.KEY_TYPED) && Character.isLowerCase(e.getKeyChar()) ) { e.setKeyChar(Character.toUpperCase(e.getKeyChar())); } else { super.processKeyEvent(e); } } }And here's a little application you can use to test it:
import java.awt.Frame; import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class UCTextAreaTest { public static void main(String[] args) { Frame f = new Frame(); f.add(new UpperCaseTextArea(), BorderLayout.CENTER); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); f.setSize(200, 150); f.setVisible(true); } }
| pful entry. I was actually looking for a password text...
Author: Marc Mellotte (http://www.jguru.com/guru/viewbio.jsp?EID=90525), Jul 3, 2000 pful entry. I was actually looking for a password text field, i.e. asterisks appear instead of the password characters. Using the code above, I subclassed TextField successfully. [FAQ Manager Note] Check out the setEchoChar() method of TextField, or use JPasswordField.... |
| I encountered a problem in the given code
After the...
Author: Saravanan Jayachandran (http://www.jguru.com/guru/viewbio.jsp?EID=91462), Jul 28, 2000 I encountered a problem in the given code After the execution of e.setKeyChar(Character.toUpperCase(e.getKeyChar())); the lowercase character gets converted into UPPERCASE but I am not able see that in the textarea as you are not setting it in the textarea( I am using Linux 5.2 jdk116_v5) |
| JFormattedTextField in Java 2, v 1.4
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11), Oct 1, 2001 Swing in Java 2, v1.4 now provides a JFormattedTextField which can have a filter to do what you're looking for. See http://java.sun.com/j2se/1.4/docs/guide/swing/1.4/ftf.html for details. |
Why must I override getPreferredSize() for Canvas to appear on the screen?
Location: http://www.jguru.com/faq/view.jsp?EID=8937
Created: Jan 26, 2000
Modified: 2000-01-26 05:38:18.498
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by arul senthil (http://www.jguru.com/guru/viewbio.jsp?EID=8904
Whenever you use a component in a layout manager, it may be asked for its preferredSize. This is a layout manager's way of respecting the sizing wishes of components that it manages. Some layout managers try to respect it, while others may ignore it.
The preferredSize property is a component's way of saying how big it wants to be to be comfortable. In the case of a Canvas, there is nothing to display, so its preferredSize is (0,0). Because of this, if it is placed in a layout manager that respected preferredSize(), like BorderLayout or FlowLayout, it will take up no space and appear invisible.
You should never "set" the preferredSize of any component from the outside. Swing components allow you to do this, but it is a very bad idea. The preferredSize should always be computed based on what the component displays. A Button, for example, figures out how big the text will be, and adds some room for the border around that text. A Panel asks its layout manager (assuming one has been set) for a preferredSize, so all of its contained components can be taken into account.
You should override the getPreferredSize() method of Canvas to return a size appropriate for what you are displaying. Depending on what is displayed, the preferredSize may need to change. For example, if you're displaying a graph and a new month is added to its x-axis, the preferred width may need to increase. Override getPreferredSize() to return the proper computed preferred size.
What exactly is the "Event Dispatch" thread (aka "AWT" Thread)?
Location: http://www.jguru.com/faq/view.jsp?EID=8963
Created: Jan 26, 2000
Modified: 2000-02-01 06:16:27.889
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Mohamed M. (http://www.jguru.com/guru/viewbio.jsp?EID=3439
Comments and alternative answersWhen you run a GUI applet or application, the code in your main() method creates a GUI and sets up event handling. When you call setVisible(true) for your Frame, Window, Dialog, or when the browser displays the Applet, the user must be able to interact with the GUI.
The problem is that your main() method may not end at that point. It could be busy doing some other task, such as computing PI to 40,000 decimal places. If the user had to wait for the main() method to finish before they could interact with the GUI, they could end up quite unhappy.
So the AWT library implements its own thread to watch GUI interaction. This thread is essentially a little loop that checks the system event queue for mouse clicks, key presses and other system-level events. (You can also put your own events in the system queue, but that's another story...).
The AWT thread (aka the "Event Dispatch" thread) grabs a system event off the queue and determines what to do with it. If it looks like a click on top of a component, it calls the mouse click processing handler for that component. That component, in turn, could fire other events. For example, if you click on a JButton, the AWT thread passes the mouse click to the JButton, which interprets it as a "button press", and fires its own actionPerformed event. Anyone listening will have their actionPerformed method called.
The AWT thread also handles repainting of your GUI. Anytime you call repaint(), a "refresh" request is placed in the event queue. Whenever the AWT thread sees a "refresh" request, if examines the GUI for damaged areas or components marked invalid (ie, the text has changed on a Label), then calls the appropriate methods to layout the GUI and paint any components that require painting.
Note: The AWT "thread" may in fact be implemented by multiple threads under some runtime environments. These threads coordinate effort to watch for mouse clicks, keypresses, repaint requests, etc. As far as you're concerned you can treat this all as one "AWT thread".
AWT components are threadsafe, in that if you call a Label's setText() method, it synchronizes such that the displayed text cannot appear with a partially old value and partially new value. However, Swing components, are generally not threadsafe. Because of this, you must make sure that any changes to Swing components that might affect their display are done through the AWT event thread. If the same thread both updates and displays a component, you are guaranteed that the display is consistent.
You can use SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() to defer processing to the AWT thread.
| Jdialog modal
Author: nandhini eswaran (http://www.jguru.com/guru/viewbio.jsp?EID=399227), Apr 9, 2001 I have an application written in java that waits for a C++ code to write result in a file. The data in the file is used to display figures in a UI which is a JDialog. when the user chooses a option on this dialog scrren then the next file from the C++ program is awaited. During this process if the JDialog screen is made modal then all the figures in the dialog screen and the main application screen are diplayed properly. But now I want the user to interact with the main application screen when the dialog is open. So I tried to make the Jdialog non-modal or make it a JFrame instead. But then I see only blank screens because the paint method is not entered at all. I think this has got some thing to do with the event handling threads which are not allowing the paint method to be entered at all Is this the case or is there some other problem? Is there a way around this? |
| See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 7, 2001 See also When exactly is the AWT thread started? |
| Delay in repainting GUI
Author: Andrew Siegel (http://www.jguru.com/guru/viewbio.jsp?EID=70978), Mar 14, 2003 This is very helpful but still leaves some vexing questions for me. For example, why does a JTextArea.append, when called within an event handler running on the EDT, not appear on the GUI until after the event handler is exited? This must be a very common question but none of my books addresses it. What's wierder to me is that awt's TextArea does _not_ work this way (but awt's label.setText(...) does). If the answer has to do with JTextArea.append being one of the few synchronized Swing methods, then why would TextArea not work the same way, if indeed awt is threadsafe as mentioned above. Even if that can be resolved, what thread would be locking the JTextArea for the duration of the actionPerformed method? I should say that I program around this all the time with invokeLater, but I would really like to understand what is going on. Something seem awry ...thanks! |
| Re: Delay in repainting GUI
Author: Bill Kress (http://www.jguru.com/guru/viewbio.jsp?EID=1142405), Jan 30, 2004 Generally when you update the screen it does not happen immideatly, it is added to a queue and all done at once. You have to have the EDT to update the component, but I'd guess that the EDT won't update the screen until after all the events (such as yours) have been handled. |
| How to trigger events programmatically?
Author: ivan ceras (http://www.jguru.com/guru/viewbio.jsp?EID=1370141), Sep 18, 2008 What if I have a custom components and has different sets of events? How do I fire an event when a certain patterns of user actions occur? Thanks, ivanceras |
Can you create custom cursors in JDK 1.1?
Location: http://www.jguru.com/faq/view.jsp?EID=8974
Created: Jan 26, 2000
Modified: 2000-01-26 06:10:18.888
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Jean-Yves BRUD (http://www.jguru.com/guru/viewbio.jsp?EID=8908
You cannot create custom cursors in JDK 1.1. This support is only available in the Java2 platform.
In JDK 1.1, you can only set cursors to the constant values provided in the java.awt.Cursor class.
How can I change the size of an Applet/JApplet in a Web Page?
Location: http://www.jguru.com/faq/view.jsp?EID=8992
Created: Jan 26, 2000
Modified: 2000-01-26 09:00:20.531
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Venkata Reddy Vajrala (http://www.jguru.com/guru/viewbio.jsp?EID=3588
Comments and alternative answersShort answer: you can't.
The browser defines a fixed-sized area in the web page for the Applet. If you need dynamic sizing, your only choice is to have your Applet display a Frame, Window, or Dialog (or their Swing equivalents).
Note that just because the Applet doesn't change size, you should not avoid layout managers. Layout managers are still important because the components could appear different sizes based on the user's font settings or locale (if your program localizes).
| Not a recommended alternative... but one way you can...
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Feb 6, 2000 Not a recommended alternative... but one way you can change the size is to have Java and JavaScript interact, forcing the page the applet is loaded on to reload with a new size. |
| You can resize an applet by using JavaScript/html....
Author: Gary Leeson (http://www.jguru.com/guru/viewbio.jsp?EID=32570), May 31, 2000 You can resize an applet by using JavaScript/html. The following HTML snipped shows a working example. You should note that the applet-name tag is important. Naturally you should not use absolute positioning of you components if want the results to look good. Hope this is of use
<BODY bgcolor=#C6C3C6 onResize="resize()"
onLoad="resize()" topmargin="0"
leftmargin="0" marginwidth="0"
marginheight="0">
<SCRIPT LANGUAGE="JavaScript">
function resize()
{
var w_newWidth,w_newHeight;
var w_maxWidth=1600, w_maxHeight=1200;
if (navigator.appName.indexOf("Microsoft") != -1)
{
w_newWidth=document.body.clientWidth-15;
w_newHeight=document.body.clientHeight-15;
}
else
{
var netscapeScrollWidth=50;
w_newWidth=window.innerWidth-netscapeScrollWidth;
w_newHeight=window.innerHeight-netscapeScrollWidth;
}
if (w_newWidth>w_maxWidth)
w_newWidth=w_maxWidth;
if (w_newHeight>w_maxHeight)
w_newHeight=w_maxHeight;
document.myApplet.setSize(w_newWidth,w_newHeight);
window.scroll(0,0);
}
window.onResize = resize;
window.onLoad = resize;
</SCRIPT>
<APPLET NAME="myApplet"
CODE="GUIFrame.class"
archive="swingall.jar"
WIDTH="2000" HEIGHT="1000"
ALIGN="BOTTOM">
</APPLET>
</BODY>
|
| Very easy in fact.
All you have to do is to make good...
Author: moetai brotherson (http://www.jguru.com/guru/viewbio.jsp?EID=100631), Jul 12, 2000 Very easy in fact. All you have to do is to make good use of HTML. In the size parameters of the applet tag just put 100% and 100% instead of pixel sizes. Then your applet will AUTOMATICALLY resize without anything else to do!
Even works with swing applets in the translated tag. |
| Calling "document.myApplet.setSize( w_newWidth,...
Author: Hendrik-Jan van Randen (http://www.jguru.com/guru/viewbio.jsp?EID=116340), Aug 1, 2000
Any good solution that works fine in both Netscape and Internet Explorer would still be highly appreciated...
|
| Re: Calling "document.myApplet.setSize( w_newWidth,...
Author: Michael Witbrock (http://www.jguru.com/guru/viewbio.jsp?EID=505541), Sep 27, 2001 This works fine in Mozilla as of 2001 09 21 presumably netscape 6.1 too. |
| And by the way, on a Mac JavaScript to Java commun...
Author: Jasen Halmes (http://www.jguru.com/guru/viewbio.jsp?EID=55625), Sep 14, 2000 And by the way, on a Mac JavaScript to Java communication doesn't work. So any solution requiring this would not be useful to cross platform developers. What we need is for the browser/vm writers to obey the Java spec and implement the resize call. Then no "hacks" are necessary. |
| how can i change the size of applet
Author: hai dong (http://www.jguru.com/guru/viewbio.jsp?EID=463628), Jul 27, 2001 it's possible. you just write the applet attribute from javascript like
if(chooseSizeA){
document.write('<Applet code="blabla" size="blabla"'>)
document.write('</Applet>');
else{
document.write('<Applet code="blabla" size="blabla"'>)
document.write('</Applet>');
}
so you can change the size. |
| Here it is!
Author: Kaan Uzun (http://www.jguru.com/guru/viewbio.jsp?EID=874169), May 10, 2002 Gary's javascript solution works, it is just incomplete. You have to override the setSize(int, int) of the Applet class: public void setSize(int width, int height) { super.setSize(width,height); validate(); } Here check out Francis Lu's full document on this: http://www.javaworld.com/javaworld/javatips/jw-javatip80.html However as noted above, I don't have access to a MAC so don't know for sure, this probably is not cross-platform compatible. However getting Netscape and Explorer for once to behave the same way is a good start!! |
| How can I change the size of an Applet/JApplet in a Web Page?
Author: Jerry Lampi (http://www.jguru.com/guru/viewbio.jsp?EID=1089525), Jan 20, 2004 Keep in mind that the width=nn% and height=nn% work in the <OBJECT...> form of the applet tag as well. I was blinded by all the examples on this showing <APPLET> tags, but in current browsers (Internet Explorer 6.x and Netscape 7.1), the percentages are supported using the new <OBJECT> tag as well. In fact, there is no need to make any JavaScript and/or Applet changes at all. Simply change to percentages and the applet resizes accordingly. Of course, your applet(s) must have a decent layout manager for the resize to look okay. In addition, I found that the Applet had to be outside of an HTML table. Some interesting notes I discovered while wasting time trying to make the fancy JavaScript/Applet setSize() work:
|
| Re: How can I change the size of an Applet/JApplet in a Web Page?
Author: Rob Guest (http://www.jguru.com/guru/viewbio.jsp?EID=985742), Jul 30, 2004 I am setting both the width and height to %100 within the OBJECT tag. My page launches a new window that only displays the applet. This works great in IE; The applet fills the window and it resizes beautifully. However, in Netscape the applet height is about 200 pixels (should be about 600), leaving a 400 pixel high white space under the applet; plus, the width resizes but not the height. I use JavaScript to open the new applet window to a specific dimension. The window loads a simple HTML doc with just something like the following in the body:
<OBJECT
classid="clsid:8AD9C840-044E-11D1-B3E9-008054F55D3"
codebase="http://java.sun.com/update/1.4.2/jinstall-1_4-windows-i586.cab#Version=1,4,0,0"
WIDTH="100%" HEIGHT="100%" >
<PARAM NAME=CODE VALUE="editor/Applet.class" >
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.4">
<PARAM NAME="scriptable" VALUE="false">
<PARAM NAME="ARCHIVE" VALUE="cica.jar">
<PARAM name="progressbar" value="true">
<COMMENT>
<EMBED
type="application/x-java-applet;version=1.4"
CODE="editor/Applet.class"
ARCHIVE="cica.jar"
WIDTH="100%"
HEIGHT="100%"
scriptable="false"
progressbar="true"
pluginspage="http://java.sun.com/products/plugin/index.html#download">
<NOEMBED>
</NOEMBED>
</EMBED>
</COMMENT>
</OBJECT>
Anyone know why the applet's height does not change when I use Netscape?
Thanks,
Rob
|
| Re[2]: How can I change the size of an Applet/JApplet in a Web Page?
Author: Benoit Mahe (http://www.jguru.com/guru/viewbio.jsp?EID=1231647), Mar 9, 2005 I think I found a workarround for netscape/mozilla/firefox. Apparently, height=100% does not work on object tag because of a lack of reference.
I tried to add a surrounding div with a fixed height and the <object> tag with height=100% works fine and fill the entire div area.
So, we just have to update the javascript and change the div height on resize.
|
How are individual pixels represented in memory?
Location: http://www.jguru.com/faq/view.jsp?EID=9765
Created: Jan 28, 2000
Modified: 2000-02-14 08:55:24.887
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Each pixel is stored as a 32 bit integer (int). The int packs four unsigned bytes within it, one for each of the alpha, red, green, and blue (ARGB) color planes, in that order.
Alpha
(8-bits)Red
(8-bits)Green
(8-bits)Blue
(8-bits)32 bit pixel To get at each value, you would use a masking operation and a bit shift :
int alpha = (pixel & 0xff000000) >> 24; int red = (pixel & 0x00ff0000) >> 16; int green = (pixel & 0x0000ff00) >> 8; int blue = (pixel & 0x000000ff) >> 0;Keep in mind that you cannot store each value in a byte as bytes are signed.
How do you create custom cursors with the Java 2 platform?
Location: http://www.jguru.com/faq/view.jsp?EID=9958
Created: Jan 29, 2000
Modified: 2000-01-31 08:11:21.708
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersThe createCustomCursor() method of the Toolkit class provides for the ability to create a cursor out of an Image.
When creating custom cursors, be sure to take advantage of the hints available from the getBestCursorSize() and getMaximumCursorColors() methods.
| custom cursor size
Author: D M (http://www.jguru.com/guru/viewbio.jsp?EID=1067355), Mar 18, 2003 In a basic program using gifs for cursor Images I found that unless the image is 30*30 (pixels) it will be enlarged. This could just be me, but a 30*30 image with lots of transparant space works well for me :) |
| Re: custom cursor size
Author: ashwini iyer (http://www.jguru.com/guru/viewbio.jsp?EID=1127648), Nov 11, 2003
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("img.gif");
brokenCursor = toolkit.createCustomCursor(image , new Point(0,0), "img");
Component.setCursor(brokenCursor);
|
| Re[2]: custom cursor
Author: Adam Farris (http://www.jguru.com/guru/viewbio.jsp?EID=1213935), Nov 30, 2004 I have the following code in my program:
Toolkit tk = Toolkit.getDefaultToolkit();
Image pointer = tk.getImage("pointer.gif");
Cursor myPointer= tk.createCustomCursor(pointer, new Point(10,10), "Blah");
when I run the program, it never gets to the point where it shows the Jframe that i've made. If I comment out the last line it runs just fine, but of course it doesn't make my cursor. can anyone tell me why, or suggest a different way to make a cursor? |
| Re[3]: custom cursor
Author: wwqw wqwqwqw (http://www.jguru.com/guru/viewbio.jsp?EID=1220234), Jan 8, 2005 try using ImageIcon img = new ImageIcon("pointer.gif") Image pointer = img.getImage(); instead of tk.getImage("pointer.gif") |
| Re[4]: custom cursor
Author: Martin Zvarik (http://www.jguru.com/guru/viewbio.jsp?EID=1221703), Jan 17, 2005 I need to have there a drawing like a circle or rectangle... is it possible to have cursor as an drawing instead of an image??? PLEASE help!!! (mzvarik@atlas.cz) |
| I GOT IT :-)
Author: Martin Zvarik (http://www.jguru.com/guru/viewbio.jsp?EID=1221703), Jan 17, 2005 curWidth=32; curHeight=32; int pix[] = new int[curWidth*curHeight]; for(y=0; y<=curHeight; y++) for(x=0; x<=curWidth; x++) pix[y+x]=0; // all points transparent // black circle - outside curCol=Color.black.getRGB(); yscale=10; xscale=10; for(x=2; x<=8; x++) pix[x]=curCol; // up for(x=2; x<=8; x++) pix[(yscale*curWidth)+x]=curCol; // bottom for(y=2; y<=8; y++) pix[curWidth*y]=curCol; // left for(y=2; y<=8; y++) pix[(curWidth*y)+yscale]=curCol; // right pix[1+curWidth]=curCol; pix[yscale+curWidth-1]=curCol; pix[1+(curWidth*(yscale-1))]=curCol; pix[(curWidth*(yscale-1))+yscale-1]=curCol; // white circle - inside curCol=Color.white.getRGB(); yscale=yscale-1; xscale=xscale-1; for(x=3; x<=7; x++) pix[x+curWidth]=curCol; // up for(x=3; x<=7; x++) pix[(yscale*curWidth)+x]=curCol; // bottom for(y=3; y<=7; y++) pix[curWidth*y+1]=curCol; // left for(y=3; y<=7; y++) pix[(curWidth*y)+yscale]=curCol; // right pix[2+curWidth+curWidth]=curCol; pix[yscale+curWidth+curWidth-1]=curCol; pix[1+(curWidth*(yscale-1))+1]=curCol; pix[(curWidth*(yscale-1))+yscale-1]=curCol; img = createImage(new MemoryImageSource(curWidth,curHeight,pix,0,curWidth)); Cursor curCircle = Toolkit.getDefaultToolkit().createCustomCursor(img,new Point(5,5),"circle"); setCursor(curCircle); |
| Cursor resolution looks lower than for regular cursors?
Author: Anna Hedman (http://www.jguru.com/guru/viewbio.jsp?EID=1317232), Oct 26, 2006 Hi, I tried to specify my own cursor in a similar way as described above, but for some reason my cursor becomes larger than normal cursors and the resolution looks lower than for the rest of the screen. Any suggestions on what to do about that? |
| Re: I GOT IT :-)
|
| Re: custom cursor size
Author: Dooma Mr (http://www.jguru.com/guru/viewbio.jsp?EID=1257660), Aug 11, 2005 Cursor c; Toolkit tk = Toolkit.getDefaultToolkit(); Image image = getImage(getCodeBase (),"lofasz.gif"); c = tk.createCustomCursor(image, new Point(0,0),"cursorName"); setCursor(c); this worked for me perfectly :D The only thing you need to change is: "lofasz.gif" |
| Re[2]: custom cursor size
Author: Rocha Melo (http://www.jguru.com/guru/viewbio.jsp?EID=1280935), Jan 27, 2006 This version worked great for me too. I'm wondering how to perform this change of the cursor just over a component, say a button. I tried to use the setCursor() on the component, but it keeps changing as soon as it enters the Frame around it. Please, some help ? Thanks in advance |
| Re[3]: custom cursor size
Author: Jerome Falcon (http://www.jguru.com/guru/viewbio.jsp?EID=1286654), Mar 3, 2006 Perform the changed cursor on a Button (yourButton) for example, use the MouseListener :
yourButton.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
setCursor(yourCursor);
}
public void mouseExited(MouseEvent e) {
setCursor(null); // or setCursor(anotherCursor);
}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
});
|
| Re[4]: custom cursor size
Author: Glenn Murphy (http://www.jguru.com/guru/viewbio.jsp?EID=1299718), Jun 5, 2006 You should also check out this function in the java.awt.Toolkit class: public Dimension getBestCursorSize(int preferredWidth, int preferredHeight) On XP the 'best' cursor size appears to be 32x32, (which allows for cursors rather bigger than a standard mouse arrow at 12x21) and images of any other size passed into createCustomCursor() seem to get scaled... So what i did was to make a method that will take my own image (presumed smaller than 32x32) and blit it onto a new image of the best size and then pass that into createCustomCursor instead... which avoids the scaling... so my basic 12x21 arrow gets blitted onto a new best size 32x32 image (BufferedImage, type=ARGB to encompass the bitmask transparency) and the scaling is avoided. Also passing zeros, into the getBestCursorSize(0, 0) seems to just give u right away the default best size, not sure how passing in what u prefer affects things exactly. Another note is the Point parameter means u can offset the click point of the cursor image, so u can make a spherical target with the center of the image the click point if u want. |
| Re[5]: custom cursor size
Author: Ray Cooke (http://www.jguru.com/guru/viewbio.jsp?EID=1304035), Jul 3, 2006 I'm implementing custom cursors pretty much as specified here, however I keep getting a thick shadow around the image i'm using as the cursor. I can't seem to track this down anywhere. Any idea what this might be and how I could get rid of it?! :S
Ray |
| custom cursor
Author: Maulik Patel (http://www.jguru.com/guru/viewbio.jsp?EID=1348206), Sep 30, 2007 Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = toolkit.getImage("img.gif"); brokenCursor = toolkit.createCustomCursor(image , new Point(0,0), "img"); Component.setCursor(brokenCursor); when I use this code and move mouse over the frame, cursor never appears. Can you please explain me why? |
| Custom Cursor
Author: Tom Fiset (http://www.jguru.com/guru/viewbio.jsp?EID=1334121), Apr 16, 2007 I found that this worked magically:
Toolkit tk = Toolkit.getDefaultToolkit();
try{
setCursor(
tk.createCustomCursor(ImageIO.read(this.getClass().getResourceAsStream("/Cursor.png")),
new Point(15,15),"MyCursor" ) );
}
catch(Exception e){}
Where the point's coordinates(where the click is detected) are half the size of the image(this one was 30x30, thus 15 and 15). The class this is in extends JPanel and import javax.imageio.*; The image is in the same folder as the .class file. |
How do I create a window that always stays on top of my application?
Location: http://www.jguru.com/faq/view.jsp?EID=9991
Created: Jan 30, 2000
Modified: 2000-01-31 08:14:48.627
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersWithout resorting to native code, you cannot do this.
| If your application has a single frame you could
create...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Feb 24, 2000 If your application has a single frame you could create a non-modal dialog with the application as it's parent. The non-modal dialog should stay on top of the frame. I have myself used this to create floating toolbars which (correctly) stay on top of the application frame, unlike the Swing's floating toolbars. |
| Re: If your application has a single frame you could create...
Author: Nicky Mølholm (http://www.jguru.com/guru/viewbio.jsp?EID=1092895), Jun 11, 2003 Hi! I just verified the previous answer - it actually works!! For those of you who need a quick-snip...here it is:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Try {
public Try () {
JFrame f = new JFrame();
f.getContentPane().add(BorderLayout.CENTER, new JButton ("hello"));
f.setSize(300,300);
f.setVisible(true);
new EscapeDialog(f);
}
public static void main (String[] args ) {
new Try();
}
}
class EscapeDialog extends JDialog {
public EscapeDialog(JFrame owner) {
super (owner);
getContentPane().add(BorderLayout.CENTER, new JButton ("hello"));
setModal(false);
setSize(50,45);
setVisible(true);
}
}
|
How do we build a TabbedPane component using AWT?
Location: http://www.jguru.com/faq/view.jsp?EID=10323
Created: Jan 31, 2000
Modified: 2000-01-31 08:34:01.989
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by vinay babu (http://www.jguru.com/guru/viewbio.jsp?EID=10197
Swing provides a component called JTabbedPane that is rather good.
If you cannot (or don't want to) use Swing for some reason, there are several ways to do this.
The most common one is to create a custom Panel subclass that uses a CardLayout to display its children, and provide a set of buttons along an edge to switch between components. Other ways are more manual to track the components.
For an example (free with source code, for any use other than simply selling it) please see Scott Stanchfield's TabSplitter at http://www.javadude.com/tools/tabsplitter.
How do you change the coffee cup icon that appears in the top corner of frames?
Location: http://www.jguru.com/faq/view.jsp?EID=10385
Created: Jan 31, 2000
Modified: 2000-07-25 20:36:40.75
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersThe setIconImage() method of the Frame class permits you to alter the icon displayed.
Image image = ...; aFrame.setIconImage(image);See How do I display an Image in an Applet or Application? for how to load the image.
| JDialog
Author: Craig Newlander (http://www.jguru.com/guru/viewbio.jsp?EID=411343), Jul 12, 2001 This method does not work for a JDialog. How can the icon be changed for a JDialog ? |
| Re: JDialog
Author: useng yap (http://www.jguru.com/guru/viewbio.jsp?EID=419669), Aug 17, 2001 I think JDialog inherit the Icon from the owner frame. Hope this can help. ^_^ |
| help needed
Author: tang kwong fatt (http://www.jguru.com/guru/viewbio.jsp?EID=1136464), Dec 31, 2003
i try using it, but there is some error in it;
P:\Fatt\Java\Final Project\MainFrame.java:15: incompatible types
found : java.lang.String
required: java.awt.Image
Image image = ("P:\\A.bmp");
//the arrow point at " -before P:\\
my code is as following;
Image image = ("P:\\A.bmp");
mainFrame.setIconImage(image);
thanz
|
| Re: help needed
Author: Konstantinos Fragkopoulos (http://www.jguru.com/guru/viewbio.jsp?EID=1189978), Aug 2, 2004 Try this... setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(imageLocation)));
e.g. imageLocation = "/com/somecompany/Resources/GIFs/yourImage.gif" |
| it's working but...
Author: Ashish Dhyani (http://www.jguru.com/guru/viewbio.jsp?EID=1251633), Jul 4, 2005 setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(imageLocation))); is working but for only some gif images and it is not working when i m creating the excutable jar. Can any one tell how to do this with executable jar. Thanks in advance... |
| java Icon
Author: Marty Buswell (http://www.jguru.com/guru/viewbio.jsp?EID=1173244), May 24, 2004 Can you send me a step by step outline on how to change the Java Icon to another Icon, whatever it may be? Thank you..smarty |
| Re: java Icon
Author: Gesu TaNazzaret (http://www.jguru.com/guru/viewbio.jsp?EID=1329096), Feb 22, 2007 Image image = new ImageIcon(locationOfImage).getImage(); this.setIconImage(image); //where 'this' refers to a JFrame |
| java Icon
Author: Marty Buswell (http://www.jguru.com/guru/viewbio.jsp?EID=1173244), May 24, 2004 Can you send me a step by step outline on how to change the Java Icon to another Icon, whatever it may be? Thank you..smarty |
When do I use adapter classes vs. interfaces in "new" expressions for event handling?
Location: http://www.jguru.com/faq/view.jsp?EID=10618
Created: Feb 1, 2000
Modified: 2000-02-01 06:51:05.129
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Gopal Saha (http://www.jguru.com/guru/viewbio.jsp?EID=10163
Comments and alternative answersWhen you register an event handler, you must pass it an instance of some class that implements its listener interface.
Simple Event Handler
Start with a simple example. Suppose we want to print "Hello" when a button is pressed. Button fires an actionPerformed event when pressed, which is the only method in the ActionListener interface. We could write the following code to accomplish this task:
SayHello.java
import java.awt.*; import java.awt.event.*; public class SayHello implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Hello"); } }
SimpleGUI.java
import java.awt.*; public class SimpleGUI { public static void main(String[] args) { Frame f = new Frame(); Button b = new Button("Press me"); b.addActionListener(new SayHello()); f.add(b); f.setVisible(true); // application exit handler omitted } }Simple Anonymous Inner Class
It seems like a waste to create an entirely new class just to say "Hello". This uses up a class name in our namespace, and unique names can be difficult to create.
To help this, we create an anonymous inner class by writing the event handler class code in the call to register the event handler. The new test class looks as follows:
SimpleGUI2.java
import java.awt.*; import java.awt.event.*; public class SimpleGUI2 { public static void main(String[] args) { Frame f = new Frame(); Button b = new Button("Press me"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Hello"); }}); f.add(b); f.setVisible(true); // application exit handler omitted } }ActionListener is an interface! Whenever you see "new" followed by an interface name and a "{" (open curly brace), you're creating an anonymous inner class. You would read
new ActionListener() { ... }as "Create a new instance of some class (we don't care what its name is) that implements ActionListener, and the details are in the curly braces."
This is a convenient shorthand for creating event handlers.
Event Adapters
Some event listener interfaces require several methods. For example, WindowListener requires seven methods. Normally, you only care about one of these methods, windowClosing. If we were to write an anonymous inner class to close an application, it might look as follows
Frame f = new Frame(); f.addWindowListener(new WindowListener() { public void windowClosing(WindowEvent e) { System.exit(0); } public void windowClosed(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} });All of those dummy methods are really a lot of noise. In java.awt.event, Sun defined a class called WindowAdapter that implements WindowListener with seven dummy methods. This means that you can extend WindowAdapter and you only need to override the classes you care about. The above code becomes:
Frame f = new Frame(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); }});You read the anonymous inner class above as "create an instance of some class (we don't care what its name is) that extends WindowAdapter, and the details are in the curly braces."
The full example for the button press and window close follows:
SimpleGUI3.java
import java.awt.*; import java.awt.event.*; public class SimpleGUI3 { public static void main(String[] args) { Frame f = new Frame(); Button b = new Button("Press me"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Hello"); }}); f.add(b); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); }}); f.setVisible(true); // application exit handler omitted } }
| Thanks, good explanation
Author: cto cto (http://www.jguru.com/guru/viewbio.jsp?EID=1374611), Dec 7, 2008 Makes sense. Adapter is just an implementation of an interface but with dummy/nonsense methods. |
How do I get rid of the Unsigned Java Applet Window message at the bottom of windows/frames I create in my applet?
Location: http://www.jguru.com/faq/view.jsp?EID=11000
Created: Feb 2, 2000
Modified: 2000-09-13 13:37:36.369
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersThis is a security feature to prevent untrusted applets from displaying what appear like trusted windows. If you sign your applet and the user trusts you, the message will go away.
| For information on signed applets and their browser...
Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15), Feb 4, 2000 For information on signed applets and their browser interaction, see Certificate jFAQ |
What is a peer?
Location: http://www.jguru.com/faq/view.jsp?EID=11353
Created: Feb 4, 2000
Modified: 2000-02-04 06:50:13.207
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
Comments and alternative answersAWT uses native code (code specific to a single operating system) to display its components. Each implementation of the Jave Runtime Environment (JRE) must provide native implementations of Buttons, Labels, Panels, and all of the other AWT components.
Whenever you use an AWT component, if forwards all of its drawing requests to a piece of native code. This allows you to generically use an AWT Button in your application, but the Button appears as a Windows Button, a Motif Button, a Mac Button, or a real button on whatever platform you are running.
These pieces of native code are referred to as peers, as they share the responsibility for displaying a component.
Peer code includes native code to display components, as well as draw lines, determine platform specifics such as current screen size, and other native platform issues.
Note that the Swing components do use peers for two tasks. First, Swing's JFrame, JWindow, JDialog and JApplet extend their AWT counterparts. They all use peers to display a real drawing area on the screen.
Other Swing components are lightweight; they do not have peers. These components draw themselves on top of an existing JFrame, JWindow, JDialog or JApplet. However note that the drawing functions are implemented using peers, so they actually use peers as well, though not as their complete implementations.
| It's not strictly true that peers need be native c...
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911), Feb 13, 2000 It's not strictly true that peers need be native code. Really, peers provide _platform_specific_ implementation of their platform independant java.awt counterparts. In the standard implementations (motif, win32, mac) it's true that the peers do a bit of processing (in java) and then hand off the bulk of the work to the local native window library - but this need not be the case. For example, Sun's Personal Java Application Environment http://java.sun.com/products/personaljava/pjava_ds.html includes their "Truffle" toolkit, which implements most of the functionality of each AWT peer in java code, and only hands primitive operations down to the native layer. Don't be confused - these are real AWT peers, neither lightweights nor Swing components. [FAQ Manager comment]Good points, and I completely agree. |
How do I get the native window pointer to an AWT Window?
Location: http://www.jguru.com/faq/view.jsp?EID=11518
Created: Feb 4, 2000
Modified: 2000-02-05 07:38:58.931
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
This capability is currently not supported.Comments and alternative answers
| Though it is not public attached below is the code...
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011), May 4, 2000 Though it is not public attached below is the code snippet that uses Undocumented classes and methods to get the HWND of a java.awt.Canvas on Windows NT/98 running JDK 1.1.8 (or) 1.2.2 (or) above.
import java.awt.*;
import sun.awt.*;
/* This class uses undocumented features of Sun's JDK */
/* Works only on Windows NT/98 with JDK1.1.8, JDK1.2.2 */
public class SunCanvas extends Canvas
{
/* Returns the HWND for canvas. */
public int getHWND()
{
DrawingSurfaceInfo drawingSurfaceInfo;
Win32DrawingSurface win32DrawingSurface;
int hwnd = 0;
/* Get the drawing surface */
drawingSurfaceInfo =
((DrawingSurface)(getPeer())).getDrawingSurfaceInfo();
if (null != drawingSurfaceInfo) {
drawingSurfaceInfo.lock();
/* Get the Win32 specific information */
win32DrawingSurface =
(Win32DrawingSurface)drawingSurfaceInfo.getSurface();
hwnd = win32DrawingSurface.getHWnd();
drawingSurfaceInfo.unlock();
}
return hwnd;
}
}
|
| Re: Though it is not public attached below is the code...
Author: gowri gopalakrishnan (http://www.jguru.com/guru/viewbio.jsp?EID=515181), Oct 9, 2001 Hello I used this code above to render a visualization program (c++) in a java application. Rendering works fine but when I catch the events in C (key and mouse ) using the winproc and update the visualization rendering, my screen is not updated, Though the visualization program finished the rendering. Is there anyway suggestions as to how to update the screen for key and mouse clicks |
Can I use the Java2D capabilities with the 1.1 Java runtime environment?
Location: http://www.jguru.com/faq/view.jsp?EID=11525
Created: Feb 4, 2000
Modified: 2000-07-01 22:20:36.696
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The short answer is no. The libraries are part of the standard Java 2 platform release (starting with version 1.2). Since they modify core classes in the java.awt.* libraries, you can not pull them out and use them with another version. They are not a standard extension like Swing, but part of the standard release.
How do I use layout managers to compose a GUI?
Location: http://www.jguru.com/faq/view.jsp?EID=11659
Created: Feb 5, 2000
Modified: 2000-05-29 11:54:18.162
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
See Effective Layout Management at the Java Developer Connection.
How can I simulate user interaction (key press, mouse click) on a component?
Location: http://www.jguru.com/faq/view.jsp?EID=11818
Created: Feb 6, 2000
Modified: 2000-02-07 07:33:25.564
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by lyndon mendoza (http://www.jguru.com/guru/viewbio.jsp?EID=8369
Comments and alternative answersThe 1.3 Java release includes a Robot class to generate low-level native mouse / keyboard input events at the operating system level.
The other alternative is to call postEvent() of the EventQueue class.
| You can programmatically perform a "click"...
Author: Saravanan Jayachandran (http://www.jguru.com/guru/viewbio.jsp?EID=91462), Jul 28, 2000 You can programmatically perform a "click" on a JButton , JMenuItem , JToggleButton using the doClick() method of the javax.swing.AbstractButton class. You can also specify the duration of click |
How do I center a dialog on top of a frame?
Location: http://www.jguru.com/faq/view.jsp?EID=12670
Created: Feb 9, 2000
Modified: 2000-02-09 07:56:40.664
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Comments and alternative answersWhen you create a dialog, you must pass it the parent Frame. This Frame can be obtained via the Dialog's getParent() method. We'll define a subclass of Dialog called CenterableDialog that will look at the parent Frame and determine where to place the dialog. We must be careful and watch out for the screen edges too!
The CenterableDialog class
Here's the code. Once you define this class, all you have to do is:
- Use CenterableDialog wherever you would normally use Dialog
- Call showCentered() instead of show() to display the dialog. The reason we don't override show() itself is so we can still explicitly set the dialog's position and show() it non-centered.
import java.awt.Dialog; import java.awt.Dimension; import java.awt.Point; import java.awt.Frame; public class CenterableDialog extends Dialog { public CenterableDialog(Frame parent) { super(parent); } public CenterableDialog(Frame parent, String title) { super(parent, title); } public CenterableDialog(Frame parent, String title, boolean modal) { super(parent, title, modal); } public CenterableDialog(Frame parent, boolean modal) { super(parent, modal); } public void showCentered() { Frame parent = (Frame)getParent(); Dimension dim = parent.getSize(); Point loc = parent.getLocationOnScreen(); Dimension size = getSize(); loc.x += (dim.width - size.width)/2; loc.y += (dim.height - size.height)/2; if (loc.x < 0) loc.x = 0; if (loc.y < 0) loc.y = 0; Dimension screen = getToolkit().getScreenSize(); if (size.width > screen.width) size.width = screen.width; if (size.height > screen.height) size.height = screen.height; if (loc.x + size.width > screen.width) loc.x = screen.width - size.width; if (loc.y + size.height > screen.height) loc.y = screen.height - size.height; setBounds(loc.x, loc.y, size.width, size.height); show(); } }What about FileDialog?
You can use the same subclass trick on FileDialog -- it would look exactly the same as the above, except for the name of the class.
| In JDK 1.3, you cannot apply the above code to a F...
Author: ha qi (http://www.jguru.com/guru/viewbio.jsp?EID=265826), Jan 16, 2001 In JDK 1.3, you cannot apply the above code to a FileDialog. It will always have a position (0, 0). |
When used in an Applet/JApplet, does a Frame/JFrame show up inside the web page or as a new window?
Location: http://www.jguru.com/faq/view.jsp?EID=13602
Created: Feb 12, 2000
Modified: 2000-02-12 07:15:02.056
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Duane Vigue (http://www.jguru.com/guru/viewbio.jsp?EID=12977
If you add components to an Applet or JApplet, they will appear in the web page's assigned spot for the applet.
If you create a new Frame, Window, or Dialog (or their Swing equivalents), they will always appear as a separate window (complete with a small Warning tag to indicate they were created by an applet -- see the certificate FAQ, http://www.jguru.com/jguru/faq/view.jsp?EID=11475).
If you would like to have Frames appear in the web page itself, you could add a JDesktopPane to a JApplet, and add JInternalFrames to it. This of course requires Swing, and the best way to ensure this is to use the Java Plug-in from Sun (http://java.sun.com/products/plugin/).
How do I convert an in-memory bitmap to something that is usable by JAVA?
Location: http://www.jguru.com/faq/view.jsp?EID=13924
Created: Feb 13, 2000
Modified: 2000-02-14 08:40:18.838
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Steven Cote (http://www.jguru.com/guru/viewbio.jsp?EID=11054
Jef Poskanzer has a 1.1-compliant GIF writer: http://www.acme.com/java/software/Acme.JPM.Encoders.GifEncoder.htmlComments and alternative answers
| If your pixel data is stored in an array of ints
(...
Author: Stephen Hodnicki (http://www.jguru.com/guru/viewbio.jsp?EID=33499), Apr 7, 2000 If your pixel data is stored in an array of ints
(
From an
Image myNewImage = createImage(new MemoryImageSource(width, height, pix, 0, width) );
where
|
| Re: If your pixel data is stored in an array of ints
(...
Author: ANKANET (www.ankanet.com.tr) (http://www.jguru.com/guru/viewbio.jsp?EID=787522), Mar 7, 2002 We have implemented APIs for such usages. You can easily encode into and decode from GIF/BMP/WBMP/JPEG formats. APIs are very easy to use in any Java application. Please check http://java.ankanet.com.tr for more info. |
How can I capture the image of an AWT GUI?
Location: http://www.jguru.com/faq/view.jsp?EID=14471
Created: Feb 15, 2000
Modified: 2000-05-24 05:39:56.497
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by RaghuNath Boyalakuntla (http://www.jguru.com/guru/viewbio.jsp?EID=12873
Comments and alternative answersYou can use the printAll() method of Component to accomplish this.
As an example
Component comp = ... ; // the top-level component // you want to capture // create an image for the capture Image img = comp.createImage(comp.getWidth(), comp.getHeight()); // grab a graphics context for that image Graphics g = img.getGraphics(); // print the GUI into that image comp.printAll(g);The resulting Image contains a picture of the GUI. Note that if the GUI is not displayes, you either need to display it first or call addNotify() on it to create the necessary peer components.
| I tried the code above, and it seems to me that
it...
Author: Scott Anderson (http://www.jguru.com/guru/viewbio.jsp?EID=25975), Mar 19, 2000 I tried the code above, and it seems to me that it only works in appletviewer or application. If the code runs inside a browser (IE5,NS4), the pixels in the off screen image is shifted. Looks like the ColorModel used in the on-screen image is different from the one in the off-screen image created by createImage(w,h); I have no idea on how to fix this problem. Can anyone help? |
| I tried the same but here my problem is to get the...
Author: karuppanan rameshkumar (http://www.jguru.com/guru/viewbio.jsp?EID=102591), Jul 28, 2000 I tried the same but here my problem is to get the Image object of the GUI.But comp.createImage() is always returning null please correct me. [FAQ Manager Note] Make sure the GUI has actually been realized -- you can do this by making sure the GUI was already displayed, or by calling comp.addNotify(). |
Can I use menus and a menu bar in an applet?
Location: http://www.jguru.com/faq/view.jsp?EID=15630
Created: Feb 18, 2000
Modified: 2000-02-18 13:16:57.344
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
AWT applets (those that subclass java.applet.Applet) cannot include an AWT MenuBar. Swing applets (those that subclass javax.swing.JApplet) can use the JMenuBar. To display menus in an AWT you would either need to create an external Frame to place them in or create your own custom components that simulated the behavior of menus on menu bars.Comments and alternative answers
| It has been known that in some browsers it is
possible...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Feb 24, 2000 It has been known that in some browsers it is possible to walk up the getParent() chain of the Applet and get an instance of Frame subclass and then call setMenuBar() on it. The same technique is known to have worked for creating modal dialogs. It is not a supported behaviour though. Also, if the web page is scrolled the menubar may not move with your applet.
Other alternative is to use Netscape LiveScript
and/or Dynamic HTML layers to simulate a
MenuBar+Menu combo.
|
I tried adding the same menu item to multiple menus. Why doesn't it work properly?
Location: http://www.jguru.com/faq/view.jsp?EID=15643
Created: Feb 18, 2000
Modified: 2000-02-18 13:53:05.223
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersWhen adding a component to a container, it is removed from any previous container. Because of this, you cannot have the same component/menu items in multiple containers/menus.
| An alternative to adding a single menu item to multiple...
Author: Jeff Mackay (http://www.jguru.com/guru/viewbio.jsp?EID=16238), Feb 21, 2000 An alternative to adding a single menu item to multiple menus is to use Actions. A single action can be added to multiple menus and toolbars. When you change properties of the action (text, icon, enable state), those changes are reflected in each menu/toolbar. |
How can I limit the size of my window?
Location: http://www.jguru.com/faq/view.jsp?EID=15690
Created: Feb 18, 2000
Modified: 2000-02-18 14:12:48.188
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersYou can register a ComponentListener with the window and have the componentResized() method validate the window size. If the window is outside acceptable limits, you can return things to the desired size.
| This has a snapping effect behaviour.
Here is the...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Feb 24, 2000 This has a snapping effect behaviour. Here is the code -
/**
* FrameResize.java
*
*
* Created: Thu Feb 24 12:07:14 2000
*
* @author Sandip Chitale (schitale@selectica.com)
* @version
*/
import java.awt.*;
import java.awt.event.*;
public class FrameResize extends Frame {
public FrameResize () {
}
public static void main(String args[])
{
Frame f = new FrameResize();
f.setSize(300, 300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
f.addComponentListener(
new ComponentAdapter() {
public void componentResized(ComponentEvent ce)
{
Frame sf = (Frame) ce.getComponent();
sf.removeComponentListener(this);
sf.setSize(
Math.min(sf.getSize().width, 500), Math.min(sf.getSize().height, 500)
);
sf.addComponentListener(this);
}
}
);
}
}// FrameResize
|
| If call setResizable(false) method in Dialog, Frame and JFrame, anybody cant resize the window by mouse, etc.
Author: Young-tae Lee (http://www.jguru.com/guru/viewbio.jsp?EID=900707), Jun 21, 2002 Dialog, Frame, JFrame and JInternalFrame classes support setResizable() method. it makes anybody to resize the window. For more information, refer JDK API. and you can see a chip code like this:
import java.awt.*;
import java.awt.event.*;
public class FrameResize2 extends Frame {
public FrameResize2 () {
setSize(300, 300);
setResizable(false);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
}
public static void main(String args[])
{
new FrameResize2();
}
}
|
How do I force drawImage() to refetch an image?
Location: http://www.jguru.com/faq/view.jsp?EID=15705
Created: Feb 18, 2000
Modified: 2000-02-21 03:42:22.595
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
If you flush() an Image between calls to drawImage(), the Image will be refetched instead of using the local cached version.
What is the difference between JFC & WFC?
Location: http://www.jguru.com/faq/view.jsp?EID=16247
Created: Feb 20, 2000
Modified: 2000-02-21 03:49:59.617
Author: Jeff Mackay (http://www.jguru.com/guru/viewbio.jsp?EID=16238)
Question originally posed by Dheeraj Bhatia (http://www.jguru.com/guru/viewbio.jsp?EID=14903
JFC supports robust and portable user interfaces. The Swing classes are robust, compatible with AWT, and provide you with a great deal of control over a user interface. Since source code is available, it is relatively easy to extend the JFC to do exactly what you need it to do. But the number of third-party controls written for Swing is still relatively small.
WFC runs only on the Windows (32-bit) user interface, and uses Microsoft extensions to Java for event handling and ActiveX integration. Because ActiveX components are available to WFC programs, there are theoretically more controls available for WFC than for JFC. In practice, however, most ActiveX vendors do not actively support WFC, so the number of controls available for WFC is probably smaller than for JFC. The WFC programming model is closely aligned with the Windows platform--it doesn't extend (or even interoperate with) AWT, so it feels more like programming with VB than with Java. Source code is not available, so you're on your own when extending the library.
In terms of functionality, WFC and JFC are similar: they both offer a similar range of controls, they both support clipboard and drag-n-drop operations, etc. WFC performance is better than JFC, and in general, memory requirements for WFC are lower than for JFC. For simple user interfaces, WFC is easy to develop with. For more complex user interfaces, WFC is more difficult than JFC. WFC was written with a component mindset: the details of any specific component are hidden within the component. JFC was written with an object-oriented mindset, providing a greater degree of control.
The bottom line is: If you need a robust, cross platform user interface, use JFC. If you're writing a quick and simple front-end, and if all of your clients are running Windows, and if you don't mind the Microsoft-specific extensions to Java, consider using WFC.
How can I display images in an TextArea?
Location: http://www.jguru.com/faq/view.jsp?EID=16251
Created: Feb 20, 2000
Modified: 2000-02-21 03:52:44.06
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Nelson Nazareth (http://www.jguru.com/guru/viewbio.jsp?EID=14700
AWT TextArea components only support displaying text. You cannot display images in them. If you don't mind using the Swing components, you can use either the JEditorPane or JTextPane to display images within text components.
How can I display Text strings of different style on different lines of an TextArea.
i.e I want Hello on first line as PLAIN String.
Hello World on second line as BOLD. or might be in different Color.
Location: http://www.jguru.com/faq/view.jsp?EID=16252
Created: Feb 20, 2000
Modified: 2000-02-21 03:53:26.393
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Nelson Nazareth (http://www.jguru.com/guru/viewbio.jsp?EID=14700
Comments and alternative answersThe AWT TextArea only supports displaying its text in a single color and single font. To display text in different styles, you can use the Swing JTextPane or JEditorPane (or create your own component).
| how safe is swing
Author: pradeep kumar (http://www.jguru.com/guru/viewbio.jsp?EID=503989), Dec 6, 2001 If I use swing component, would the applet run over internet without any problems. what I mean to ask is, if the user doesnt have swing component on their compuer, would the swing applet run OK> |
Where can I get information about writing a layout manager?
Location: http://www.jguru.com/faq/view.jsp?EID=16253
Created: Feb 20, 2000
Modified: 2000-02-21 03:54:39.06
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Alexey Lonshakov (http://www.jguru.com/guru/viewbio.jsp?EID=10550
Comments and alternative answersSun's online tutorial describes what you need to do to create a layout manager at http://java.sun.com/docs/books/tutorial/uiswing/layout/custom.html.
| writing a layout manager
Author: Ted Smith (http://www.jguru.com/guru/viewbio.jsp?EID=1300887), Jun 14, 2006 There is a good tutorial at http://netpea.com/129330.html. |
How do I overcome the 32K limit of TextArea?
Location: http://www.jguru.com/faq/view.jsp?EID=16267
Created: Feb 20, 2000
Modified: 2000-02-21 03:40:57.973
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
On Windows 95 machines, the AWT TextArea is limited to about 32K characters. This is a limitation of the underlying operating system. Since AWT components rely on native components, you cannot override this behavior from within Java. If you need larger text areas, you need to either convince your users to not use Windows 95 or use a component other than TextArea, like the Swing JTextArea, that doesn't have this limit.
How do I create multi-line labels in AWT / Swing?
Location: http://www.jguru.com/faq/view.jsp?EID=16550
Created: Feb 21, 2000
Modified: 2000-02-23 08:21:24.588
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersThe AWT Label does not support multiple lines on Label. You would need to create multiple Label components and place them in a Panel (or create your own component).
In Swing 1.1.1 and later, you can place HTML in your labels to get a multi-line label, as in
String htmlLabel = "<html><sup>HTML</sup> <sub><em>Label</em></sub><br>" + "<font color=\"#FF0080\"><u>Multi-line</u></font>"; JLabel label = new JLabel(htmlLabel);If you want to be able to use \n and \r to indicate new lines, you would need to define your own UI for the Swing component.
| Observation on use of html in JLabels: the JLabel ...
Author: Joseph Shelby (http://www.jguru.com/guru/viewbio.jsp?EID=26292), Mar 20, 2000 Observation on use of html in JLabels: the JLabel does cache the View object (javax.swing.text) that was created when first rendered, but rendering the view is still a time-consuming process. Using JLabels as graph nodes, with the html to support multi-line, I found that having more than, say, 20 nodes on the screen redrawing at each refresh to be dreadfully slow. |
How can I explicitly display a tooltip in AWT?
Location: http://www.jguru.com/faq/view.jsp?EID=17099
Created: Feb 23, 2000
Modified: 2000-12-27 08:55:58.195
Author: Christophe Caissotti (http://www.jguru.com/guru/viewbio.jsp?EID=17093)
Comments and alternative answersHere's some sample code that can display a tooltip in an AWT GUI.
Users can see information each time they move the mouse on a GUI. This little class displays tips given by a String. The String can include five Html tags: <br><b><i></i></b>
You can download the class file at http://www.chez.com/ccaissotti/components/tipProducer.java
To display a tip, just create a TipProducer with the String you want to show and call its draw() method.
For example
public void onMouseMove( MouseEvent me ) { tp = new tipProducer(); tp.setString("Click on the point<br>x=<b>" + me.getX() + "</b><br>y=<b>"+me.getY()+ "</b>" ); tp.draw(g, me.getX(), me.getY ); }
| Well, this is correct version. It works for applets...
Author: Predrag Mihailovic (http://www.jguru.com/guru/viewbio.jsp?EID=48205), Dec 11, 2000 Well, this is correct version. It works for applets and frames. Here is source code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ToolTip extends Canvas {
protected String tip;
protected Component owner;
private Container mainContainer;
private LayoutManager mainLayout;
private boolean shown;
private final int VERTICAL_OFFSET = 30;
private final int HORIZONTAL_ENLARGE = 10;
public ToolTip(String tip, Component owner) {
this.tip = tip;
this.owner = owner;
owner.addMouseListener(new MAdapter());
setBackground(new Color(255,255,220));
}
public void paint(Graphics g) {
g.drawRect(0,0,getSize().width -1, getSize().height -1);
g.drawString(tip, 3, getSize().height - 3);
}
private void addToolTip() {
mainContainer.setLayout(null);
FontMetrics fm = getFontMetrics(owner.getFont());
setSize(fm.stringWidth(tip) + HORIZONTAL_ENLARGE, fm.getHeight());
setLocation((owner.getLocationOnScreen().x - mainContainer.getLocationOnScreen().x) ,
(owner.getLocationOnScreen().y - mainContainer.getLocationOnScreen().y + VERTICAL_OFFSET));
// correction, whole tool tip must be visible
if (mainContainer.getSize().width < ( getLocation().x + getSize().width )) {
setLocation(mainContainer.getSize().width - getSize().width, getLocation().y);
}
mainContainer.add(this, 0);
mainContainer.validate();
repaint();
shown = true;
}
private void removeToolTip() {
if (shown) {
mainContainer.remove(0);
mainContainer.setLayout(mainLayout);
mainContainer.validate();
}
shown = false;
}
private void findMainContainer() {
Container parent = owner.getParent();
while (true) {
if ((parent instanceof Applet) || (parent instanceof Frame)) {
mainContainer = parent;
break;
} else {
parent = parent.getParent();
}
}
mainLayout = mainContainer.getLayout();
}
class MAdapter extends MouseAdapter {
public void mouseEntered(MouseEvent me) {
findMainContainer();
addToolTip();
}
public void mouseExited(MouseEvent me) {
removeToolTip();
}
public void mousePressed(MouseEvent me) {
removeToolTip();
}
}
}
And code for testing:
import java.awt.*;
import java.awt.event.*;
public class ToolTipTest extends java.applet.Applet {
private Label myLabel;
private Button myButton;
private TextField myTextField;
public void init() {
myLabel = new Label("Hello world!");
new ToolTip("I say: Hello world!", myLabel);
myButton = new Button("Press");
new ToolTip("It's working !", myButton);
myTextField = new TextField(10);
new ToolTip("Tip for this field", myTextField);
add(myLabel);
add(myButton);
add(myTextField);
}
}
|
| Re: Well, this is correct version. It works for applets...
Author: Rajesh Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=546959), Nov 14, 2001 Thankyou VeryMuch This is working Fine Yours Rajesh |
| Re: Well, this is correct version. It works for applets...
Author: Marco Laponder (http://www.jguru.com/guru/viewbio.jsp?EID=706723), Jan 2, 2002 It looks very good on windows as well for Netscape as for Explorer but for Linux the tooltip is not shown. Anybody has an idea why or how to solve this ? Marco Laponder (mlr@interchain.nl) |
| Re[2]: Well, this is correct version. It works for applets...
Author: Trond Albinussen (http://www.jguru.com/guru/viewbio.jsp?EID=1069471), Mar 24, 2003 HI. I hope someone is watching this... The code above from Predrag Mihailovic is working up to java1.3.-b24. With java1.4.1_01-b01 the applet hangs. The code works fine on all platforms and OS, but not with 1.4.1. No error messages, not even with try-catch(Exception e) on every block of code. Can anybody help please? |
| Re[3]: Well, this is correct version. It works for applets...
Author: Slobodan Marinkovic (http://www.jguru.com/guru/viewbio.jsp?EID=1177388), Jun 9, 2004 There is a bug in newer JDKs, in Container's add method. Try this workaround;
private void addToolTip() {
....
....
setVisible(false); //<- added
mainContainer.add(this, 0);
setVisible(true); //<- added
mainContainer.validate();
repaint();
shown = true;
}
|
| Re: Well, this is correct version. It works for applets...
Author: Alan Walker (http://www.jguru.com/guru/viewbio.jsp?EID=1214567), Dec 4, 2004 Works well for me!
If you want your tool tip to appear just below the mouse pointer, you can add two arguments to the addToolTip method: (int xPos, int yPos). Then change the setLocation call to this:
Finally, change the call to addToolTip in the mAdapter class:
|
How can I iconify/deiconify my Frame/JFrame?
Location: http://www.jguru.com/faq/view.jsp?EID=17415
Created: Feb 23, 2000
Modified: 2000-02-25 06:09:05.032
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersThe setState() method introduced to Java 1.2 provides support for iconifying and deiconifying.
frame.setState(Frame.ICONIFIED); frame.setState(Frame.NORMAL);
| OK -- but how to do it within swing 1.1.x ?
Is pr...
Author: Thomas SMETS (http://www.jguru.com/guru/viewbio.jsp?EID=20729), Jul 3, 2000 OK -- but how to do it within swing 1.1.x ?
|
How do I maximize a Frame/JFrame ?
Location: http://www.jguru.com/faq/view.jsp?EID=17416
Created: Feb 23, 2000
Modified: 2000-02-25 06:11:51.009
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
Comments and alternative answersThere is no direct support for this. The best you can do is make sure the frame is deiconified then set its size to the screen size.
frame.setState(Frame.NORMAL); Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension dimension = toolkit.getScreenSize(); frame.setSize(dimension);[FAQ Manager Note] The operating system will not treat this as a maximized frame, so in general this is not a good idea for simulating maximize. I'd recommend that you only set the state to NORMAL to ensure the window is visible (not minimized/iconified) and allow the user to press the maximize button if they want.
| One can set the size to a size slightly larger
than...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Mar 17, 2001 One can set the size to a size slightly larger than the one returned by toolkit.getScreenSize() and location of say -2, -2 so that the resize handles are not accesible achieving a closer approximation of maximized state. One might have to experiment a little more to get it right. |
| sure you can.
Author: Rui Pereira (http://www.jguru.com/guru/viewbio.jsp?EID=1145862), Feb 12, 2004 try this: frame.setVisible(true); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); |
| This code does not work perfectly
Author: Rajibul Islam (http://www.jguru.com/guru/viewbio.jsp?EID=1224860), Feb 2, 2005 this following code place in the constructor addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } public void windowOpened(WindowEvent e) { setExtendedState(MAXIMIZED_BOTH); // Load the main window in a maximize state } } );
then every frame load maximize |
| u can use this code
Author: haitham el-fenawy (http://www.jguru.com/guru/viewbio.jsp?EID=1204922), Oct 12, 2004 Toolkit kit = myFrame.getToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
Dimension windowSize = myFrame.getSize();
int windowWidth = windowSize.width;
int windowHeight = windowSize.height;
int X = (screenWidth - windowWidth)/2;
int Y = (screenHeight - windowHeight)/2;
myFrame.setLocation(X, Y);
with my best wishes Eng. Hiatham
|
| Re: u can use this code
Author: Neha Agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=1378157), Feb 26, 2009 I have a problem in the same lines with this, my project which earlier was in 1.4 and now in 1.6 does not have minimize and maximize buttons on the title bar of the JFrame. Earlier when it was in java 1.4 the buttons were visible, and now they are not present. Are there any classes/methods that are depricated which are causing this? How do i fix it? Please advice |
How can I make a TextField accept and display ASCII characters like the smiley?
Location: http://www.jguru.com/faq/view.jsp?EID=17637
Created: Feb 24, 2000
Modified: 2000-02-25 06:15:34.315
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by lyndon mendoza (http://www.jguru.com/guru/viewbio.jsp?EID=8369
Comments and alternative answersJava uses the Unicode character encodings. While 0-127 map directly from Unicode to ASCII, how they display may appear different. For instance, while \u0001 might appear as a smiley face under ASCII, the smiley face isn't in the Unicode code chart. You can use the UnicodeDisplay example from Java Examples in a Nutshell (http://www.oreilly.com/catalog/jenut/examples/UnicodeDisplay.java) to see exactly what characters are available for display.
|
Actually it depends on the character code and the
font...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Mar 17, 2001 Actually it depends on the character code and the font chosen to display it. For a given font a specific char code may map to the smily char. However some fonts may not even have a glyph corresponding to the given char code and you will most likely see a filled rectangle in the place of the char. Please look at the following apis for more details
of char code to glyph mapping etc.
http://java.sun.com/products/jdk/1.2/docs/api/java/awt/Font.html |
How do I read an Image from a JAR file with Netscape browsers?
Location: http://www.jguru.com/faq/view.jsp?EID=17781
Created: Feb 24, 2000
Modified: 2000-09-14 07:41:44.11
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The Communicator 4.x browsers do not implement the Class.getResource(), ClassLoader.getResource(), and ClassLoader.getSystemResource() methods. You need to use the Class.getResourceAsStream(), ClassLoader.getResourceAsStream(), or ClassLoader.getSystemResourceAsStream() methods instead, respectively. See http://developer.netscape.com/docs/technote/java/getresource/getresource.html for more information.With that said, the following will load an Image:
InputStream in = getClass().getResourceAsStream("image.gif"); byte buffer[] = new byte[in.available()]; in.read(buffer); Image image = Toolkit.getDefaultToolkit().createImage(buffer);
How do I get FilenameFilter to work on my FileDialog?
Location: http://www.jguru.com/faq/view.jsp?EID=17853
Created: Feb 24, 2000
Modified: 2001-08-20 11:00:38.007
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Basically, it doesn't work on Windows machines.
The JFileDialog provides a better alternative that supports filters, if you can use the Swing component set.
See Bug 4031440 for more information: http://developer.java.sun.com/developer/bugParade/bugs/4031440.html.
How can I embed small images into the .class file that uses them so that I don't have to download so many separate files?
Location: http://www.jguru.com/faq/view.jsp?EID=19095
Created: Feb 28, 2000
Modified: 2000-03-06 19:32:03.314
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
Comments and alternative answersTry to follow the strategy followed by the javax.swing.Icon interface. Read all about it at http://java.sun.com/products/jdk/1.2/docs/api/javax/swing/Icon.html
You can use something like this -
private static class MenuArrowIcon implements Icon, UIResource, Serializable { : : : } // End class MenuArrowIconfrom the
javax/swing/plaf/basic/BasicIconFactory.javaYou can initialize an int array and use either
java.awt.image.MemoryImageSourcehttp://java.sun.com/products/jdk/1.2/docs/api/java/awt/image/MemoryImageSource.html
java.awt.image.BufferedImagehttp://java.sun.com/products/jdk/1.2/docs/api/java/awt/image/BufferedImage.html
| Alternative for storing image files
Author: Rahi Parsi (http://www.jguru.com/guru/viewbio.jsp?EID=484157), Oct 20, 2001
You can store the image(s) in a jar file along with the class files. For example:
|
When I fill a Choice with more than 30000 Strings, why doesn't it show all of them?
Location: http://www.jguru.com/faq/view.jsp?EID=20513
Created: Mar 5, 2000
Modified: 2000-03-06 19:52:22.899
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Mayur Adatia (http://www.jguru.com/guru/viewbio.jsp?EID=14325
The AWT Choice component is limited to the capabilities of the associated native control of the user's platform. Sounds like it has a 32K limit for your platform.
As a user, I would hate the user interface if I was expected to pick something from over 30,000 choices. You might consider designing an interface that limited the number of options to something a little more reasonable.
How do I make sure an Image is loaded before I try to display it?
Location: http://www.jguru.com/faq/view.jsp?EID=20617
Created: Mar 6, 2000
Modified: 2000-03-06 19:53:11.004
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersYou can use the AWT MediaTracker to start and wait for the loading of an Image object.
Image image = ...; MediaTracker tracker = new MediaTracker(component or this); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { System.out.println("Interrupted while loading Image"); }At this point, if everything went okay, the image would be loaded. You can check the status with statusAll() or statusID() to see if they loaded successfully.
| To load a file from disk, the "..." must...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 17, 2000 To load a file from disk, the "..." must be replaced with something like getToolkit().getImage(file) as below:
static Frame frame;
public static Frame getFrame() {
if (frame == null) {
frame = new Frame();
frame.addNotify(); // create peer
}
return frame;
}
static Toolkit toolkit;
/**
* Get a default toolkit. Uses a dummy frame, so we can use this
* toolkit to make a valid offscreen buffer. Note that this buffer
* will only be as deep, pixel-wise, as the current screen
* resolution.
**/
public static Toolkit getToolkit() {
if (toolkit == null) {
// create the dummy frame, from which we get a peer, so we can
// make a valid offscreen buffer (AWT sucks)
toolkit = getFrame.getToolkit();
}
return toolkit;
}
public Image loadImage(String file) throws IOException
{
Image i = getToolkit().getImage(file);
// wait for it to load
MediaTracker mt = new MediaTracker(frame);
mt.addImage(i, 0);
try {
mt.waitForID(0);
}
catch (InterruptedException e2)
{
}
if (mt.isErrorID(0))
{
throw new IOException("Error loading image: " + file);
}
}
|
| Re: To load a file from disk, the "..." must...
Author: Varun Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=482944), Aug 24, 2001 I tried the code given by you. it works fine but in the end control does not returns to the calling function. i used system.exit(0) then it returns but i need to return value to the calling function. How do i do it? Thanks in advance... |
| ImageInfo
Author: martin harm (http://www.jguru.com/guru/viewbio.jsp?EID=1023679), Nov 10, 2002 see http://www.geocities.com/marcoschmidt.geo/image-info.html very nice, small, fast and without using any toolkit... and PublicDomain |
How can I control the Z-order that my overlapping components are drawn in?
Location: http://www.jguru.com/faq/view.jsp?EID=21482
Created: Mar 7, 2000
Modified: 2000-03-13 04:10:50.335
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersAWT does not define z-order behavior. In fact, it is different on different platforms. You would need to draw all the components yourself, instead of relying on the Container to do this for you.
If you are using Swing, you can place your components inside a JLayeredPane and assign each a layer number. Higher layer numbers appear on top of lower layer numbers. (Note that JDesktopPane is a layered pane; each JInternalFrame can be at different layers.)
| z-order can be changed in AWT !
Author: Rudi Vaum (http://www.jguru.com/guru/viewbio.jsp?EID=1166967), Apr 29, 2004 According to the API specification of java.awt.Container, you can set a z-order: .... public abstract class Container extends Component A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order). ..... |
How can I set multiple lines of text in a Button?
Location: http://www.jguru.com/faq/view.jsp?EID=21664
Created: Mar 8, 2000
Modified: 2000-03-13 04:17:49.02
Author: MAHESH MULCHANDANI (http://www.jguru.com/guru/viewbio.jsp?EID=18395)
Question originally posed by Belgundi Achyuth Acharya (http://www.jguru.com/guru/viewbio.jsp?EID=20249
Comments and alternative answersThere is no way to set Multiple Lines of Text in an AWT button. If you try to attach a label whose length is more than the width of button it is trimmed on both sides.
You can have multi-line Buttons in Swing, however. The latest version of Swing allows you to specify the button text using HTML, and you can add <br> tags inside the HTML (as well as tags such as <b> and <i>)
| can you give an example ?
Author: sam pitroda (http://www.jguru.com/guru/viewbio.jsp?EID=476938), Sep 12, 2001 A |
| Re: can you give an example ?
Author: rahulsale saley (http://www.jguru.com/guru/viewbio.jsp?EID=997073), Sep 10, 2002 Hi Sam, Hope this will help you. <! --I have commented this so you can read it properly //jbNewUser.setText("<html> |
How do I create a TextField that limits the number of characters a user can place in it?
Location: http://www.jguru.com/faq/view.jsp?EID=23148
Created: Mar 11, 2000
Modified: 2000-08-03 18:04:43.645
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersTo limit the number of characters a user can type into the AWT TextField, you need to watch as the user types and count characters. If the size gets too large, you reject input. You need to still permit characters like TAB for moving focus as well as Backspace/Delete for removing characters. The following program demonstrates this.
import java.awt.*; import java.awt.event.*; public class SizedTextField extends TextField { private int size; // size = 0 is unlimited public SizedTextField () { super(""); this.size = 0; init(); } public SizedTextField (int columns) { super(columns); this.size = 0; init(); } public SizedTextField (int columns, int size) { super (columns); this.size = Math.max (0, size); init(); } public SizedTextField (String text) { super(text); this.size = 0; init(); } public SizedTextField (String text, int columns) { super(text, columns); this.size = 0; init(); } public SizedTextField (String text, int columns, int size) { super(text, columns); this.size = Math.max (0, size); init(); } private void init() { KeyListener listener = new KeyAdapter() { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((size > 0) && (((TextField)(e.getComponent())).getText().length () >= size)) { // Check for backspace / delete / tab -- let these pass through if ((key == KeyEvent.VK_DELETE) || (key == KeyEvent.VK_TAB) || (key == KeyEvent.VK_BACK_SPACE)) { return; } else { e.consume(); } } } }; addKeyListener(listener); } protected String paramString () { String str = super.paramString (); if (size != 0) { str += ",size=" + size; } return str; } public static void main(String args[]) { Frame f = new Frame("Test"); TextField tf1 = new TextField(); TextField tf2 = new SizedTextField(10, 10); f.add(tf1, BorderLayout.NORTH); f.add(tf2, BorderLayout.SOUTH); f.pack(); f.show(); } }A note of caution. This does not limit you as a programmer from saying setText() with some really long string.
| Add a java.awt.event.TextListener on the text field....
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Apr 4, 2000 Add a java.awt.event.TextListener on the text field. Then in the callback do -
public void textValueChanged(TextEvent e) {
TextField tf = (TextField ) e.getSource();
if (tf.getText().trim().length() > THRESHOLD) {
tf.setText(tf.getText().trim().substring(0, THRESHOLD);
Toolkit.getDefaultToolkit().beep();
}
}
You have to use the TextListener rather than KeyListener so that -
|
How can I keep a PopupMenu/JPopupMenu visible after I select one of its menu items?
Location: http://www.jguru.com/faq/view.jsp?EID=23340
Created: Mar 12, 2000
Modified: 2000-03-14 10:57:10.822
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
This is basically what is called a tearoff menu. You would need to simulate the behavior by putting the top level set of menu choices within a Window, providing some way for the user to close the window.
How do I create Menus which are loaded based upon user authentication?
Location: http://www.jguru.com/faq/view.jsp?EID=23341
Created: Mar 12, 2000
Modified: 2000-03-14 10:58:05.886
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Vinay Solanke (http://www.jguru.com/guru/viewbio.jsp?EID=12334
The JFC Notepad demo that comes with the JDK demonstrates how to load menus dymanically. You can setup different locales to define different authorization levels.
How can I find the center of a circle drawn using Graphics.drawArc()?
Location: http://www.jguru.com/faq/view.jsp?EID=23344
Created: Mar 12, 2000
Modified: 2000-03-18 15:24:02.965
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Thomas K Jacob (http://www.jguru.com/guru/viewbio.jsp?EID=16991
The drawArc() method has six arguments: the x and y coordinates of the top left corner, the width and height, as well as the start and ending angle positions. To get the center point, all you need is four of them. The width of the circle is from x to x+width-1. The height of the circle is from y to y+height-1. Thus, the center point would be x+(width-1)/2, y+(height-1)/2.
The minus one is necessary because a starting pixel is at x (or y). This is just like arrays where a 100 element array is indexed from 0 to 99.
How do I print a multi-page text document?
Location: http://www.jguru.com/faq/view.jsp?EID=23346
Created: Mar 12, 2000
Modified: 2000-03-16 07:54:51.412
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
For Java 1.1, the following program will demonstrate the printing of multi-page documents.
// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski. Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Properties;
public class TestPrint extends Frame {
TextArea textArea;
Label statusInfo;
Button loadButton, printButton, closeButton;
Properties props = new Properties();
public TestPrint() {
super ("File Loader");
add (statusInfo = new Label(), "North");
Panel p = new Panel ();
p.add (loadButton = new Button ("Load"));
loadButton.addActionListener( new LoadFileCommand() );
p.add (printButton = new Button ("Print"));
printButton.addActionListener( new PrintCommand() );
p.add (closeButton = new Button ("Close"));
closeButton.addActionListener( new CloseCommand() );
add (p, "South");
add (textArea = new TextArea (10, 40), "Center");
pack();
}
public static void main (String args[]) {
TestPrint f = new TestPrint();
f.show();
}
// Bail Out
class CloseCommand implements ActionListener {
public void actionPerformed (ActionEvent e) {
System.exit (0);
}
}
// Load a file into the text area.
class LoadFileCommand implements ActionListener {
public void actionPerformed (ActionEvent e) {
int state;
String msg;
FileDialog file = new FileDialog (TestPrint.this, "Load File", FileDialog.LOAD);
file.setFile ("*.java"); // Set initial filename filter
file.show(); // Blocks
String curFile;
if ((curFile = file.getFile()) != null) {
String filename = file.getDirectory() + curFile;
char[] data;
setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
File f = new File (filename);
try {
FileReader fin = new FileReader (f);
int filesize = (int)f.length();
data = new char[filesize];
fin.read (data, 0, filesize);
} catch (FileNotFoundException exc) {
String errorString = "File Not Found: " + filename;
data = errorString.toCharArray ();
} catch (IOException exc) {
String errorString = "IOException: " + filename;
data = errorString.toCharArray ();
}
statusInfo.setText ("Load: " + filename);
textArea.setText (new String (data));
setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
}
// Print a file into the text area.
class PrintCommand implements ActionListener {
public void actionPerformed (ActionEvent e) {
PrintJob pjob = getToolkit().getPrintJob(TestPrint.this, "Cool Stuff", props);
if (pjob != null) {
Graphics pg = pjob.getGraphics();
if (pg != null) {
String s = textArea.getText();
printLongString (pjob, pg, s);
pg.dispose();
}
pjob.end();
}
}
}
// Print string to graphics via printjob
// Does not deal with word wrap or tabs
void printLongString (PrintJob pjob, Graphics pg, String s) {
int pageNum = 1;
int linesForThisPage = 0;
int linesForThisJob = 0;
// Note: String is immutable so won't change while printing.
if (!(pg instanceof PrintGraphics)) {
throw new IllegalArgumentException ("Graphics context not PrintGraphics");
}
StringReader sr = new StringReader (s);
LineNumberReader lnr = new LineNumberReader (sr);
String nextLine;
int pageHeight = pjob.getPageDimension().height;
Font helv = new Font("Helvetica", Font.PLAIN, 12);
//have to set the font to get any output
pg.setFont (helv);
FontMetrics fm = pg.getFontMetrics(helv);
int fontHeight = fm.getHeight();
int fontDescent = fm.getDescent();
int curHeight = 0;
try {
do {
nextLine = lnr.readLine();
if (nextLine != null) {
if ((curHeight + fontHeight) > pageHeight) {
// New Page
System.out.println ("" + linesForThisPage + " lines printed for page " +
pageNum);
pageNum++;
linesForThisPage = 0;
pg.dispose();
pg = pjob.getGraphics();
if (pg != null) {
pg.setFont (helv);
}
curHeight = 0;
}
curHeight += fontHeight;
if (pg != null) {
pg.drawString (nextLine, 0, curHeight - fontDescent);
linesForThisPage++;
linesForThisJob++;
} else {
System.out.println ("pg null");
}
}
} while (nextLine != null);
} catch (EOFException eof) {
// Fine, ignore
} catch (Throwable t) { // Anything else
t.printStackTrace();
}
System.out.println ("" + linesForThisPage + " lines printed for page " + pageNum);
System.out.println ("pages printed: " + pageNum);
System.out.println ("total lines printed: " + linesForThisJob);
}
}
Comments and alternative answers
| string not printed
Author: vaidehi gudipaty (http://www.jguru.com/guru/viewbio.jsp?EID=433963), Jun 5, 2001 When Iam trying to load one of my files and print it using this code, only blank pages are printed.String is not printing. What could be the problem? |
| printing a multi-page text document
Author: Laura Manias (http://www.jguru.com/guru/viewbio.jsp?EID=773907), Feb 27, 2002 I have a jtextarea and i would like to print its content. In jtextarea I set line wrapping and I would like it count the lines wrapped and not the /n . How ca I do? |
| Re: printing a multi-page text document
Author: Santosh M (http://www.jguru.com/guru/viewbio.jsp?EID=1151825), Jun 11, 2004 Use the Smart JPrint APIs that is available for free. In about a minue you should be able to print, preview, optionally PDF generate your Java programs and Swing component (JTextArea) content. Lok at the online demo: http://www.activetree.com. Try the online demo to print, preview, and generate PDF online right now. About Smart JPrint? Smart JPrint is a pure Java class library used for the following:
Features
|
| Re[2]: printing a multi-page text document
Author: Larry Brown (http://www.jguru.com/guru/viewbio.jsp?EID=1243403), May 10, 2005 The Java Print Dialog Framework (JPDF) is a product which provides the ability to print any Swing component (JTable, JTree, JTextPane, and so on). It provides Page Setup dialogs specific to the type of component you need to print. Print preview dialogs are also included. If your application requires printing Swing Components, then this product will provide you with everything you need for your printing capability. It is easily integrated into your application, with a mimimum amount of custom coding required. The JPDF is available for sale at
http://www.softframeworks.com. A free Demo application is available. |
Why should I call repaint() instead of paint()?
Location: http://www.jguru.com/faq/view.jsp?EID=23379
Created: Mar 12, 2000
Modified: 2000-03-16 08:00:51.022
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by sailesh patra (http://www.jguru.com/guru/viewbio.jsp?EID=18223
repaint() enqueues a paint message onto the system's event queue. Later (in another thread) the AWT system will dequeue this message and dispatch it. One of the (many) things it does is call the paint() or update() method of the component. If you directly call paint() yourself, you'll run in to the following issues:
- You lose serial paint processing
By doing painting in any old thread you're calling graphics primitives on the same compoent in one thread while the system event thread is potentially calling on the same component them in another thread.
Thus you run into reentrancy issues in your own code and in AWT, race conditions between your own threads and you greatly increase the probability of lock contention for internal AWT resources, which will be to the detriment of performance. A well-behaved AWT programming does all of its actual painting to real components in response to paint events, inside the system's event handler thread.- You lose paint event elision
The AWT internals contain code that looks for damage/paint events that overlap each other, and tries to glue them together into one big event, which is much more efficient. By circumventing this mechanism you may, in some applications, be unnecessarily repainting the same area of the screen a bunch of times - an AWT that doesn't elide paint events runs much slower in a lot of circumstances.- You lose native notification
By calling repaint() you ensure that the native paint code for the component is called. Just calling paint() yourself stops this from happening - which might cause you problems if you expect the native to be properly painted too.- You're breaking the pattern
From a software-engineering stand-point, you're breaking with the general AWT repaint paradigm. This would be okay if you were gaining some advantage from doing so, but you aren't, so you're unnecessarily making your code less maintainable, harder for others to understand and less reusable.
How can I get the current mouse coordinates while
handling a KeyEvent in a keyPressed(KeyEvent) method?
Location: http://www.jguru.com/faq/view.jsp?EID=23383
Created: Mar 12, 2000
Modified: 2000-03-16 08:33:54.893
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Nils-Gunnar Nilsson (http://www.jguru.com/guru/viewbio.jsp?EID=3199
The KeyEvent doesn't contain that information, but you can do the following:
- Add both a KeyListener and a MouseMotionListener to the component you're interested in.
- In the mouseMoved() callback, store the MouseEvent in an instance variable.
- In the keyPressed() callback, get the last reported location of the mousepointer by calling getPoint() on that MouseEvent you stored.
This will work fine unless you need accurate performance in applications where the mouse is likely to be moving when the key is pressed (e.g. video games) - in which case you'll probably find that the reported mouse position appears to 'lag' the actual mouse pointer.
Can I make setBackground() a Transparent Color?
Location: http://www.jguru.com/faq/view.jsp?EID=23387
Created: Mar 12, 2000
Modified: 2000-03-18 15:24:46.546
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Darren Dunkley-Smith (http://www.jguru.com/guru/viewbio.jsp?EID=16106
In Java2, sure, the AWT contains a constructor for java.awt.Color that takes an alpha (transparency) value - just set this to 0.
Java 1.1.x doesn't support this, so you can't have a transparent background color.
Can I draw rotated text, without using the Java2D API?
Location: http://www.jguru.com/faq/view.jsp?EID=23388
Created: Mar 12, 2000
Modified: 2000-03-18 15:25:29.131
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
No, not really.
The only thing you can do is use the regular AWT graphics code to draw into an offscreen image - and then you can rotate the offscreen image yourself - doing so for 90 degree rotations is pretty easy, but for other angles its not so much fun.
How do you eliminate widgets that don't have a traversable property from the tabbing sequence, so that some components on a panel never receive the focus from the tab key?
Location: http://www.jguru.com/faq/view.jsp?EID=23389
Created: Mar 12, 2000
Modified: 2000-03-18 15:26:10.27
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Greg Joyce (http://www.jguru.com/guru/viewbio.jsp?EID=15123
Override the isFocusTraversible() method (from java.awt.Component) and always return false.
What is double buffering?
Location: http://www.jguru.com/faq/view.jsp?EID=23392
Created: Mar 12, 2000
Modified: 2000-03-18 21:13:33.136
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
Comments and alternative answersDouble-buffering is a technique to reduce flickering in drawing, particularly in animation.
Instead of drawing directly onto the component (in the paint or update method) you create an offscreen image (using component.createImage) and paint your picture into that. Once you're done you actualise the image by painting it onto the graphics context of an actual component - thus there isn't a time when your image can be seen half-drawn.
| Double Buffering
Author: Ajit B (http://www.jguru.com/guru/viewbio.jsp?EID=506896), Sep 29, 2001 so isn't it like Double buffering actually slows down the performance coz it need to handle additional task of creating image, though it gives user the feeling of faster loading n avoids flickering???...........Ajit |
How do I create a window-less frame to put my applet (applet only no borders)? or is that possible?
Location: http://www.jguru.com/faq/view.jsp?EID=23782
Created: Mar 13, 2000
Modified: 2001-10-29 22:18:38.807
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Zhi Shen (http://www.jguru.com/guru/viewbio.jsp?EID=21324
Anything you do like this would not be from Java. You should be able to do this with JavaScript. http://plutoniumsoftware.com/games/bm3d/ does something similar to what you want, but not exactly.Note: the question is not about creating an undecorated frame from an applet. It is to load the applet into an undecorated browser window.
How do I show diagrams and graphs?
Location: http://www.jguru.com/faq/view.jsp?EID=25795
Created: Mar 18, 2000
Modified: 2000-03-19 06:33:44.986
Author: Anil Punjabi (http://www.jguru.com/guru/viewbio.jsp?EID=23218)
Question originally posed by Kristijan Marin (http://www.jguru.com/guru/viewbio.jsp?EID=15063
Comments and alternative answersYou can try JLoox athttp://www.loox.com
There are several other packages available as well. Try searching for "java chart" on the web
[FAQ Manager Note: If you would like to recommend other specific tools, please submit a feedback!]
| You can also try JFreeChart at http://www.jrefiner...
Author: David Gilbert (http://www.jguru.com/guru/viewbio.jsp?EID=19371), Nov 11, 2000 You can also try JFreeChart at http://www.jrefinery.com. It's free and includes all source code under the terms of the GNU Lesser General Public Licence. |
| Re: You can also try JFreeChart at...
Author: David Gilbert (http://www.jguru.com/guru/viewbio.jsp?EID=19371), Apr 7, 2002 JFreeChart has moved to: http://www.object-refinery.com/jfreechart/ Regards,
Dave Gilbert |
| Plotting Graphs using Java
Author: sarikonda venumadhav (http://www.jguru.com/guru/viewbio.jsp?EID=453588), Jul 11, 2001 I dont want to use a tool but code in Java and fetch the data from database. Any ideas? |
| Re: Plotting Graphs using Java
Author: timm coerrens (http://www.jguru.com/guru/viewbio.jsp?EID=380894), Aug 27, 2001 Hi, i am doin it with a servlet, that generates image/jpeg as output. you can draw into it with some data from the database. you find code on this page. hope this helps |
| Re: Re: Plotting Graphs using Java
Author: VENU MADHAV (http://www.jguru.com/guru/viewbio.jsp?EID=500472), Sep 20, 2001 Hi Timm I want to know how to print out the image/jpeg after creating them... I am using servlets and am able to generate the graphs but now I have to print them on paper.... any ideas??? Thanx for ur response... Venu Madhav Sarikonda.... |
| Re: Re: Re: Plotting Graphs using Java
Author: timm coerrens (http://www.jguru.com/guru/viewbio.jsp?EID=380894), Sep 20, 2001 HI, in the end i realize the output as a 'printable' page without backgroundcolor etc. The image created can be saved with rightclick 'save picture'. Then you can paste it into a program like photoshop. Or do you want the image to be printed directly from the page? greetinx Timm |
| Re[2]: Plotting Graphs using Java
Author: M N (http://www.jguru.com/guru/viewbio.jsp?EID=1214752), Dec 6, 2004 Can u please help me by sending the code to generate the graph using database datas & JSP(servlets). thanks in advance |
| Re[3]: Plotting Graphs using Java
Author: Keshri Nandan Chaudhary (http://www.jguru.com/guru/viewbio.jsp?EID=1320485), Nov 27, 2006 Hi If you have received the code for showing the graphs and charts, can you please send me the same, i am in dire need of it. Thnx a lot KNC |
| Re[2]: Plotting Graphs using Java
Author: deepti singh (http://www.jguru.com/guru/viewbio.jsp?EID=1240062), Apr 21, 2005 will you please provide me the code and settings to be made on tomcat |
| Try JGraph at http://www.jgraph.com
Author: Gaudenz Alder (http://www.jguru.com/guru/viewbio.jsp?EID=491811), Sep 6, 2001 JGraph is well suited to visualize graphs with Swing. Have a look at Graphpad, a demo application which uses JGraph. Visit the website at http://www.jgraph.com. |
| RChart
Author: Jaume Ba (http://www.jguru.com/guru/viewbio.jsp?EID=827369), Jul 9, 2002 See also RChart at http://www.java4less.com/charts_e.htm it works as servlet, applet or bean, and has a visual designer |
How do I draw in an off-screen image?
Location: http://www.jguru.com/faq/view.jsp?EID=25812
Created: Mar 18, 2000
Modified: 2000-03-19 06:36:51.274
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Jean-Yves BRUD (http://www.jguru.com/guru/viewbio.jsp?EID=8908
After you've created the offscreen image, you can draw into it by getting the appropriate Graphics object, which you get by calling getGraphics on the offscreen image. Here's a basic example:
Canvas c = new Canvas(); Image i = c.createImage(10, 10); // create offscreen image Graphics g = i.getGraphics(); g.drawRect(0,1,2,3); // draw into the offscreen image
How can I determine the color of a pixel displayed in a GUI?
Location: http://www.jguru.com/faq/view.jsp?EID=25973
Created: Mar 19, 2000
Modified: 2000-03-20 14:15:45.512
Author: Andre van Dalen (http://www.jguru.com/guru/viewbio.jsp?EID=7570)
Question originally posed by Jean-Yves BRUD (http://www.jguru.com/guru/viewbio.jsp?EID=8908
If you use double buffering, your question comes down to how to determine the pixel color in the image you use to paint to the screen. You can use the PixelGrabber class to tranform (part of) your Image into an
int[]and read the pixel color from that.If you want to determine the color of a pixel on the screen, you need to use JNI to call a C++ routine that retrieves pixels from the screen.
[FAQ Manager note: Double Buffering refers to drawing to an alternate, offscreen image before dumping that image to the screen.]
What are the issues in using Swing along with AWT?
Location: http://www.jguru.com/faq/view.jsp?EID=26294
Created: Mar 20, 2000
Modified: 2000-03-20 14:24:15.235
Author: Joseph Shelby (http://www.jguru.com/guru/viewbio.jsp?EID=26292)
Question originally posed by Chakree Chakree (http://www.jguru.com/guru/viewbio.jsp?EID=22927
Comments and alternative answersThe article Mixing Heavyweights at the Swing Connection from Javasoft has details on what caveats you need to be aware of in mixing Heavy and Light components together.
| more wants..
Author: bhakti ratna (http://www.jguru.com/guru/viewbio.jsp?EID=1253295), Jul 20, 2005 It is helpful but i need more about mixing concepts and disadvantage and advantages of mixing, what basically shd do? |
How can I display a modal Dialog from an applet in the Browser?
Location: http://www.jguru.com/faq/view.jsp?EID=27423
Created: Mar 22, 2000
Modified: 2001-07-26 21:11:51.245
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Rajesh Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=26470
In order to display a Dialog, you need a Frame to be the "owner" of the dialog - all of the java.awt.Dialog constructors require a Frame. Now, I've seen several "teach yourself java" books that say you should make a dummy Frame, and then pass that in as the parent - but that's plain silly.Comments and alternative answersWhat you need to do is walk up the AWT widget instance heirarchy (walking upward from the applet) - at the top of such heirarchies you'll find a Window, a Dialog or a Frame (the three "toplevel" widgets in AWT) - thoughtfully the applet host code will always set itself up as a Frame, just so you can use that as a parent for your dialogs. This walkup procedure is shown in the following example - it's done in the findParentFrame() method.
import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class test extends Applet implements ActionListener { Button b; private Frame findParentFrame(){ Container c = this; while(c != null){ if (c instanceof Frame) return (Frame)c; c = c.getParent(); } return (Frame)null; } public void init(){ setLayout(new FlowLayout()); b = new Button("push me"); b.addActionListener(this); add(b); } public void actionPerformed(ActionEvent e){ Frame f = findParentFrame(); if(f != null){ Dialog d = new Dialog(f, "modalDialog", true); d.setLayout(new FlowLayout()); d.add(new Label("hello")); d.pack(); d.setLocation(100,100); d.show(); } } }So that's that, right?
Well, not entirely. As with many aspects of their implementation of Java applets, browsers differ in how they interpret the meaning of "modal". Almost all make the dialog modal with respect to the applet that created it, but some make it fully modal (i.e. the entire browser is waiting on the modal dialog) and others allow other browser windows or even the same browser window (perhaps with other Java applets in it) to continue to run. This seems to happen more because of the way browser vendors implement the event handling loops in their products than by deliberate design (one major browser manufacturer we could name varies in this regard between the same browser on different OSes). Short of scary JavaScript/LiveConnect/JNI nastiness, you'll have to live with your browser manufacturer's conception of how to implement modal.
For browser manufacturers, ignoring modal behaviour for applets is often a wise choice - otherwise, malicious or defective applets (um, like my example above) can bring up a modal dialog with no means of it being closed, and thus leave the entire browser unusable - forcing the user to kill the browser to recover.
Another small note about modal dialogs - if you intend your applet to work on Personal Java platforms (things like cable-boxes and webphones) you should assume that only modal dialogs are permitted - Personal Java allows the browser to throw an exception if the browser doesn't support non-modal dialogs.
| Here's the swing version of the above code - it's
...
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911), Apr 4, 2000 Here's the swing version of the above code - it's pretty much the same - notice that the constructor for JDialog still takes a regular java.awt.Frame as an argument, not a JFrame [editor note: JFrame is a subclass of Frame so could be used if the parent was truly a JFrame].
|
| For IE, see http://www.jguru.com/jguru/faq/view.js...
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 20, 2000 For IE, see http://www.jguru.com/jguru/faq/view.jsp?EID=67354. |
| A little change to call FileDialog instead of Dialog.
Author: Arun Mahajan (http://www.jguru.com/guru/viewbio.jsp?EID=512172), Feb 14, 2002 I think the following change is OK. If not let me know your comments. import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class testFile extends Applet implements ActionListener { Button b; Label l = new Label(); private Frame findParentFrame(){ Container c = this; while(c != null){ if (c instanceof Frame) return (Frame)c; c = c.getParent(); } return (Frame)null; } public void init(){ setLayout(new FlowLayout()); b = new Button("push me"); b.addActionListener(this); add(b); } public void actionPerformed(ActionEvent e){ Frame f = findParentFrame(); if(f != null){ FileDialog d = new FileDialog(f); d.show(); String xx = d.getFile(); l.setText(xx); l.setBounds(10,15,100,20); add(l); } } } |
How do I display an Image in an applet or application?
Location: http://www.jguru.com/faq/view.jsp?EID=28451
Created: Mar 25, 2000
Modified: 2000-09-14 13:10:29.762
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Sunil Varghese (http://www.jguru.com/guru/viewbio.jsp?EID=28026
The basic manner of displaying an Image in an applet/application is to call the drawImage() method of the Graphics class in the paint() method of the component to display the image. There are six varieties of the method that deal with scaling and background colors for transparent images. The basic manner of calling is as follows:Comments and alternative answersg.drawImage(image, xPosition, yPosition, this);
The last argument is what's called an ImageObserver and helps deal with the asynchronous loading of image data. Generally speaking, you just pass a reference to the applet as the image observer so that as more data is loaded the applet (the observer) is notified and redraws itself.This leaves one question though. How do you get the image to display? The getImage() method of Applet or Toolkit helps here, requiring just the URL of where to get the image from:
Image image = getImage(url);
For an application, you would instead use getImage() method of Toolkit:Toolkit kit = Toolkit.getDefaultToolkit();
To make matters simpler for an applet, allowing you to move an applet between hosts without having to hardcode where the images come from, you can use a second variety of the method:
Image image = kit.getImage(url);
Image image = kit.getImage(filename);
Image image = getImage(baseURL, file);
Here, you provide the base URL and filename separately. The two are combined to form the specific URL to get the image file from. How is this better? Well, there are two more methods to help here. The getDocumentBase() method allows you to start with a base URL of where the HTML file is located. And, the getCodeBase() method allows you to start with a base URL of where the .class file is located. Using one of the two you can find an image in the same directory as either with something like this:Image image = getImage(getDocumentBase(), "image.jpg");
That is basically it, except if you want to package image files into a JAR. For this, you need to use the getResourceAsStream() method of the Class class.InputStream in = getClass().getResourceAsStream ("image.gif"); byte buffer[] = new byte[in.available()]; for (int i = 0, n = in.available(); i<n; i++) buffer[i] = (byte)in.read(); // in.read(buffer); // this doesn't read all when reading from JAR Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = toolkit.createImage(buffer);Unfortunately, you cannot use the getResource() method (which returns a URL) as Netscape browsers do not support it.
| in.available and in.read
Author: Guillermo Rodriguez (http://www.jguru.com/guru/viewbio.jsp?EID=453469), Jul 11, 2001 There is a misconception in this code (below). It is true that read() can legitimally read less bytes than requested, but it will never read less bytes than reported by in.available(), as this is defined to be the amount of data which is readily available to the JVM. BTW, in.available() is not necessarily the _length_ of the image -- it's only the part that is available when the method is called (when reading from JAR files, this is usually the whole image, but it doesn't need to). For the same reason, calling in.available() twice (one when creating the array and another one at the beginning of the for loop) can lead to unexpected results.
InputStream in = getClass().getResourceAsStream
("image.gif");
byte buffer[] = new byte[in.available()];
for (int i = 0, n = in.available(); i<n; i++)
buffer[i] = (byte)in.read();
// in.read(buffer);
// this doesn't read all when reading from JAR
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.createImage(buffer);
|
| Re: in.available and in.read
Author: Simon Arthur (http://www.jguru.com/guru/viewbio.jsp?EID=1284606), Feb 18, 2006 Even easier if you have the javax.imageio.* package:
InputStream in =
getClass().getResourceAsStream("image.gif");
BufferedImage bi = javax.imageio.ImageIO.read(in);
|
How can I get the component/container structure of an open Window?
Location: http://www.jguru.com/faq/view.jsp?EID=30309
Created: Mar 30, 2000
Modified: 2000-04-03 10:47:07.82
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Programmatically, you can call the list() method of Component/Container. You can also press CTRL-SHIFT-F1 while the window has the input focus and the structure will be dumped to standard output (System.out).
How can I change the cusror when the mouse button is pressed?
Location: http://www.jguru.com/faq/view.jsp?EID=30964
Created: Apr 1, 2000
Modified: 2000-04-03 11:07:55.353
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by radha gadiraju (http://www.jguru.com/guru/viewbio.jsp?EID=29279
comp.addMouseListener(
new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// If you are using swing you may want to use
// SwingUtilities.invokeLater(new Runnable {
// public void run() {
comp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// This helps sometimes
Toolkit.getDefaultToolkit().sync();
}});
How and why would you use the java.awt.EventQueue?
Location: http://www.jguru.com/faq/view.jsp?EID=31064
Created: Apr 2, 2000
Modified: 2000-04-03 11:18:24.257
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by lyndon mendoza (http://www.jguru.com/guru/viewbio.jsp?EID=8369
Comments and alternative answersWell there are many reasons.
- Say, you wanted to catch all the mouse events across all the GUI of your application. Without tapping the EventQueue you will have to add a mouse listener and mouse motion listener to every component. You will have to also add container listener to every container so that you can then add mouse listener to newly added components. You will still not know the existence of new frames if it was not explicitly annouced in the program.
- If you wanted to detect inactivity on the EventQueue so that you could perform low priority background task (like the animation on the help guy in MS word when user seems to be inactive possibly because the user is wondering what to do next etc). You could start a time after every event. If next event comes before the timer expires, restart the timer. If the times expires you know that the event queue has been inactive that long and you could start the background task.
- You may want to automate the wait cursor as described in a recent article in JavaWorld. Here is the reference - http://www.javaworld.com/javaworld/javatips/jw-javatip87.html
- The JFC/Swing Accesibility utilities use the event queue to keep track of the GUI state.
- JavaStar (now discontinued) GUI testing tool used the event queue to keep track of the state of GUI and to do record and playback functionality for regression testing.
In fact the AWT engineers realized the importance of such a functionality and in JDK1.2 it is directly supported through
java.awt.Toolkit.getDefaultToolkit().addAWTListener(....)The event queue class also supports push(EventQueue eq) and pop() APIs so that the users can install their own EventQueue.
In JDK1.1 the only way to hook the EventQueue was to modify the JDK-DIR/lib/awt.properties file and add an entry -
AWT.EventQueueClass=<your-eventqueue-subclass> which is dynamically loaded. This affects all the applications run from that installation though. You could turn on the special functionality using a system property or something though.
| JDK1.1.8 EventQueue
Author: Matt Stein (http://www.jguru.com/guru/viewbio.jsp?EID=535119), Oct 31, 2001 With regards to JDK1.1.8, could someone go into more detail on the following: In JDK1.1 the only way to hook the EventQueue was to modify the JDK-DIR/lib/awt.properties file and add an entry - (i.e. how would you do this?) Thanks! |
How do I cut and paste a Java Image to a an external program like Microsoft Paint?
Location: http://www.jguru.com/faq/view.jsp?EID=31065
Created: Apr 2, 2000
Modified: 2000-04-05 04:11:34.36
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
As of today - no you can't :( in 100% pure Java. That is because of the following bug and other related bugs - http://developer.java.sun.com/developer/bugParade/bugs/4040183.html
You can do that using JNI though. It can be done on MS Windows platform using the following strategy -
Use the java.awt.image.PixelGrabber class to convert the Java Image into a DIB or BMP format array ( the formats used to transfer images on the MS Windows platform). Then pass it to the JNI function which use the following APIs -
OpenClipboard() EmptyClipboard() GlobalAlloc( buffer) GlobalLock( buffer) // copy image header and data to the buffer // you wil have to deal with byte and RGB pixel order here GlobalUnlock(buffer) SetClipboardData(buffer) CloseClipboard()
How may I catch popup trigger events for all the components in a JFrame? I tried using GlassPane but it seems a bit to complicated as one must forward all other mouse events in an consistent manner
Location: http://www.jguru.com/faq/view.jsp?EID=31654
Created: Apr 3, 2000
Modified: 2000-04-04 05:39:07.843
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by David Lilljegren (http://www.jguru.com/guru/viewbio.jsp?EID=29979
If you are using JDK1.2 you could use the
java.awt.Toolkit public void addAWTEventListener(AWTEventListener listener, long eventMask)API. You could listen to MOUSE_EVENT_MASK mask. Then check if the source of the event is contained in the JFrame that you are trying to track the isPopupTrigger(). If so then check if mouseEvent.isPopTrigger() and if it is do your thing...
How can I use right-to-left text in a JTextPane?
Location: http://www.jguru.com/faq/view.jsp?EID=31690
Created: Apr 3, 2000
Modified: 2000-04-04 05:45:23.921
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Samsamoddin Rajaei (http://www.jguru.com/guru/viewbio.jsp?EID=22673
Starting JDK1.2 the java.awt.Component class has the following method
public ComponentOrientation getComponentOrientation()Retrieve the language-sensitive orientation that is to be used to order the elements or text within this component. LayoutManager and Component subclasses that wish to respect orientation should call this method to get the component's orientation before performing layout or drawing.
[FAQ Manager Note]This will apply the orientation to a single component. If you want to apply it to all components under a Window, use
java.awt.Window.applyResourceBundle()]
How do I create a modal Dialog without a Titlebar/close button or if that is not possible, how do I create a modal Window?
Location: http://www.jguru.com/faq/view.jsp?EID=32674
Created: Apr 5, 2000
Modified: 2000-04-24 20:56:12.771
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Josh Marquart (http://www.jguru.com/guru/viewbio.jsp?EID=30693
Comments and alternative answersThe following might work
public class YourFrame extends Frame { // blah // blah private void showModalWindow() { Window w = new Window(this); w.setLayout(new BorderLayout()); w.add(new Label("Modal Window"), BorderLayout.CENTER); w.pack(); // or w.setBounds() etc. w.addWindowListener( new WindowAdapter() { public void windowClosed(WindowEvent we) { // remove listener we.getWindow().removeWindowListener(this); // enable outer YourFrame instance setEnabled(true); } } ); setEnabled(false); w.setVisible(true); } }
| Here is a complete example
(save it in ModalWindow...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Apr 10, 2000 Here is a complete example (save it in ModalWindowExample.java)
import java.awt.*;
import java.awt.event.*;
public class ModalWindowExample extends Frame {
public ModalWindowExample() {
super("ModalWindowExample Frame");
add(new TextArea(), BorderLayout.CENTER);
Button b = new Button("Show modal window");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showModalWindow();
}});
add(b, BorderLayout.NORTH);
pack();
setLocation(100, 200);
setVisible(true);
}
private void showModalWindow() {
class HidingWindow extends Window {
public HidingWindow(Frame frame) {
super(frame);
setBackground(SystemColor.control);
}
public Insets getInsets() {
return new Insets(2,2,2,2);
}
public void setVisible(boolean show) {
super.setVisible(show);
if (!show) {
ModalWindowExample.this.setEnabled(true);
ModalWindowExample.this.toFront();
}
}
public void paint(Graphics g) {
Dimension size = getSize();
Color c = g.getColor();
g.setColor(SystemColor.control);
g.fill3DRect(0,0, size.width, size.height, true);
g.setColor(c);
super.paint(g);
}
};
final Window w = new HidingWindow(this);
w.setLayout(new BorderLayout());
w.add(new TextArea(), BorderLayout.CENTER);
Button b = new Button("Close");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
w.setVisible(false);
}});
w.add(b, BorderLayout.NORTH);
w.pack();
w.setLocation(400, 400);
// or w.setBounds() etc.
// w.addWindowListener(
// new WindowAdapter() {
// public void windowClosing(WindowEvent we) {
// System.out.println(we);
// remove listener
// we.getWindow().removeWindowListener(this);
// // enable outer ModalWindowExample instance
// ModalWindowExample.this.setEnabled(true);
// }
// });
setEnabled(false);
w.setVisible(true);
}
public static void main(String args[]) {
Frame f = new ModalWindowExample();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
}
}
|
| I had tried this example and there is a little but...
Author: Miquel Mustaros (http://www.jguru.com/guru/viewbio.jsp?EID=114558), Jul 30, 2000 I had tried this example and there is a little but very important bug. When you press on the button labeled "Show modal window", a modal window is created, but the focus is on the button of the first window and if you press the space bar, a new instance of the second window is created and so. The first window doesn't receive mouse events but receives keyboard events until you click the mouse on the second window. I tried a requestFocus on the button of the second window but it does nothing. |
| Re: I had tried this example and there is a little but...
Author: Octavio Luna (http://www.jguru.com/guru/viewbio.jsp?EID=986623), Aug 21, 2002 I made a few changes to the code (I let the "Close" button be part of the Modal Window) and I use toFront() to made the new Modal Window the Main One and After that I called the requestFocus() of the component that I wanbted to be focusable one. I hope this help You.
|
| Modal Windows and Frames
Author: Jene Jasper (http://www.jguru.com/guru/viewbio.jsp?EID=1155096), Mar 17, 2004 Take a look at the following project on java.net: jmodalwindow.dev.java.net |
Can I make frames have curved/rounded borders?
Location: http://www.jguru.com/faq/view.jsp?EID=33025
Created: Apr 6, 2000
Modified: 2000-04-07 07:22:13.487
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Anil Punjabi (http://www.jguru.com/guru/viewbio.jsp?EID=23218
No, you can't (at least not in 100% pure Java).
How do I add a popup menu to an item in a List(AWT 1.1)?
Location: http://www.jguru.com/faq/view.jsp?EID=33838
Created: Apr 8, 2000
Modified: 2000-04-16 06:52:18.609
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Christopher MacDougald (http://www.jguru.com/guru/viewbio.jsp?EID=32183
The trick is to figure out what is the index of the item at the mouse press location.
Couple of tricks could be used -
- Create offscreen (location -2000, -2000) list with 5 items i.e. new List(5). Fill it with 5 items. Call getPreferredHeight() and divide by 100 to get the row height. Once you know the row height rest is easy. Just listen to the mouseEvents. Check for mouseEvent.isPopupTrigger(). Then show the popup based on the index of the item under the mouseEvent.getPoint(). You can even build the popup menu on the fly (not reccommended).
- If the list is single select. The mouse event should select the item under it. Then do the showing of popup based on getSelectedIndex().
Should I ever use the Java 1.0 event handling mechanisms?
Location: http://www.jguru.com/faq/view.jsp?EID=33993
Created: Apr 9, 2000
Modified: 2000-09-14 07:58:01.13
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
Comments and alternative answersIn most cases, the answer is no. Around 90% of the browsers people use support the Java 1.1 AWT capabilities. However, if you really want to hit 100% and not lock out some users, than you are stuck with the 1.0 world. Of course, this also means that the users are at a security risk, as there have been many security fixes since the older browser releases, for both Java and JavaScript.
[FAQ Manager note] You can also put a note on your web page stating "You need Java 1.1 support to view this applet". The 1.1 browsers have been available for long enough that it's really fair to expect your users to upgrade.
| It is not valid to expect users to upgrade. Netscape...
Author: Larry Widing (http://www.jguru.com/guru/viewbio.jsp?EID=96408), Jul 5, 2000 It is not valid to expect users to upgrade. Netscape users on Macs are out of luck, as there is not a version of Netscape there that supports the AWT 1.1 event model. Also, anyone using Netscape prior to 4.06 (non-Mac platforms) will not have a 1.1 supporting JVM, unless they have applied the patch (if available for thier version). Furthermore, many corporations are VERY slow to upgrade their browsers, due to requirements of their MIS departments that all machines use the same version of a particular software product, and the time/cost to upgrade in that environment can be prohibative. You need to make very certain of your target client base before making the decision to require Java 1.1.
As an aside, Netscape versions prior to 4.05 will not load signed applets, as their internal certificate has expired. Another reason for these users to upgrade their browsers. |
How do I create an new image as part (rectangle) of a source image?
Location: http://www.jguru.com/faq/view.jsp?EID=33997
Created: Apr 9, 2000
Modified: 2000-04-16 07:08:11.887
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Gaetano Gallo (http://www.jguru.com/guru/viewbio.jsp?EID=30091
Look at using the CropImageFilter.
Image image = ...; ImageFilter filter = new CropImageFilter(x,y,width,height); Image newImage = createImage(new FilteredImageSource(image.getSource(), filter));
How can I display characters of the symbol font
(ex: Arrow symbols... up and down arrows) on an applet?
Location: http://www.jguru.com/faq/view.jsp?EID=35388
Created: Apr 12, 2000
Modified: 2000-06-09 19:36:08.667
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Sandilya Vadapalli (http://www.jguru.com/guru/viewbio.jsp?EID=31317
The symbols have a specific mapping into Unicode. You need to learn what their Unicode position is and use that. For instance, you'll find the arrows from 2190-2195. You'll then have to make sure you are using a font that supports them. For instance, bold Serif does, but plain doesn't. The following program demonstrates how to dipslay the arrows:
import java.awt.*;
import java.applet.Applet;
public class Arrow extends Applet {
public void paint(Graphics g) {
g.setFont(new Font("Serif", Font.BOLD, 25));
g.drawString("\u2190\u2191\u2192\u2193\u2194\u2195", 20, 20);
}
}
If you would like help in finding characters for different fonts, check out the UnicodeDisplay program in the Java Examples in a Nutshell from O'Reilly at http://www.oreilly.com/catalog/jenut/examples/.
While displaying a font on an applet, is it necessary for the system running the browser to have the font or is it carried across from the web server where the applet resides?
Location: http://www.jguru.com/faq/view.jsp?EID=35416
Created: Apr 12, 2000
Modified: 2001-07-26 21:25:20.358
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Sandilya Vadapalli (http://www.jguru.com/guru/viewbio.jsp?EID=31317
Prior to the 1.3 release, the font was required to be on the user's platform and their font.properties file had to be modified so you could use it. Starting with 1.3, you can call public static Font createFont(int fontFormat, InputStream fontStream) throws FontFormatException, IOException which lets you pass true type fonts across an input stream.However, Font.createFont() uses a working file to create the new font. And, untrusted applets have no permission to create the working file. Consider creating the Font in a servlet and serializing it back to the applet.
Is it possible to enable Drag & Drop in applets and if so, how?
Location: http://www.jguru.com/faq/view.jsp?EID=35982
Created: Apr 13, 2000
Modified: 2001-07-26 21:30:57.753
Author: Saket Malhotra (http://www.jguru.com/guru/viewbio.jsp?EID=35980)
Question originally posed by Jesper Berglund (http://www.jguru.com/guru/viewbio.jsp?EID=11962
You need Java 2 support for the drag & drop APIs. You can obtain this by requiring the Java Plug in for your applet.
The other alternative is to create your own custom drag and drop library
Apparently, you can't create the drop targets in init() or start().
How do I change the color of individual list items in AWT 1.1?
Location: http://www.jguru.com/faq/view.jsp?EID=36071
Created: Apr 13, 2000
Modified: 2000-04-16 13:36:24.228
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Christopher MacDougald (http://www.jguru.com/guru/viewbio.jsp?EID=32183
The List control in AWT does not support this capability. You'll have to either build your own, find someone else who has, or use the Swing JList control.
Can I change the size of the scrollbars in a java.awt.List component?
Location: http://www.jguru.com/faq/view.jsp?EID=36072
Created: Apr 13, 2000
Modified: 2000-04-16 07:18:43.924
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Zhi Shen (http://www.jguru.com/guru/viewbio.jsp?EID=21324
You have no control over the scrollbar size with the List component. Its a native / peer-based control. What the operating system gives you is what you get.
What is a lightweight component?
Location: http://www.jguru.com/faq/view.jsp?EID=38532
Created: Apr 20, 2000
Modified: 2000-05-20 17:55:29.245
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10)
Comments and alternative answersBefore talking about lightweight components, it is necessary to discuss the concept of Java peers. When instantiating any of the AWT component classes, e.g. a java.awt.Button, the system actually asks the native environment to create the component. This ensures the user sees the native look-and-feel and the component acts like the native control. The native code that provides this look-and-feel is called a peer; each platform has its own set of peers. A Java button appears and acts as a Windows button when run under Windows, as a Macintosh button when run under Macintosh, and as a Unix button when run under Unix. The FAQ found at http://www.jguru.com/jguru/faq/view.jsp?EID=11353 discusses the concept of peers in more detail.
While in practice this sounds great, there are problems because not all native controls respond similarly to the same events. This can result in a Java program exhibiting different behavior under different Java AWT environments. To overcome this problem, you must use components written entirely in Java. That is, components that do not have a native peer. These are called lightweight components. Swing provides a set of pure Java lightweight components, ensuring better cross-platform compatibility. (Or at least ensuring that any bugs are the same bugs on all platform - a very important feature!)
A lightweight component is one that subclasses java.awt.Component (or java.awt.Container) directly - implementing the look-and-feel of the component in Java rather than delegating the look-and-feel to a native peer. Lightweight components can be more efficient at utilizing system resource, they can be transparent, and they do not have to be rectangular (all of which are limitations when working with components that have a peer). For instance, if you are creating lots of panels to help layout components, you can create a LightweightPanel class that subclasses Container to use instead. This would allow you to use the LayoutManager on your panel but not require the overhead of managing all the heavyweight peers that would be created with each java.awt.Panel.
| Reading this answer someone could understand that it...
Author: Kong Goodu (http://www.jguru.com/guru/viewbio.jsp?EID=70389), Jun 25, 2000 Reading this answer someone could understand that it is possible to realize an pure java application only with lightweight components (with transparent or non-rectangular windows, for example an ICQ splash-screen, etc.). Is this true ? [FAQ Manager note] You always need at least one heavyweight component to stary drawing on. This is why (J)Frame, (J)Window, or (J)Dialog are heavyweight.
|
| Swing is a light weight component, and awt is a heavy weight component
Author: krishna chowdary (http://www.jguru.com/guru/viewbio.jsp?EID=1353057), Jan 5, 2008 Light weight Component takes the components from the jvm, means it does not request the operating System for getting the components. Swings are light weight components. thats why swing look and feel is different and same on every operating System. Where as, heavy weight components are depending on the O.S. if we request a button component, then JVM ask the button to the os and then it give to the JVM. it is very time consuming process. So awt look and feel is depending on the os. It changes from one os to another os. These are the major differences between the heavy weight and light weight components |
How can I create my own component?
Location: http://www.jguru.com/faq/view.jsp?EID=38533
Created: Apr 20, 2000
Modified: 2000-04-24 20:29:49.564
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10)
Question originally posed by sudhakar ks (http://www.jguru.com/guru/viewbio.jsp?EID=26574
Comments and alternative answersTo create an actual component that is lightweight requires six steps:
And that's all there is to it.
- You need to define a constructor or constructors in order to initialize the state of your component If your component is to respond to any events internally (like mouse presses to activate it), this has to be enabled in the constructor, usually by adding the appropriate listener.
- Assuming that in the previous step you added a listener for handling internal events, you have to now define the listener class. It is best to do this with an inner class because then access is restricted to the lightweight component.
- You need to deal with sizing the object and programmatically changing any properties. For instance, if you have a button that supports changing of its label, you also need to provide a method to recalculate its size when the label is changed.
- You need to override the paint() method so the component can be drawn. This is where you define the visual appearance of your component.
- If you want your component to be non-rectangular, you need to override the contains() method. The contains() method should return true when it is over an area of the object. This routine should be very fast as it will be called frequently. By default, it always returns true. If your component is defined by a java.awt.Polygon shape, that class has a contains() method that you can call. Otherwise, you have to calculate this yourself.
- If you plan on supporting the notification of objects when an event happens (like sending an java.awt.event.ActionEvent when a button is selected, you need to create add/removeXXXListener() methods. Assuming the event type you are using is one of the predefined AWT events, you can use the java.awt.AWTEventMulticaster class to add and remove listeners from the list.
The following source demonstrates all this by creating a round button component. This component is activated only if selected within the circle. The code is simplified to illustrate the important points when creating your own component - if you want this to behave like a real button then you will have to get more sophisticated with the mouse event handling. First, the constructor initializes the radius and creates a listener for mouse events:
import java.awt.*; import java.awt.event.*; public class CircularButton extends Component { private int radius; boolean pressed = false; ActionListener actionListener = null; public CircularButton() { this(5); } public CircularButton(int radius) { if (radius < 0) { throw new IllegalArgumentException("Illegal Radius: " + radius); } this.radius = radius; addMouseListener(new ClickAdapter()); setSize(getPreferredSize()); }This component is the source of ActionEvents, like all buttons, so it is responsible for maintaining a list of listeners and providing methods to add and remove listeners. It does this with the help of the java.awt.AWTEventMulticaster class:
public void addActionListener(ActionListener l) { actionListener = AWTEventMulticaster.add(actionListener, l); } public void removeActionListener(ActionListener l) { actionListener = AWTEventMulticaster.remove(actionListener, l); }The constructor defined an inner class called ClickAdapter to handle mouse events. This event handler doesn't worry if the mouse click is over the object or not, it just keeps track of the state of pressed and notifies the listeners. Because the adding and removing of listeners is done with AWTEventMulticaster, invoking the notification method on the actionListener instance variable (which is actually an instance of AWTEventMulticaster) will notify all the listeners. (If you do not use AWTEventMulticaster, you would need to maintain the listener list in something like a java.util.Vector then iterate through the list of listener elements yourself, calling each listener method. And do it in a thread-safe manner, which AWTEventListener does for you.) ClickAdapter looks like this:
private final class ClickAdapter extends MouseAdapter { public void mousePressed(MouseEvent e) { if (isEnabled()) { pressed = true; repaint(); } } public void mouseReleased(MouseEvent e) { if (isEnabled()) { pressed = false; repaint(); if (actionListener != null) { actionListener.actionPerformed( new ActionEvent(CircularButton.this, ActionEvent.ACTION_PERFORMED, "")); } } } }There are three sizing routines that need to be overridden so that the layout managers can properly size and position this component:
public Dimension getPreferredSize() { int side = radius *2; return new Dimension(side, side); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); }To draw the component, you must override the paint() method. This is an important step because it defines the visual appearance of your component; an appearance that may even vary with the component's state, as does this button:
public void paint(Graphics g) { super.paint(g); if (isEnabled()) { if (pressed) { g.setColor(Color.white); g.fillOval(0, 0, radius*2, radius*2); g.setColor(Color.black); g.drawOval(0, 0, radius*2, radius*2); } else { g.setColor(Color.black); g.fillOval(0, 0, radius*2, radius*2); } } else { g.setColor(Color.gray); g.fillOval(0, 0, radius*2, radius*2); } }Next, override the contains() method in order to support a non-rectangular component. To check to see if a point is within the circle, compare against the radius. Note that the range of the x and y input parameters covers the full size of the circle, and nothing more.
public boolean contains(int x, int y) { //distance = square root of (deltaX squared + deltaY squared) int deltax = x - radius; int deltay = y - radius; double distance = Math.sqrt(Math.pow(deltax, 2) + Math.pow(deltay, 2)); return (distance <= radius); }Finally, a main method is provided which simply creates a frame with several instances of CircularButton for test purposes:
public static void main(String[] args) { final CircularButton cb1, cb2, cb3, cb4, cb5; Frame f = new Frame(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); f.setLayout(new FlowLayout()); f.add(cb1 = new CircularButton(25)); f.add(cb2 = new CircularButton(25)); f.add(cb3 = new CircularButton(25)); f.add(cb4 = new CircularButton(25)); f.add(cb5 = new CircularButton(25)); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e) { Object o = e.getSource(); String msg; if (o.equals(cb1)) { msg = "One"; } else if (o == cb2) { msg = "Two"; } else if (o == cb3) { msg = "Three"; } else if (o == cb4) { msg = "Four"; } else if (o == cb5) { msg = "Five"; } else { msg = "Huh?" + o; } System.out.println("Button: " + msg); } }; cb1.addActionListener(al); cb2.addActionListener(al); cb3.addActionListener(al); cb4.addActionListener(al); cb5.addActionListener(al); cb5.setEnabled(false); f.pack(); f.show(); } }
| This was helpful
Author: Jos Groen (http://www.jguru.com/guru/viewbio.jsp?EID=1267874), Oct 19, 2005 Thanx for summiting this example! |
How do you make a JavaBean which has a static size?
Location: http://www.jguru.com/faq/view.jsp?EID=39608
Created: Apr 24, 2000
Modified: 2001-07-24 10:28:25.884
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Asim Raja (http://www.jguru.com/guru/viewbio.jsp?EID=24654
To make a fixed size component, just override the getMinimum/Preferred methods to return the fixed size. You should also provide the bean with its own BeanInfo class to effectively hide the size properties. That way, they won't appear. You may find it necessary to update the deprecated methods, too, like preferredSize(), but that shouldn't be necessary. See the Juggler bean that comes with the BDK for one such fixed size component.If you're class isn't a subclass of Component, all this is irrelevant.
How do I cut and past text from the clipboard?
Location: http://www.jguru.com/faq/view.jsp?EID=39779
Created: Apr 24, 2000
Modified: 2000-04-24 22:21:01.476
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Comments and alternative answersStarting with Java 1.1, access to the system clipboard is available via the java.awt.datatransfer package. This package also provides the basis for drag-and-drop capabilities, which is included with Java in the 1.2 release (in the java.awt.dnd package).
The Clipboard class is the basis for the capabilities. By asking the Toolkit, you can access the system clipboard with the Toolkit.getSystemClipboard() method. This requires a check past the SecurityManager so is usually restricted within applets. In both applets and applications you can create a Clipboard independent of the system clipboard by just calling the constructor for Clipboard. This way, applets can still provide cut-and-paste capabilities internally, without accessing the system's clipboard, and applications can maintain a private clipboard as well as accessing the system clipboard.
Items are placed on the clipboard with the Clipboard.setContents() method. This requires that the items implement the Transferable interface.
public interface Transferable { public abstract DataFlavor getTransferDataFlavors()[]; public abstract boolean isDataFlavorSupported(DataFlavor); public abstract Object getTransferData(DataFlavor); }The Transferable interface works with items that can be represented in different DataFlavors. Essentially, flavors are MIME types and may be represented by the standard MIME type strings. The getTransferDataFlavors() method returns flavors ordered from richest to simplest (i.e., MS Word, RTF, ASCII). Also, an additional MIME type was introduced to represent Java classes:
application/x-java-serialized-object; class=classname application/x-java-serialized-object; class=java.util.VectorBecause transferring text is so common, Java provides the StringSelection class to assist. There is one limitation with information sent to the system clipboard: between Java programs and non-Java programs, you can only transfer text strings.
Clipboard Access Example
The following program demonstrates the use of all these classes. If there is a command line argument, it places it on the clipboard. Then, it takes off whatever is on the clipboard, as a String, and prints it out. If the contents cannot be represented as a String the exception message String is caught and displayed.
import java.awt.Toolkit; import java.awt.datatransfer.*; public class clip { public static void main (String args[]) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (args.length != 0) { StringSelection data = new StringSelection (args[0]); clipboard.setContents (data, data); } Transferable clipData = clipboard.getContents(clipboard); String s; try { s = (String)(clipData.getTransferData( DataFlavor.stringFlavor)); } catch (UnsupportedFlavorException ee) { s = ee.toString(); } System.out.println ("Clipboard Had: " + s); System.exit (0); } }
| How do I cut and paste text from the clipboard in a JApplet?
Author: Jose Maria Bernal (http://www.jguru.com/guru/viewbio.jsp?EID=505961), Jan 22, 2002 I need cut a JTable and paste it in Excel? How can I do this? |
Is it possible to create a tree component using AWT?
Location: http://www.jguru.com/faq/view.jsp?EID=40253
Created: Apr 25, 2000
Modified: 2000-04-29 11:35:28.708
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by vikram godboley (http://www.jguru.com/guru/viewbio.jsp?EID=37645
Yes, but you are on your own for the drawing.Comments and alternative answers
Matthew Wilson has a free tre implementation in AWT at http://www.bluemoon.net/~mewilson/..
| The above link is no longer valid (http://www.blue...
Author: Prog Dario (http://www.jguru.com/guru/viewbio.jsp?EID=300740), Jan 12, 2001 The above link is no longer valid (http://www.bluemoon.net/~mewilson/) Does anyone have a new link for this? |
| I'm not sure, but i think this is the script we se...
Author: Florian Richter (http://www.jguru.com/guru/viewbio.jsp?EID=317099), Jan 31, 2001 I'm not sure, but i think this is the script we searched for: http://javaboutique.internet.com/JMenu/jmenu_java.html |
| Sorry -- the above link is not the complete source...
Author: Florian Richter (http://www.jguru.com/guru/viewbio.jsp?EID=317099), Feb 7, 2001 Sorry -- the above link is not the complete source! Here's another link as a complete .zip package including icons and java source:
http://www.javapool.de/cgi-bin/download/load.cgi?applets/jmenu.zip |
| And finally in my thread Matthew Wilson told me the...
Author: Florian Richter (http://www.jguru.com/guru/viewbio.jsp?EID=317099), Feb 8, 2001 And finally in my thread Matthew Wilson told me the new location of his homepage with a NEWER version of the tree menu: http://www.mycgiserver.com/~mlavwilson/ Or you can build a AWT tree component with a tutorial at:
http://www.javaworld.com/javaworld/jw-01-1997/jw-01-step_p.html |
How do I composite(render) 3 images into one image with jdk1.1?
Location: http://www.jguru.com/faq/view.jsp?EID=40932
Created: Apr 26, 2000
Modified: 2000-10-19 05:52:38.561
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by Rok Lee (http://www.jguru.com/guru/viewbio.jsp?EID=20592
Comments and alternative answersEach Image object has a Graphics object. You can modify an Image by using its Graphics object. Create a blank Image, then use its getGraphics() member to obtain its Graphics object. Use this object in the same way you would use the one provided by paint().
Sample Code:
public void paint(Graphics g) //g is your object's display surface. { //Create & load images once in start() or init() for speed. Image imTarget app.createImage(TARGET_WIDTH,TARGET_HEIGHT); Image imSrc1 = app.getImage(app.getCodeBase(), "Image1.jpg"); Image imSrc2 = app.getImage(app.getCodeBase(), "Image2.jpg"); Image imSrc3 = app.getImage(app.getCodeBase(), "Image3.jpg"); int imSrc1_X=0, imSrc2_X=0, imSrc3_X=0, imSrc1_Y=0, imSrc2_Y=0, imSrc3_Y=0; Graphics tg = null; try { tg=imTarget.getGraphics();//Create a render surface. } catch(Exception e) { System.out.println("Error creating render surface" + e); return; } if(imSrc1!=null) tg.drawImage(imSrc1, imSrc1_X, imSrc1_Y, this); if(imSrc2!=null) tg.drawImage(imSrc2, imSrc2_X, imSrc2_Y, this); if(imSrc3!=null) tg.drawImage(imSrc3, imSrc3_X, imSrc3_Y, this); g.drawImage(imTarget,0,0,this); }
| When I tg.drawImage in the paint function the I am...
Author: Kartik Shah (http://www.jguru.com/guru/viewbio.jsp?EID=229938), Oct 17, 2000 When I tg.drawImage in the paint function the I am able to see the new generated Image but if I use tg.drawImage in the init or start function, I am not able to see the new generated Image. g.drawImage(imTarget,0,0,this) in both the cases is in the paint function. I'd like to generate the new Image just once and use it throughout the applet object life. Please let me know if I can just generate the imTarget image only once and not everytime in the paint function.
|
| I'd recommend a "lazy instantiation" app...
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11), Oct 19, 2000 I'd recommend a "lazy instantiation" approach. You can modify the above code to save the image in an instance variable and check to see if it's been set. The code would look something like:
public class MyApplet extends Applet {
private Image composite;
...
public void paint(Graphics g) {
if (composite == null) {
// generate composite with
// provided code above
composite = app.createImage(...);
...
}
g.drawImage(composite,0,0,this);
}
}
The big difference is that you only create the image once... |
| And how to print out to HTML that image for client save as?
Author: tttt ntl (http://www.jguru.com/guru/viewbio.jsp?EID=410881), May 10, 2001 mean how to make that image for client save as same way we used HTML tag <Img src=... |
Is the paint method supposed to constantly be called in a JPanel? Is there a way to stop it?
Location: http://www.jguru.com/faq/view.jsp?EID=42529
Created: Apr 30, 2000
Modified: 2000-05-02 07:55:56.255
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Clarence Robinson (http://www.jguru.com/guru/viewbio.jsp?EID=22627
First of all, why would you want to stop paint() from being called in a graphical component?
If you do it nothing will be drawn. Unless, of course, you call it on your own, but why stopping something to create something else that does the same thing, and in a standard and consistent way between components?
Usually you deal with paint() and the methods that call it for performance reasons or to eliminate flickering. For the first part performance is rarely on the paint side, and if it is you don't eliminate paint(). As for flickering as you will see in a moment things can be done quite easily.
Maybe you think that paint(), being called continuously, can bog down your app speed; it is not so, because it is not called continuously but only when needed by the window manager (for example resizes, windows overlapping, etc.) or by you, when you do animations.
Let's start by looking at the class Component; Panel extends Component, an uses the paint system written in Component. The following considerations are for all classes that extend Component directly or indirectly. The code is from the source code of the Java classes V1.2.2.
/** * Paints this component. This method is called when the contents * of the component should be painted in response to the component * first being shown or damage needing repair. The clip rectangle * in the Graphics parameter will be set to the area which needs * to be painted. * @param g The graphics context to use for painting. * @see java.awt.Component#update * @since JDK1.0 */ public void paint(Graphics g) { }As you can see paint does nothing.
By searching "paint(" in the file you can find that paint() is called by the following methods:
update() paintAll() print()Let's see update:
/** * Updates this component. * * The AWT calls the update method in response to a * call to repaint. The appearance of the * component on the screen has not changed since the last call to * update or paint. You can assume that * the background is not cleared. * * The update method of Component * does the following: * * - Clears this component by filling it * with the background color. * - Sets the color of the graphics context to be * the foreground color of this component. * - Calls this component's paint * method to completely redraw this component. * * The origin of the graphics context, its * (0, 0) coordinate point, is the * top-left corner of this component. The * clipping region of the * graphics context is the bounding rectangle * of this component. * @param g the specified context to use for updating. * @see java.awt.Component#paint * @see java.awt.Component#repaint() * @since JDK1.0 */ public void update(Graphics g) { if ((this instanceof java.awt.Canvas) || (this instanceof java.awt.Panel) || (this instanceof java.awt.Frame) || (this instanceof java.awt.Dialog) || (this instanceof java.awt.Window)) { g.clearRect(0, 0, width, height); } paint(g); }As is stated in the documentation of the method, update() is called by repaint().
In the code you see that it Sets the color of the graphics context to be the foreground color of this component. Calls this component's paint method to completely redraw this component.
To eliminate flickering usually you only need to write a class that extends Component (or any other class that inherits directly or indirectly from it like Panel) with this method:
public void update(Graphics g) { paint(g); }Flickering is created by the continuous alternation of the animation frames and foreground-colored rectangles, and with the above code you don't draw the rectangle any more.
Here is paintAll():
/** * Paints this component and all of its subcomponents. * * The origin of the graphics context, its * (0, 0) coordinate point, is the * top-left corner of this component. The clipping region of the * graphics context is the bounding rectangle of this component. * @param g the graphics context to use for painting. * @see java.awt.Component#paint * @since JDK1.0 */ public void paintAll(Graphics g) { ComponentPeer peer = this.peer; if (visible && (peer != null)) { validate(); if (peer instanceof java.awt.peer.LightweightPeer) { paint(g); } else { peer.paint(g); } } }It calls paint only with a java.awt.peer.LightweightPeer.
Here is print():
/** * Prints this component. Applications should override this method * for components that must do special processing before being * printed or should be printed differently than they are painted. * * The default implementation of this method calls the * paint method. * * The origin of the graphics context, its * (0, 0) coordinate point, is the * top-left corner of this component. The clipping region of the * graphics context is the bounding rectangle of this component. * @param g the graphics context to use for printing. * @see java.awt.Component#paint(java.awt.Graphics) * @since JDK1.0 */ public void print(Graphics g) { paint(g); }print() just calls paint(). From these three methods you can see that to totally eliminate calls to paint() you just need to write a class that extends Component (or any other class that inherits directly or indirectly from it like Panel) with theses methods:
public void update(Graphics g) { } public void paintAll(Graphics g) { ComponentPeer peer = this.peer; if (visible && (peer != null)) { validate(); if (!(peer instanceof java.awt.peer.LightweightPeer)) { peer.paint(g); } } public void print(Graphics g) {}This way paint() never gets called.
By the way it is interesting to see that you can make print() call another method; in this way the printed components can differ visually from the one seen on the screen!
Now let's get back to repaint() that calls update. In fact paint() doesn't get called in the code above but update() does, even if it is empty, by repaint().
You can also see that all other methods in Component call only repaint().Here is repaint():
/** * Repaints this component. * * This method causes a call to this component's update * method as soon as possible. * @see java.awt.Component#update(java.awt.Graphics) * @since JDK1.0 */ public void repaint() { /* getToolkit().getEventQueue(). removeSourceEvents(this,PaintEvent.PAINT); */ repaint(0, 0, 0, width, height); }It says that it calls update() but the method is not there!
The getToolkit().getEventQueue().removeSourceEvents(this, PaintEvent.PAINT) removes any pending events for the specified source object (from the EventQueue documentation).So let' see the other repaint:
/** * Repaints the specified rectangle of this component within * tm milliseconds. * * This method causes a call to this component's * update method. * @param tm maximum time in milliseconds before update. * @param x the x coordinate. * @param y the y coordinate. * @param width the width. * @param height the height. * @see java.awt.Component#update(java.awt.Graphics) * @since JDK1.0 */ public void repaint(long tm, int x, int y, int width, int height) { if (this.peer instanceof java.awt.peer.LightweightPeer) { // Needs to be translated to parent coordinates since // a parent native container provides the actual repaint // services. Additionally, the request is restricted to // the bounds of the component. int px = this.x + ((x < 0) ? 0 : x); int py = this.y + ((y < 0) ? 0 : y); int pwidth = (width > this.width) ? this.width : width; int pheight = (height > this.height) ? this.height : height; parent.repaint(tm, px, py, pwidth, pheight); } else { ComponentPeer peer = this.peer; if ((peer != null) && (width > 0) && (height > 0)) { peer.repaint(tm, x, y, width, height); } } }Here you see that it is the peer that calls the update() method; repaint just asks AWT to schedule a call to update(). Anyway, to block repaint do it like is done before with update(), paintAll(), print().
For more information on the AWT methods, how they work and on how to eliminate flickering see the AWT and Swing Tutorials at http://www.javasoft.com/tutorial
How can i get the Handle (HWND) of a java.awt.Canvas on Windows NT/98?
Location: http://www.jguru.com/faq/view.jsp?EID=44507
Created: May 4, 2000
Modified: 2000-05-06 07:43:21.629
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
import java.awt.*;
import sun.awt.*;
/* This class uses undocumented features of Sun's JDK */
/* Works only on Windows NT/98 with JDK1.1.8, JDK1.2.2 */
public class SunCanvas extends Canvas
{
/* Returns the HWND for canvas. */
public int getHWND()
{
DrawingSurfaceInfo drawingSurfaceInfo;
Win32DrawingSurface win32DrawingSurface;
int hwnd = 0;
/* Get the drawing surface */
drawingSurfaceInfo =
((DrawingSurface)(getPeer())).getDrawingSurfaceInfo();
if (null != drawingSurfaceInfo) {
drawingSurfaceInfo.lock();
/* Get the Win32 specific information */
win32DrawingSurface =
(Win32DrawingSurface)drawingSurfaceInfo.getSurface();
hwnd = win32DrawingSurface.getHWnd();
drawingSurfaceInfo.unlock();
}
return hwnd;
}
}
Comments and alternative answers
| Is there something equivalent for image data? How is...
Author: Francois Petit (http://www.jguru.com/guru/viewbio.jsp?EID=323982), Feb 14, 2001 Is there something equivalent for image data? How is it possible to get the Win32 handle (HBITMAP) of a java.awt.Image or a java.awt.BufferedImage object? |
| Yes, it's easy.
Author: Andreas Reich (http://www.jguru.com/guru/viewbio.jsp?EID=447229), Jun 28, 2001 Just replace getHWnd() by getHBitmap(). Same for getHDC(). |
| Oops :-)
Author: Andreas Reich (http://www.jguru.com/guru/viewbio.jsp?EID=447229), Jun 28, 2001 Sorry, I did not read your question carefully enough. This is just for getting the HBITMAP of the Canvas. |
| handling events
Author: gowri gopalakrishnan (http://www.jguru.com/guru/viewbio.jsp?EID=515181), Dec 4, 2001 I create a frame and the canvas is in the frame. the paint method of the canvas is native (liek the example given in teh above mentioned article) The rendering works fine but the events handling is not. The events happening on the canvas are captured by my c++ code but i do not know how to capture the events happening on the frame. Yes my frame has all the listeners it needs but the system is unable to transfer the events.... anyone has any ideas, i would like to know... thanks for any help Regards Gowri |
| Re: handling events
Author: Daniel Lang (http://www.jguru.com/guru/viewbio.jsp?EID=734805), Jan 25, 2002 Hi Gowri! I have the same problem like you. You said that you have a solution in order to capture the canvas-events. Can you send me this part of the code? I would thank you for that. Regards Daniel |
| Handle to Frame?
Author: Rajesh Venkatesan (http://www.jguru.com/guru/viewbio.jsp?EID=850253), Apr 22, 2002 Can u help me with obtaining a handle to a frame? |
| Using errors for this programme.
Author: SHAILESH JADHAV (http://www.jguru.com/guru/viewbio.jsp?EID=911183), Jun 12, 2002 i have got the following error while running the programme. C:\unzipped\javacom>java MyWindow http://www.codeproject.com Exception in thread "main" java.lang.NoClassDefFoundError: sun/awt/DrawingSurface |
| getPeer() is deprecated & replaced by isDisplayable()
Author: Kirti Mistry (http://www.jguru.com/guru/viewbio.jsp?EID=1305979), Jul 19, 2006 can any one help me out how to solve this problem ? I'm modifying my old program created using older version of java. Now, I'm working on jdk1.5.0_07. I used this coding to access native drawing surface information. import sun.awt.*; ... DrawingSurface ds = (DrawingSurface)theComponent.getPeer(); DrawingSurfaceInfo dsi = ds.getDrawingSurfaceInfo(); but it gives warning for getPeer() like: warning: [deprecation] getPeer() in java.awt.Component has been deprecated. I came to know from java.sun.com that.. getPeer() Deprecated. As of JDK version 1.1, programs should not directly manipulate peers; replaced by boolean isDisplayable(). so how to use isDisplayable() in place of getPeer() ? Can anyone help me out,Please? Thanks in advance kirti email:kirtimistry2001@yahoo.com |
How can I open an HTML page inside a Frame?
Location: http://www.jguru.com/faq/view.jsp?EID=44582
Created: May 4, 2000
Modified: 2000-05-06 07:49:47.381
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by Rajat Mehta (http://www.jguru.com/guru/viewbio.jsp?EID=42868
Comments and alternative answersIf you are willing to use Microsoft Specific Code look at the following article. http://codeguru.developer.com/java/articles/290.shtml
If you want platform independence, you can try JavaSoft's HotJava HTML Component 1.1.2 http://java.sun.com/products/hotjava/#bean
Or you can try ICESoft's ICE Browser http://www.icesoft.no/ICEBrowser/
| Another way to achieve this is to use Swing's JEdi...
Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588), May 8, 2000 Another way to achieve this is to use Swing's JEditorPane component, like this...
URL myURL = new URL("http://java.sun.com");
JEditorPane htmlPane = new JEditorPane(myURL);
htmlPane.setEditable(false);
There's also lots of other functionality you can provide very easily, including using hyperlink listeners to enable the user to jump between
pages like a web browser. |
Why doesn't dispatchEvent(KeyEvent e) work in applets but does in applications?
Location: http://www.jguru.com/faq/view.jsp?EID=45465
Created: May 6, 2000
Modified: 2001-07-26 21:35:35.91
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by lyndon mendoza (http://www.jguru.com/guru/viewbio.jsp?EID=8369
This is actually the result of differences in Java runtime implementations between browser vendor. Microsoft seems to have implemented their event dispatching mechanism differently than the rest of the world. Sun's and Netscape's versions will use dispatchEvent() properly from an applet. You can try out the following test case and see for yourself:
// <applet code=TestCase width=500 height=200>
// </applet>
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TestCase extends Applet {
TextField t1 = new TextField(50);
TextField t2 = new TextField(50);
public void init() {
add(t1);
add(t2);
t1.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
t2.dispatchEvent(e);
}
});
}
}
How do I get focus on a particular component on the screen. I tried requestFocus(), but it did not work. Do I have to do something special to be able to use requestFocus() method on a Button, or a TextField?
Location: http://www.jguru.com/faq/view.jsp?EID=45866
Created: May 8, 2000
Modified: 2000-05-16 21:32:44.072
Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588)
Question originally posed by R Singh (http://www.jguru.com/guru/viewbio.jsp?EID=41413
The requestFocus() method will only work when the component is visible so ensure that your window/applet is visible and that your component has been added to it. Then call the requestFocus() method on the component to switch the focus.Comments and alternative answers
| requestFocus()
Author: charul kothari (http://www.jguru.com/guru/viewbio.jsp?EID=419403), May 10, 2001 I'm in similar situation.I've posted a similar quiestion.Pl let me know if you found a solution.I've made sure that setVisible() is set to true. Thanks |
| Re: requestFocus()
Author: George Donoso (http://www.jguru.com/guru/viewbio.jsp?EID=581201), Dec 11, 2001 Please read below (pasted from another website in Germany).......... Problem: Initially giving the focus to a specified component in the dialog. Version: Swing 1.x Suggested Solution: Swing will initially give the focus to the first component you add to the dialog. Thus you can just add the desired component first. If that does not work for you it seems you have to go through major pain. There is of course a method in each component that requests the focus (therefore called requestFocus()) which works fine. However, if you call it during your initializing operations, Swing will late give the focus back to the first component you added. The only way around this, which I found working more than one system, is to write a class that will focus a component about 0.5 seconds after it is initialized: import java.util.*; import java.awt.event.*; import javax.swing.*; public class FocusSetter implements ActionListener { private JComponent component; private javax.swing.Timer timer; public FocusSetter(JComponent comp) { this.component = comp; this.timer = new javax.swing.Timer(500, this); this.timer.start(); } public void actionPerformed(ActionEvent evt) { if ((evt != null) && (evt.getSource() == timer)) { component.requestFocus(); } } } You can then use new FocusSetter(myJComponent) to set the focus to a particualr component. I know this is not a neat solution, but the only workable I found. If you happen to come across a better one, I would like to know (thanks!). |
| Re: requestFocus()
Author: Lars Hoss (http://www.jguru.com/guru/viewbio.jsp?EID=760066), Feb 15, 2002 Another simple solution is to make use of the ComponentListener:
addComponentListener(new ComponentAdapter()
{
public void componentShown(ComponentEvent evt)
{
button.requestFocus();
}
});
You have to add the listener to the frame or the dialog that contains the button.
|
| Method requestFocus() doesn't work!
Author: Michael Heuberger (http://www.jguru.com/guru/viewbio.jsp?EID=462526), Aug 2, 2001 Even I added the JCheckBox to a JDialog and it's visible, the requestFocus() doesn't give the JCheckBox the focus. Why? |
| Invoking RequestFocus() the first time a Dialog is shown
Author: Iron Master (http://www.jguru.com/guru/viewbio.jsp?EID=808906), Mar 22, 2002 b I have a swing application which displays a non-modal JDialog. I want to set the focus on a specific component the first time the dialog is displayed. This is the solution which works for me. Before JComponent.requestFocus() can be invoked on a component, the dialog must already be displayed through a call to Dialog.show(). But before calling the requestFocus method, swing must first be given a little time to create the dialog, layout the components, make everything visible, notify listeners, etc. Normally this takes a few milliseconds. I've found that after swing has completed all these actions, then it generates a window activated event to let you know it's ready for you. Add this WindowListener to your Dialog:
Hope this can help someone. |
What is the difference between a Component and an Object?
Location: http://www.jguru.com/faq/view.jsp?EID=49214
Created: May 15, 2000
Modified: 2000-05-16 11:06:51.115
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Tennneti Narahari (http://www.jguru.com/guru/viewbio.jsp?EID=37338
AComments and alternative answersComponentis a particular type ofObject.
This is what the standard Sun documentation says (JDK 1.2.2):
public abstract class Component extends Object implements ImageObserver, MenuContainer, SerializableA component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. Class Component can also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native opaque window.
| Useful
Author: joseph steveneson (http://www.jguru.com/guru/viewbio.jsp?EID=1351330), Nov 22, 2007 But what are control elements , components and objects |
Is there any way to create a full-screen (non-windowed) application in Java?
Location: http://www.jguru.com/faq/view.jsp?EID=53106
Created: May 21, 2000
Modified: 2000-06-29 15:13:58.849
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Thijs Stalenhoef (http://www.jguru.com/guru/viewbio.jsp?EID=31863
Comments and alternative answersYes and no.
Yes because Java has components that are non-windowed. Ironically these are called Window (AWT) and JWindow (Swing).
No because in Microsoft Windows the "Start bar" remains top-level and overlaps with your Window.
Other platforms may have the same problem. Note that you may be able to get a truly full-screen application by using JNI to call native methods on your platform, but that kills portability of your application.
Here is the AWT code to make a Window as large as the screen.
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class FullscreenWindowApp extends Window { private Button button; public FullscreenWindowApp() { super(new Frame()); button = new Button("Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); }}); setLayout(new FlowLayout()); add(button); //get the screen size Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //sets the location of the window to top left of screen setBounds(0,0,screenSize.width, screenSize.height); } public static void main(String[] args) { new FullscreenWindowApp().setVisible(true); } }The Swing code is nearly the same, using JWindow instead of Window,
| Creating a full-screen application in JAVA.
Author: oliver schramm (http://www.jguru.com/guru/viewbio.jsp?EID=848684), Apr 22, 2002 Hey guys, You can realize a full-screen application in the way that you extend the javax.swing.JWindow class. Note that you have to set the size according to the max. width and height. Unfortunately the JWindow class is quite simple so if you want to use, e.g. a menu you have to program it by hand. The code snip is added to this mail - it is quite easy due the fact that JWindow comes up with a JRootPane, to add additional features one has simply to copy the methods from the JFrame class to an extended class of JWindow. (Code for a full screen java application)
package de.comcar.browser.views;
import javax.swing.JWindow;
import javax.swing.JMenuBar;
public class JFullScreenWindow extends JWindow {
public JFullScreenWindow() {
super();
}
public void setJMenuBar(JMenuBar menubar) {
getRootPane().setMenuBar(menubar);
}
public void setTitle(String title) {
}
/*.. add methods whatever you like ..*/
public static void main(String[] args) {
...
setSize(maxwidht, maxheight);
}
}
|
| Full-Screen app
Author: marc breuer (http://www.jguru.com/guru/viewbio.jsp?EID=908848), Jun 10, 2002 I just came up with this piece of code, does the trick for me...(using JFrame java 1.3)
public void maximize(int w)
doesn't look too impressive but it works.... |
| Re: Full-Screen app
Author: Khizer Hayat (http://www.jguru.com/guru/viewbio.jsp?EID=1184717), Jul 8, 2004 well i wanted to ask one thing... as i was developing the application for my project i came up to know that i am facing a problem..the JWindow thing does not accept the feature of JTextField. why is that...like it is some kind of disabled feature...plz help me with this feature as i am using full screen to develop ma software |
| Here is a fullscreen JFrame (with JTextComponents working...)
Author: Roberto Mariottini (http://www.jguru.com/guru/viewbio.jsp?EID=1253993), Jul 19, 2005
public class MainWindow extends JFrame
{
public MainWindow()
{
super("Fullscreen");
getContentPane().setPreferredSize( Toolkit.getDefaultToolkit().getScreenSize());
pack();
setResizable(false);
show();
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, getContentPane());
Point l = getLocation();
l.x -= p.x;
l.y -= p.y;
setLocation(l);
}
});
}
...
}
|
I have a JTextField with more then one FocusListener. If the first-called focusLost fails (for validation), how can I stop the next focusLost call?
Location: http://www.jguru.com/faq/view.jsp?EID=53150
Created: May 21, 2000
Modified: 2000-05-21 08:08:19.818
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Sachin Shah (http://www.jguru.com/guru/viewbio.jsp?EID=50956
Comments and alternative answersBe very careful on this type of behavior...
First, listeners are intended to be completely independent of each other. There are two main reasons for this:
- A problem in one listener should not impact another listener
- The order of listener calls is not defined by the JavaBean specification
There are two exceptions to this rule:
- Constrained properties in a JavaBean talk to VetoableChangeListeners. The order of called listeners is not defined, but if any listener throws a PropertyVetoException, the remaining ones are not called.
- If you write your own events (under the Beans model, same type of pattern as existing AWT events), their behavior is defined by you. You can implement and document that they have a certain order or will stop when any listeners throw an exception.
I strongly recommend against this as it's not normal behavior for event handling
Note that you cannot simply make the text property constrained. The problem is that the setText method for a constrained JTextField could throw a PropertyVetoException, which isn't declared in the setText method of JTextField.
There are really two things you can do here:
- You could write a custom event for this, and implement/document that it calls listeners in the added order and that if any throw an exception, the others are not called.
- Add a single focusLost listener that does the multiple validations in order, stopping if any fail.
I'd recommend the second approach, like the following:
JTextField f = new JTextField(); f.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) {} public void focusLost(FocusEvent e) { try { validation1(); validation2(); validation3(); } catch(Exception e) { // report the validation error } } });If any of the validations fail (throw an exception), the others are not processed.
Finally, Don't forget that a call to setText() can change the value of the field!. You should override setText() and include validation as well.
| Swings
Author: archana ram (http://www.jguru.com/guru/viewbio.jsp?EID=1350064), Oct 30, 2007 hi, i have 3 jTextFields.i want to enable the submit button if all the 3 fields have text(only letters,no,_).I have done the validation.I have registered all the 3 fields to keylistener,mouselistener and focus listener but the problem is when i copy/paste values into the textfields after filling the last field(in any order) the ok button is still not enabled.Only whn press any button from kb r mouse release in any of the fields the button gets activated. Required to activate the button once all the fields have value entered either by typing manually r pasting some value.Need help asap,urgent!. |
How do I create a borderless Frame/JFrame?
Location: http://www.jguru.com/faq/view.jsp?EID=53155
Created: May 21, 2000
Modified: 2000-05-21 08:15:37.284
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by arun prathap (http://www.jguru.com/guru/viewbio.jsp?EID=43168
Instead of using a Frame/JFrame, use Window/JWindow.
The Window/JWindow classes (AWT/Swing) are borderless windows. Frame/JFrame are extensions of Window/JWindow that add borders, a titlebar, and the close/maximize/minimize controls found on most platforms.
How do I load a GIF file into a BufferedImage?
Location: http://www.jguru.com/faq/view.jsp?EID=53328
Created: May 21, 2000
Modified: 2000-05-23 09:02:20.763
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Alberto Lopez (http://www.jguru.com/guru/viewbio.jsp?EID=49150
To load a GIF into a BufferedImage, load the Image normally, get its size, then create an empty BufferedImage of the appropriate size and draw the Image into the buffered image's Graphics context.
The following demonstrates this:
import java.awt.*; import java.awt.image.*; import javax.swing.*; public class BuffIt { public static void main (String args[]) { // Get Image ImageIcon icon = new ImageIcon(args[0]); Image image = icon.getImage(); // Create empty BufferedImage, sized to Image BufferedImage buffImage = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); // Draw Image into BufferedImage Graphics g = buffImage.getGraphics(); g.drawImage(image, 0, 0, null); // Show success JFrame frame = new JFrame(); JLabel label = new JLabel(new ImageIcon(buffImage)); frame.getContentPane().add(label); frame.pack(); frame.show(); } }
How do I minimize a Java application window?
Location: http://www.jguru.com/faq/view.jsp?EID=53754
Created: May 22, 2000
Modified: 2000-05-23 08:56:49.783
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Amol Sant (http://www.jguru.com/guru/viewbio.jsp?EID=45958
Assumming you are using a java.awt.Frame or a subclass (including Swing's JFrame) as the Application Window, JDK1.2's java.awt.Frame class has the following method
public void setState(int state) Sets the state of this frame. Parameters: state - Frame.ICONIFIED if this frame is in iconic state; Frame.NORMAL if this frame is in normal state.Use the Frame.ICONIFIED value to minimize it.
How can I save an Image into a file with a standard image format like GIF or JPG?
Location: http://www.jguru.com/faq/view.jsp?EID=57055
Created: May 28, 2000
Modified: 2000-05-28 07:58:09.997
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Visesh S. V. (http://www.jguru.com/guru/viewbio.jsp?EID=36836
Once you have the Image object, for JPEG you can use and for GIF you can useComments and alternative answers
| http://java.about.com/compute/java/library/weekly/...
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 19, 2000 http://java.about.com/compute/java/library/weekly/aa090299.htm demonstrates the use of the JPEGCodec |
| jpeg image can be created easily
Author: suyash jain (http://www.jguru.com/guru/viewbio.jsp?EID=525878), Dec 24, 2001 Hi, After doing hard work on making jpeg images ,i got a very easy soution to save contents of graphics on frame/applet as jpeg file. If you are interested in getting that solution mail me at suyashjain2000@yahoo.com. I will be glading in helping you. Thanx |
| Re: jpeg image can be created easily
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Dec 24, 2001 If the solution is so good, post it. |
| Jpeg image can be created easily,How!!!.Just 2 steps.
Author: suyash jain (http://www.jguru.com/guru/viewbio.jsp?EID=525878), Dec 25, 2001 /////////////////////////////////// Step 1.Copy this code as makegif.java ////////////////////////////////// import java.awt.*; import java.io.*; import java.util.*; import java.lang.*; import java.awt.event.*; public class makegif extends Frame { static FileOutputStream dataOut = null; static JpegEncoder jpg; Image image; makegif() { super("Hwello"); setSize(100,100); setBackground(Color.green); show(); } public void paint(Graphics g) { g.drawString("Suyash Jain",50,50); image=createImage(size().width,size().height); g=image.getGraphics(); g.drawString("Suyash Jain",50,50); try{ dataOut = new FileOutputStream("101.jpeg"); jpg = new JpegEncoder(image,100,dataOut); jpg.Compress(); try { dataOut.close(); } catch(IOException e) {} }catch(Exception e){} } public boolean MouseDown(Event evt,int x,int y) { System.out.println("y"); return true; } public static void main(String s[]) { new makegif(); } } //////////////////////////////////// Step 2.Download JpegEncoder.java or Copy it from here: ////////////////////////////////// // Version 1.0a // Copyright (C) 1998, James R. Weeks and BioElectroMech. // Visit BioElectroMech at www.obrador.com. Email James@obrador.com. // See license.txt for details about the allowed used of this software. // This software is based in part on the work of the Independent JPEG Group. // See IJGreadme.txt for details about the Independent JPEG Group's license. // This encoder is inspired by the Java Jpeg encoder by Florian Raemy, // studwww.eurecom.fr/~raemy. // It borrows a great deal of code and structure from the Independent // Jpeg Group's Jpeg 6a library, Copyright Thomas G. Lane. // See license.txt for details. import java.applet.Applet; import java.awt.*; import java.awt.image.*; import java.io.*; import java.util.*; import java.lang.*; /* * JpegEncoder - The JPEG main program which performs a jpeg compression of * an image. */ public class JpegEncoder extends Frame { Thread runner; BufferedOutputStream outStream; Image image; JpegInfo JpegObj; Huffman Huf; DCT dct; int imageHeight, imageWidth; int Quality; int code; public static int[] jpegNaturalOrder = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, }; public JpegEncoder(Image image, int quality, OutputStream out) { MediaTracker tracker = new MediaTracker(this); tracker.addImage(image, 0); try { tracker.waitForID(0); } catch (InterruptedException e) { // Got to do something? } /* * Quality of the image. * 0 to 100 and from bad image quality, high compression to good * image quality low compression */ Quality=quality; /* * Getting picture information * It takes the Width, Height and RGB scans of the image. */ JpegObj = new JpegInfo(image); imageHeight=JpegObj.imageHeight; imageWidth=JpegObj.imageWidth; outStream = new BufferedOutputStream(out); dct = new DCT(Quality); Huf=new Huffman(imageWidth,imageHeight); } public void setQuality(int quality) { dct = new DCT(quality); } public int getQuality() { return Quality; } public void Compress() { WriteHeaders(outStream); WriteCompressedData(outStream); WriteEOI(outStream); try { outStream.flush(); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } public void WriteCompressedData(BufferedOutputStream outStream) { int offset, i, j, r, c,a ,b, temp = 0; int comp, xpos, ypos, xblockoffset, yblockoffset; float inputArray[][]; float dctArray1[][] = new float[8][8]; double dctArray2[][] = new double[8][8]; int dctArray3[] = new int[8*8]; /* * This method controls the compression of the image. * Starting at the upper left of the image, it compresses 8x8 blocks * of data until the entire image has been compressed. */ int lastDCvalue[] = new int[JpegObj.NumberOfComponents]; int zeroArray[] = new int[64]; // initialized to hold all zeros int Width = 0, Height = 0; int nothing = 0, not; int MinBlockWidth, MinBlockHeight; // This initial setting of MinBlockWidth and MinBlockHeight is done to // ensure they start with values larger than will actually be the case. MinBlockWidth = ((imageWidth%8 != 0) ? (int) (Math.floor((double) imageWidth/8.0) + 1)*8 : imageWidth); MinBlockHeight = ((imageHeight%8 != 0) ? (int) (Math.floor((double) imageHeight/8.0) + 1)*8: imageHeight); for (comp = 0; comp < JpegObj.NumberOfComponents; comp++) { MinBlockWidth = Math.min(MinBlockWidth, JpegObj.BlockWidth[comp]); MinBlockHeight = Math.min(MinBlockHeight, JpegObj.BlockHeight[comp]); } xpos = 0; for (r = 0; r < MinBlockHeight; r++) { for (c = 0; c < MinBlockWidth; c++) { xpos = c*8; ypos = r*8; for (comp = 0; comp < JpegObj.NumberOfComponents; comp++) { Width = JpegObj.BlockWidth[comp]; Height = JpegObj.BlockHeight[comp]; inputArray = (float[][]) JpegObj.Components[comp]; for(i = 0; i < JpegObj.VsampFactor[comp]; i++) { for(j = 0; j < JpegObj.HsampFactor[comp]; j++) { xblockoffset = j * 8; yblockoffset = i * 8; for (a = 0; a < 8; a++) { for (b = 0; b < 8; b++) { // I believe this is where the dirty line at the bottom of the image is // coming from. I need to do a check here to make sure I'm not reading past // image data. // This seems to not be a big issue right now. (04/04/98) dctArray1[a][b] = inputArray[ypos + yblockoffset + a][xpos + xblockoffset + b]; } } // The following code commented out because on some images this technique // results in poor right and bottom borders. // if ((!JpegObj.lastColumnIsDummy[comp] || c < Width - 1) && (!JpegObj.lastRowIsDummy[comp] || r < Height - 1)) { dctArray2 = dct.forwardDCT(dctArray1); dctArray3 = dct.quantizeBlock(dctArray2, JpegObj.QtableNumber[comp]); // } // else { // zeroArray[0] = dctArray3[0]; // zeroArray[0] = lastDCvalue[comp]; // dctArray3 = zeroArray; // } Huf.HuffmanBlockEncoder(outStream, dctArray3, lastDCvalue[comp], JpegObj.DCtableNumber[comp], JpegObj.ACtableNumber[comp]); lastDCvalue[comp] = dctArray3[0]; } } } } } Huf.flushBuffer(outStream); } public void WriteEOI(BufferedOutputStream out) { byte[] EOI = {(byte) 0xFF, (byte) 0xD9}; WriteMarker(EOI, out); } public void WriteHeaders(BufferedOutputStream out) { int i, j, index, offset, length; int tempArray[]; // the SOI marker byte[] SOI = {(byte) 0xFF, (byte) 0xD8}; WriteMarker(SOI, out); // The order of the following headers is quiet inconsequential. // the JFIF header byte JFIF[] = new byte[18]; JFIF[0] = (byte) 0xff; JFIF[1] = (byte) 0xe0; JFIF[2] = (byte) 0x00; JFIF[3] = (byte) 0x10; JFIF[4] = (byte) 0x4a; JFIF[5] = (byte) 0x46; JFIF[6] = (byte) 0x49; JFIF[7] = (byte) 0x46; JFIF[8] = (byte) 0x00; JFIF[9] = (byte) 0x01; JFIF[10] = (byte) 0x00; JFIF[11] = (byte) 0x00; JFIF[12] = (byte) 0x00; JFIF[13] = (byte) 0x01; JFIF[14] = (byte) 0x00; JFIF[15] = (byte) 0x01; JFIF[16] = (byte) 0x00; JFIF[17] = (byte) 0x00; WriteArray(JFIF, out); // Comment Header String comment = new String(); comment = JpegObj.getComment(); length = comment.length(); byte COM[] = new byte[length + 4]; COM[0] = (byte) 0xFF; COM[1] = (byte) 0xFE; COM[2] = (byte) ((length >> 8) & 0xFF); COM[3] = (byte) (length & 0xFF); java.lang.System.arraycopy(JpegObj.Comment.getBytes(), 0, COM, 4, JpegObj.Comment.length()); WriteArray(COM, out); // The DQT header // 0 is the luminance index and 1 is the chrominance index byte DQT[] = new byte[134]; DQT[0] = (byte) 0xFF; DQT[1] = (byte) 0xDB; DQT[2] = (byte) 0x00; DQT[3] = (byte) 0x84; offset = 4; for (i = 0; i < 2; i++) { DQT[offset++] = (byte) ((0 << 4) + i); tempArray = (int[]) dct.quantum[i]; for (j = 0; j < 64; j++) { DQT[offset++] = (byte) tempArray[jpegNaturalOrder[j]]; } } WriteArray(DQT, out); // Start of Frame Header byte SOF[] = new byte[19]; SOF[0] = (byte) 0xFF; SOF[1] = (byte) 0xC0; SOF[2] = (byte) 0x00; SOF[3] = (byte) 17; SOF[4] = (byte) JpegObj.Precision; SOF[5] = (byte) ((JpegObj.imageHeight >> 8) & 0xFF); SOF[6] = (byte) ((JpegObj.imageHeight) & 0xFF); SOF[7] = (byte) ((JpegObj.imageWidth >> 8) & 0xFF); SOF[8] = (byte) ((JpegObj.imageWidth) & 0xFF); SOF[9] = (byte) JpegObj.NumberOfComponents; index = 10; for (i = 0; i < SOF[9]; i++) { SOF[index++] = (byte) JpegObj.CompID[i]; SOF[index++] = (byte) ((JpegObj.HsampFactor[i] << 4) + JpegObj.VsampFactor[i]); SOF[index++] = (byte) JpegObj.QtableNumber[i]; } WriteArray(SOF, out); // The DHT Header byte DHT1[], DHT2[], DHT3[], DHT4[]; int bytes, temp, oldindex, intermediateindex; length = 2; index = 4; oldindex = 4; DHT1 = new byte[17]; DHT4 = new byte[4]; DHT4[0] = (byte) 0xFF; DHT4[1] = (byte) 0xC4; for (i = 0; i < 4; i++ ) { bytes = 0; DHT1[index++ - oldindex] = (byte) ((int[]) Huf.bits.elementAt(i))[0]; for (j = 1; j < 17; j++) { temp = ((int[]) Huf.bits.elementAt(i))[j]; DHT1[index++ - oldindex] =(byte) temp; bytes += temp; } intermediateindex = index; DHT2 = new byte[bytes]; for (j = 0; j < bytes; j++) { DHT2[index++ - intermediateindex] = (byte) ((int[]) Huf.val.elementAt(i))[j]; } DHT3 = new byte[index]; java.lang.System.arraycopy(DHT4, 0, DHT3, 0, oldindex); java.lang.System.arraycopy(DHT1, 0, DHT3, oldindex, 17); java.lang.System.arraycopy(DHT2, 0, DHT3, oldindex + 17, bytes); DHT4 = DHT3; oldindex = index; } DHT4[2] = (byte) (((index - 2) >> 8)& 0xFF); DHT4[3] = (byte) ((index -2) & 0xFF); WriteArray(DHT4, out); // Start of Scan Header byte SOS[] = new byte[14]; SOS[0] = (byte) 0xFF; SOS[1] = (byte) 0xDA; SOS[2] = (byte) 0x00; SOS[3] = (byte) 12; SOS[4] = (byte) JpegObj.NumberOfComponents; index = 5; for (i = 0; i < SOS[4]; i++) { SOS[index++] = (byte) JpegObj.CompID[i]; SOS[index++] = (byte) ((JpegObj.DCtableNumber[i] << 4) + JpegObj.ACtableNumber[i]); } SOS[index++] = (byte) JpegObj.Ss; SOS[index++] = (byte) JpegObj.Se; SOS[index++] = (byte) ((JpegObj.Ah << 4) + JpegObj.Al); WriteArray(SOS, out); } void WriteMarker(byte[] data, BufferedOutputStream out) { try { out.write(data, 0, 2); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } void WriteArray(byte[] data, BufferedOutputStream out) { int i, length; try { length = (((int) (data[2] & 0xFF)) << 8) + (int) (data[3] & 0xFF) + 2; out.write(data, 0, length); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } } // This class incorporates quality scaling as implemented in the JPEG-6a // library. /* * DCT - A Java implementation of the Discreet Cosine Transform */ class DCT { /** * DCT Block Size - default 8 */ public int N = 8; /** * Image Quality (0-100) - default 80 (good image / good compression) */ public int QUALITY = 80; public Object quantum[] = new Object[2]; public Object Divisors[] = new Object[2]; /** * Quantitization Matrix for luminace. */ public int quantum_luminance[] = new int[N*N]; public double DivisorsLuminance[] = new double[N*N]; /** * Quantitization Matrix for chrominance. */ public int quantum_chrominance[] = new int[N*N]; public double DivisorsChrominance[] = new double[N*N]; /** * Constructs a new DCT object. Initializes the cosine transform matrix * these are used when computing the DCT and it's inverse. This also * initializes the run length counters and the ZigZag sequence. Note that * the image quality can be worse than 25 however the image will be * extemely pixelated, usually to a block size of N. * * @param QUALITY The quality of the image (0 worst - 100 best) * */ public DCT(int QUALITY) { initMatrix(QUALITY); } /* * This method sets up the quantization matrix for luminance and * chrominance using the Quality parameter. */ private void initMatrix(int quality) { double[] AANscaleFactor = { 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379}; int i; int j; int index; int Quality; int temp; // converting quality setting to that specified in the jpeg_quality_scaling // method in the IJG Jpeg-6a C libraries Quality = quality; if (Quality <= 0) Quality = 1; if (Quality > 100) Quality = 100; if (Quality < 50) Quality = 5000 / Quality; else Quality = 200 - Quality * 2; // Creating the luminance matrix quantum_luminance[0]=16; quantum_luminance[1]=11; quantum_luminance[2]=10; quantum_luminance[3]=16; quantum_luminance[4]=24; quantum_luminance[5]=40; quantum_luminance[6]=51; quantum_luminance[7]=61; quantum_luminance[8]=12; quantum_luminance[9]=12; quantum_luminance[10]=14; quantum_luminance[11]=19; quantum_luminance[12]=26; quantum_luminance[13]=58; quantum_luminance[14]=60; quantum_luminance[15]=55; quantum_luminance[16]=14; quantum_luminance[17]=13; quantum_luminance[18]=16; quantum_luminance[19]=24; quantum_luminance[20]=40; quantum_luminance[21]=57; quantum_luminance[22]=69; quantum_luminance[23]=56; quantum_luminance[24]=14; quantum_luminance[25]=17; quantum_luminance[26]=22; quantum_luminance[27]=29; quantum_luminance[28]=51; quantum_luminance[29]=87; quantum_luminance[30]=80; quantum_luminance[31]=62; quantum_luminance[32]=18; quantum_luminance[33]=22; quantum_luminance[34]=37; quantum_luminance[35]=56; quantum_luminance[36]=68; quantum_luminance[37]=109; quantum_luminance[38]=103; quantum_luminance[39]=77; quantum_luminance[40]=24; quantum_luminance[41]=35; quantum_luminance[42]=55; quantum_luminance[43]=64; quantum_luminance[44]=81; quantum_luminance[45]=104; quantum_luminance[46]=113; quantum_luminance[47]=92; quantum_luminance[48]=49; quantum_luminance[49]=64; quantum_luminance[50]=78; quantum_luminance[51]=87; quantum_luminance[52]=103; quantum_luminance[53]=121; quantum_luminance[54]=120; quantum_luminance[55]=101; quantum_luminance[56]=72; quantum_luminance[57]=92; quantum_luminance[58]=95; quantum_luminance[59]=98; quantum_luminance[60]=112; quantum_luminance[61]=100; quantum_luminance[62]=103; quantum_luminance[63]=99; for (j = 0; j < 64; j++) { temp = (quantum_luminance[j] * Quality + 50) / 100; if ( temp <= 0) temp = 1; if (temp > 255) temp = 255; quantum_luminance[j] = temp; } index = 0; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { // The divisors for the LL&M method (the slow integer method used in // jpeg 6a library). This method is currently (04/04/98) incompletely // implemented. // DivisorsLuminance[index] = ((double) quantum_luminance[index]) << 3; // The divisors for the AAN method (the float method used in jpeg 6a library. DivisorsLuminance[index] = (double) ((double)1.0/((double) quantum_luminance[index] * AANscaleFactor[i] * AANscaleFactor[j] * (double) 8.0)); index++; } } // Creating the chrominance matrix quantum_chrominance[0]=17; quantum_chrominance[1]=18; quantum_chrominance[2]=24; quantum_chrominance[3]=47; quantum_chrominance[4]=99; quantum_chrominance[5]=99; quantum_chrominance[6]=99; quantum_chrominance[7]=99; quantum_chrominance[8]=18; quantum_chrominance[9]=21; quantum_chrominance[10]=26; quantum_chrominance[11]=66; quantum_chrominance[12]=99; quantum_chrominance[13]=99; quantum_chrominance[14]=99; quantum_chrominance[15]=99; quantum_chrominance[16]=24; quantum_chrominance[17]=26; quantum_chrominance[18]=56; quantum_chrominance[19]=99; quantum_chrominance[20]=99; quantum_chrominance[21]=99; quantum_chrominance[22]=99; quantum_chrominance[23]=99; quantum_chrominance[24]=47; quantum_chrominance[25]=66; quantum_chrominance[26]=99; quantum_chrominance[27]=99; quantum_chrominance[28]=99; quantum_chrominance[29]=99; quantum_chrominance[30]=99; quantum_chrominance[31]=99; quantum_chrominance[32]=99; quantum_chrominance[33]=99; quantum_chrominance[34]=99; quantum_chrominance[35]=99; quantum_chrominance[36]=99; quantum_chrominance[37]=99; quantum_chrominance[38]=99; quantum_chrominance[39]=99; quantum_chrominance[40]=99; quantum_chrominance[41]=99; quantum_chrominance[42]=99; quantum_chrominance[43]=99; quantum_chrominance[44]=99; quantum_chrominance[45]=99; quantum_chrominance[46]=99; quantum_chrominance[47]=99; quantum_chrominance[48]=99; quantum_chrominance[49]=99; quantum_chrominance[50]=99; quantum_chrominance[51]=99; quantum_chrominance[52]=99; quantum_chrominance[53]=99; quantum_chrominance[54]=99; quantum_chrominance[55]=99; quantum_chrominance[56]=99; quantum_chrominance[57]=99; quantum_chrominance[58]=99; quantum_chrominance[59]=99; quantum_chrominance[60]=99; quantum_chrominance[61]=99; quantum_chrominance[62]=99; quantum_chrominance[63]=99; for (j = 0; j < 64; j++) { temp = (quantum_chrominance[j] * Quality + 50) / 100; if ( temp <= 0) temp = 1; if (temp >= 255) temp = 255; quantum_chrominance[j] = temp; } index = 0; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { // The divisors for the LL&M method (the slow integer method used in // jpeg 6a library). This method is currently (04/04/98) incompletely // implemented. // DivisorsChrominance[index] = ((double) quantum_chrominance[index]) << 3; // The divisors for the AAN method (the float method used in jpeg 6a library. DivisorsChrominance[index] = (double) ((double)1.0/((double) quantum_chrominance[index] * AANscaleFactor[i] * AANscaleFactor[j] * (double)8.0)); index++; } } // quantum and Divisors are objects used to hold the appropriate matices quantum[0] = quantum_luminance; Divisors[0] = DivisorsLuminance; quantum[1] = quantum_chrominance; Divisors[1] = DivisorsChrominance; } /* * This method preforms forward DCT on a block of image data using * the literal method specified for a 2-D Discrete Cosine Transform. * It is included as a curiosity and can give you an idea of the * difference in the compression result (the resulting image quality) * by comparing its output to the output of the AAN method below. * It is ridiculously inefficient. */ // For now the final output is unusable. The associated quantization step // needs some tweaking. If you get this part working, please let me know. public double[][] forwardDCTExtreme(float input[][]) { double output[][] = new double[N][N]; double tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; double tmp10, tmp11, tmp12, tmp13; double z1, z2, z3, z4, z5, z11, z13; int i; int j; int v, u, x, y; for (v = 0; v < 8; v++) { for (u = 0; u < 8; u++) { for (x = 0; x < 8; x++) { for (y = 0; y < 8; y++) { output[v][u] += ((double)input[x][y])*Math.cos(((double)(2*x + 1)*(double)u*Math.PI)/(double)16)*Math.cos(((double)(2*y + 1)*(double)v*Math.PI)/(double)16); } } output[v][u] *= (double)(0.25)*((u == 0) ? ((double)1.0/Math.sqrt(2)) : (double) 1.0)*((v == 0) ? ((double)1.0/Math.sqrt(2)) : (double) 1.0); } } return output; } /* * This method preforms a DCT on a block of image data using the AAN * method as implemented in the IJG Jpeg-6a library. */ public double[][] forwardDCT(float input[][]) { double output[][] = new double[N][N]; double tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; double tmp10, tmp11, tmp12, tmp13; double z1, z2, z3, z4, z5, z11, z13; int i; int j; // Subtracts 128 from the input values for (i = 0; i < 8; i++) { for(j = 0; j < 8; j++) { output[i][j] = ((double)input[i][j] - (double)128.0); // input[i][j] -= 128; } } for (i = 0; i < 8; i++) { tmp0 = output[i][0] + output[i][7]; tmp7 = output[i][0] - output[i][7]; tmp1 = output[i][1] + output[i][6]; tmp6 = output[i][1] - output[i][6]; tmp2 = output[i][2] + output[i][5]; tmp5 = output[i][2] - output[i][5]; tmp3 = output[i][3] + output[i][4]; tmp4 = output[i][3] - output[i][4]; tmp10 = tmp0 + tmp3; tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; output[i][0] = tmp10 + tmp11; output[i][4] = tmp10 - tmp11; z1 = (tmp12 + tmp13) * (double) 0.707106781; output[i][2] = tmp13 + z1; output[i][6] = tmp13 - z1; tmp10 = tmp4 + tmp5; tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; z5 = (tmp10 - tmp12) * (double) 0.382683433; z2 = ((double) 0.541196100) * tmp10 + z5; z4 = ((double) 1.306562965) * tmp12 + z5; z3 = tmp11 * ((double) 0.707106781); z11 = tmp7 + z3; z13 = tmp7 - z3; output[i][5] = z13 + z2; output[i][3] = z13 - z2; output[i][1] = z11 + z4; output[i][7] = z11 - z4; } for (i = 0; i < 8; i++) { tmp0 = output[0][i] + output[7][i]; tmp7 = output[0][i] - output[7][i]; tmp1 = output[1][i] + output[6][i]; tmp6 = output[1][i] - output[6][i]; tmp2 = output[2][i] + output[5][i]; tmp5 = output[2][i] - output[5][i]; tmp3 = output[3][i] + output[4][i]; tmp4 = output[3][i] - output[4][i]; tmp10 = tmp0 + tmp3; tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; output[0][i] = tmp10 + tmp11; output[4][i] = tmp10 - tmp11; z1 = (tmp12 + tmp13) * (double) 0.707106781; output[2][i] = tmp13 + z1; output[6][i] = tmp13 - z1; tmp10 = tmp4 + tmp5; tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; z5 = (tmp10 - tmp12) * (double) 0.382683433; z2 = ((double) 0.541196100) * tmp10 + z5; z4 = ((double) 1.306562965) * tmp12 + z5; z3 = tmp11 * ((double) 0.707106781); z11 = tmp7 + z3; z13 = tmp7 - z3; output[5][i] = z13 + z2; output[3][i] = z13 - z2; output[1][i] = z11 + z4; output[7][i] = z11 - z4; } return output; } /* * This method quantitizes data and rounds it to the nearest integer. */ public int[] quantizeBlock(double inputData[][], int code) { int outputData[] = new int[N*N]; int i, j; int index; index = 0; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { // The second line results in significantly better compression. outputData[index] = (int)(Math.round(inputData[i][j] * (((double[]) (Divisors[code]))[index]))); // outputData[index] = (int)(((inputData[i][j] * (((double[]) (Divisors[code]))[index])) + 16384.5) -16384); index++; } } return outputData; } /* * This is the method for quantizing a block DCT'ed with forwardDCTExtreme * This method quantitizes data and rounds it to the nearest integer. */ public int[] quantizeBlockExtreme(double inputData[][], int code) { int outputData[] = new int[N*N]; int i, j; int index; index = 0; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { outputData[index] = (int)(Math.round(inputData[i][j] / (double)(((int[]) (quantum[code]))[index]))); index++; } } return outputData; } } // This class was modified by James R. Weeks on 3/27/98. // It now incorporates Huffman table derivation as in the C jpeg library // from the IJG, Jpeg-6a. class Huffman { int bufferPutBits, bufferPutBuffer; public int ImageHeight; public int ImageWidth; public int DC_matrix0[][]; public int AC_matrix0[][]; public int DC_matrix1[][]; public int AC_matrix1[][]; public Object DC_matrix[]; public Object AC_matrix[]; public int code; public int NumOfDCTables; public int NumOfACTables; public int[] bitsDCluminance = { 0x00, 0, 1, 5, 1, 1,1,1,1,1,0,0,0,0,0,0,0}; public int[] valDCluminance = { 0,1,2,3,4,5,6,7,8,9,10,11 }; public int[] bitsDCchrominance = { 0x01,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0 }; public int[] valDCchrominance = { 0,1,2,3,4,5,6,7,8,9,10,11 }; public int[] bitsACluminance = {0x10,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d }; public int[] valACluminance = { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa }; public int[] bitsACchrominance = { 0x11,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77 };; public int[] valACchrominance = { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa }; public Vector bits; public Vector val; /* * jpegNaturalOrder[i] is the natural-order position of the i'th element * of zigzag order. */ public static int[] jpegNaturalOrder = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, }; /* * The Huffman class constructor */ public Huffman(int Width,int Height) { bits = new Vector(); bits.addElement(bitsDCluminance); bits.addElement(bitsACluminance); bits.addElement(bitsDCchrominance); bits.addElement(bitsACchrominance); val = new Vector(); val.addElement(valDCluminance); val.addElement(valACluminance); val.addElement(valDCchrominance); val.addElement(valACchrominance); initHuf(); code=code; ImageWidth=Width; ImageHeight=Height; } /** * HuffmanBlockEncoder run length encodes and Huffman encodes the quantized * data. **/ public void HuffmanBlockEncoder(BufferedOutputStream outStream, int zigzag[], int prec, int DCcode, int ACcode) { int temp, temp2, nbits, k, r, i; NumOfDCTables = 2; NumOfACTables = 2; // The DC portion temp = temp2 = zigzag[0] - prec; if(temp < 0) { temp = -temp; temp2--; } nbits = 0; while (temp != 0) { nbits++; temp >>= 1; } // if (nbits > 11) nbits = 11; bufferIt(outStream, ((int[][])DC_matrix[DCcode])[nbits][0], ((int[][])DC_matrix[DCcode])[nbits][1]); // The arguments in bufferIt are code and size. if (nbits != 0) { bufferIt(outStream, temp2, nbits); } // The AC portion r = 0; for (k = 1; k < 64; k++) { if ((temp = zigzag[jpegNaturalOrder[k]]) == 0) { r++; } else { while (r > 15) { bufferIt(outStream, ((int[][])AC_matrix[ACcode])[0xF0][0], ((int[][])AC_matrix[ACcode])[0xF0][1]); r -= 16; } temp2 = temp; if (temp < 0) { temp = -temp; temp2--; } nbits = 1; while ((temp >>= 1) != 0) { nbits++; } i = (r << 4) + nbits; bufferIt(outStream, ((int[][])AC_matrix[ACcode])[i][0], ((int[][])AC_matrix[ACcode])[i][1]); bufferIt(outStream, temp2, nbits); r = 0; } } if (r > 0) { bufferIt(outStream, ((int[][])AC_matrix[ACcode])[0][0], ((int[][])AC_matrix[ACcode])[0][1]); } } // Uses an integer long (32 bits) buffer to store the Huffman encoded bits // and sends them to outStream by the byte. void bufferIt(BufferedOutputStream outStream, int code,int size) { int PutBuffer = code; int PutBits = bufferPutBits; PutBuffer &= (1 << size) - 1; PutBits += size; PutBuffer <<= 24 - PutBits; PutBuffer |= bufferPutBuffer; while(PutBits >= 8) { int c = ((PutBuffer >> 16) & 0xFF); try { outStream.write(c); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } if (c == 0xFF) { try { outStream.write(0); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } PutBuffer <<= 8; PutBits -= 8; } bufferPutBuffer = PutBuffer; bufferPutBits = PutBits; } void flushBuffer(BufferedOutputStream outStream) { int PutBuffer = bufferPutBuffer; int PutBits = bufferPutBits; while (PutBits >= 8) { int c = ((PutBuffer >> 16) & 0xFF); try { outStream.write(c); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } if (c == 0xFF) { try { outStream.write(0); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } PutBuffer <<= 8; PutBits -= 8; } if (PutBits > 0) { int c = ((PutBuffer >> 16) & 0xFF); try { outStream.write(c); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } } /* * Initialisation of the Huffman codes for Luminance and Chrominance. * This code results in the same tables created in the IJG Jpeg-6a * library. */ public void initHuf() { DC_matrix0=new int[12][2]; DC_matrix1=new int[12][2]; AC_matrix0=new int[255][2]; AC_matrix1=new int[255][2]; DC_matrix = new Object[2]; AC_matrix = new Object[2]; int p, l, i, lastp, si, code; int[] huffsize = new int[257]; int[] huffcode= new int[257]; /* * init of the DC values for the chrominance * [][0] is the code [][1] is the number of bit */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= bitsDCchrominance[l]; i++) { huffsize[p++] = l; } } huffsize[p] = 0; lastp = p; code = 0; si = huffsize[0]; p = 0; while(huffsize[p] != 0) { while(huffsize[p] == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } for (p = 0; p < lastp; p++) { DC_matrix1[valDCchrominance[p]][0] = huffcode[p]; DC_matrix1[valDCchrominance[p]][1] = huffsize[p]; } /* * Init of the AC hufmann code for the chrominance * matrix [][][0] is the code & matrix[][][1] is the number of bit needed */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= bitsACchrominance[l]; i++) { huffsize[p++] = l; } } huffsize[p] = 0; lastp = p; code = 0; si = huffsize[0]; p = 0; while(huffsize[p] != 0) { while(huffsize[p] == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } for (p = 0; p < lastp; p++) { AC_matrix1[valACchrominance[p]][0] = huffcode[p]; AC_matrix1[valACchrominance[p]][1] = huffsize[p]; } /* * init of the DC values for the luminance * [][0] is the code [][1] is the number of bit */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= bitsDCluminance[l]; i++) { huffsize[p++] = l; } } huffsize[p] = 0; lastp = p; code = 0; si = huffsize[0]; p = 0; while(huffsize[p] != 0) { while(huffsize[p] == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } for (p = 0; p < lastp; p++) { DC_matrix0[valDCluminance[p]][0] = huffcode[p]; DC_matrix0[valDCluminance[p]][1] = huffsize[p]; } /* * Init of the AC hufmann code for luminance * matrix [][][0] is the code & matrix[][][1] is the number of bit */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= bitsACluminance[l]; i++) { huffsize[p++] = l; } } huffsize[p] = 0; lastp = p; code = 0; si = huffsize[0]; p = 0; while(huffsize[p] != 0) { while(huffsize[p] == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } for (int q = 0; q < lastp; q++) { AC_matrix0[valACluminance[q]][0] = huffcode[q]; AC_matrix0[valACluminance[q]][1] = huffsize[q]; } DC_matrix[0] = DC_matrix0; DC_matrix[1] = DC_matrix1; AC_matrix[0] = AC_matrix0; AC_matrix[1] = AC_matrix1; } } /* * JpegInfo - Given an image, sets default information about it and divides * it into its constituant components, downsizing those that need to be. */ class JpegInfo { String Comment; public Image imageobj; public int imageHeight; public int imageWidth; public int BlockWidth[]; public int BlockHeight[]; // the following are set as the default public int Precision = 8; public int NumberOfComponents = 3; public Object Components[]; public int[] CompID = {1, 2, 3}; public int[] HsampFactor = {1, 1, 1}; public int[] VsampFactor = {1, 1, 1}; public int[] QtableNumber = {0, 1, 1}; public int[] DCtableNumber = {0, 1, 1}; public int[] ACtableNumber = {0, 1, 1}; public boolean[] lastColumnIsDummy = {false, false, false}; public boolean[] lastRowIsDummy = {false, false, false}; public int Ss = 0; public int Se = 63; public int Ah = 0; public int Al = 0; public int compWidth[], compHeight[]; public int MaxHsampFactor; public int MaxVsampFactor; public JpegInfo(Image image) { Components = new Object[NumberOfComponents]; compWidth = new int[NumberOfComponents]; compHeight = new int[NumberOfComponents]; BlockWidth = new int[NumberOfComponents]; BlockHeight = new int[NumberOfComponents]; imageobj = image; imageWidth = image.getWidth(null); imageHeight = image.getHeight(null); Comment = "JPEG Encoder Copyright 1998, James R. Weeks and BioElectroMech. "; getYCCArray(); } public void setComment(String comment) { Comment.concat(comment); } public String getComment() { return Comment; } /* * This method creates and fills three arrays, Y, Cb, and Cr using the * input image. */ private void getYCCArray() { int values[] = new int[imageWidth * imageHeight]; int r, g, b, y, x; // In order to minimize the chance that grabPixels will throw an exception // it may be necessary to grab some pixels every few scanlines and process // those before going for more. The time expense may be prohibitive. // However, for a situation where memory overhead is a concern, this may be // the only choice. PixelGrabber grabber = new PixelGrabber(imageobj.getSource(), 0, 0, imageWidth, imageHeight, values, 0, imageWidth); MaxHsampFactor = 1; MaxVsampFactor = 1; for (y = 0; y < NumberOfComponents; y++) { MaxHsampFactor = Math.max(MaxHsampFactor, HsampFactor[y]); MaxVsampFactor = Math.max(MaxVsampFactor, VsampFactor[y]); } for (y = 0; y < NumberOfComponents; y++) { compWidth[y] = (((imageWidth%8 != 0) ? ((int) Math.ceil((double) imageWidth/8.0))*8 : imageWidth)/MaxHsampFactor)*HsampFactor[y]; if (compWidth[y] != ((imageWidth/MaxHsampFactor)*HsampFactor[y])) { lastColumnIsDummy[y] = true; } // results in a multiple of 8 for compWidth // this will make the rest of the program fail for the unlikely // event that someone tries to compress an 16 x 16 pixel image // which would of course be worse than pointless BlockWidth[y] = (int) Math.ceil((double) compWidth[y]/8.0); compHeight[y] = (((imageHeight%8 != 0) ? ((int) Math.ceil((double) imageHeight/8.0))*8: imageHeight)/MaxVsampFactor)*VsampFactor[y]; if (compHeight[y] != ((imageHeight/MaxVsampFactor)*VsampFactor[y])) { lastRowIsDummy[y] = true; } BlockHeight[y] = (int) Math.ceil((double) compHeight[y]/8.0); } try { if(grabber.grabPixels() != true) { try { throw new AWTException("Grabber returned false: " + grabber.status()); } catch (Exception e) {}; } } catch (InterruptedException e) {}; float Y[][] = new float[compHeight[0]][compWidth[0]]; float Cr1[][] = new float[compHeight[0]][compWidth[0]]; float Cb1[][] = new float[compHeight[0]][compWidth[0]]; float Cb2[][] = new float[compHeight[1]][compWidth[1]]; float Cr2[][] = new float[compHeight[2]][compWidth[2]]; int index = 0; for (y = 0; y < imageHeight; ++y) { for (x = 0; x < imageWidth; ++x) { r = ((values[index] >> 16) & 0xff); g = ((values[index] >> 8) & 0xff); b = (values[index] & 0xff); // The following three lines are a more correct color conversion but // the current conversion technique is sufficient and results in a higher // compression rate. // Y[y][x] = 16 + (float)(0.8588*(0.299 * (float)r + 0.587 * (float)g + 0.114 * (float)b )); // Cb1[y][x] = 128 + (float)(0.8784*(-0.16874 * (float)r - 0.33126 * (float)g + 0.5 * (float)b)); // Cr1[y][x] = 128 + (float)(0.8784*(0.5 * (float)r - 0.41869 * (float)g - 0.08131 * (float)b)); Y[y][x] = (float)((0.299 * (float)r + 0.587 * (float)g + 0.114 * (float)b)); Cb1[y][x] = 128 + (float)((-0.16874 * (float)r - 0.33126 * (float)g + 0.5 * (float)b)); Cr1[y][x] = 128 + (float)((0.5 * (float)r - 0.41869 * (float)g - 0.08131 * (float)b)); index++; } } // Need a way to set the H and V sample factors before allowing downsampling. // For now (04/04/98) downsampling must be hard coded. // Until a better downsampler is implemented, this will not be done. // Downsampling is currently supported. The downsampling method here // is a simple box filter. Components[0] = Y; // Cb2 = DownSample(Cb1, 1); Components[1] = Cb1; // Cr2 = DownSample(Cr1, 2); Components[2] = Cr1; } float[][] DownSample(float[][] C, int comp) { int inrow, incol; int outrow, outcol; float output[][]; int temp; int bias; inrow = 0; incol = 0; output = new float[compHeight[comp]][compWidth[comp]]; for (outrow = 0; outrow < compHeight[comp]; outrow++) { bias = 1; for (outcol = 0; outcol < compWidth[comp]; outcol++) { output[outrow][outcol] = (C[inrow][incol++] + C[inrow++][incol--] + C[inrow][incol++] + C[inrow--][incol++] + (float)bias)/(float)4.0; bias ^= 3; } inrow += 2; incol = 0; } return output; } } ////////////////////////////////////// Compile makegif.java & run ,there will be one window when u will resize that window,this code will create 101.jpeg image file according to graphics on Frame. Still having problem contact to me. |
| Re: Jpeg image can be created easily,How!!!.Just 2 steps.
Author: David KLECEL (http://www.jguru.com/guru/viewbio.jsp?EID=904135), Jun 5, 2002 i can't compile makegif.java cause even if JpegEncoder.java is compiled it doesn't resolve JpegEncoder class in makegif.java. |
| Re: jpeg image can be created easily
Author: amitkhosla007 khosla (http://www.jguru.com/guru/viewbio.jsp?EID=1264124), Sep 25, 2005 sayush ...i trying to generate barcode font of my own....i m just a biginner in the java...please suggest me to how can save my contents as jpg or bmp image ...and how can i use these saved images again in th new program |
| The best solution to save images into GIF files
Author: Gif4J Software (http://www.jguru.com/guru/viewbio.jsp?EID=1207827), Oct 28, 2004 Gif4J Library is new and the most powerful GIF animation library. You can easily encode images, add watermarks, apply morphing filters and much more. Please check www.gif4j.com for more info. |
Can I prevent the mouse from moving out of a Dialog or Frame?
Location: http://www.jguru.com/faq/view.jsp?EID=58813
Created: May 28, 2000
Modified: 2000-05-28 08:21:31.919
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by G.Shankar Narayanan (http://www.jguru.com/guru/viewbio.jsp?EID=29514
You can't. Standard Java provides no controls to limit where the mouse can go.Comments and alternative answers
| dirty workaround for some cases
Author: Dennis Meyer (http://www.jguru.com/guru/viewbio.jsp?EID=551660), Feb 24, 2003 It is possible to use java.awt.Robot since 1.3. You can invoke the method mouseMove(int x,int y) to move the mousePointer on your screen (not frame!). If you invoke it in your mouseBehavior you can interact on mousemovement. This is in fact very dirty but seems to be the only workaround if you need this feature by force.
Be careful using robot. It needs extended X - functionality of your OS. Described in the JavaDoc. |
I include a JPanel with a null layout in a JScrollPane, and it doesn't display the scrollbars. Why?
Location: http://www.jguru.com/faq/view.jsp?EID=58838
Created: May 28, 2000
Modified: 2000-05-28 08:36:31.631
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by muralidhar reddy gandham (http://www.jguru.com/guru/viewbio.jsp?EID=45444
Comments and alternative answersFirst, always use layout managers when constructing a GUI! See Effective Layout Management (http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr) for details on why, what layout managers are and how to use them.
Second, a JScrollPane asks the contained component for its preferred size. A JPanel with no layout manager returns (0,0), which tells the JScrollPane that it doesn't need to provide scrollbars.
A JPanel with a layout manager delegates the preferred size request to its layout manager, which computes a size that should make all the contained components happy. When this, (usually) non-zero size is returned, the JScrollPane will provide scrollbars if there is not enough room.
| JscrollPane containing JPanel with Null Layout
Author: Ash Kul (http://www.jguru.com/guru/viewbio.jsp?EID=1044565), Jan 8, 2003 I have a similar problem. As per your suggestion I am setting prefferedSize and Size of the JPanel I am adding to JScrollPane but still its not showing scroll bars. Its seems like JPanel is printing on the top of JScrollPane on JFrame insted of inside the ScrollPane. Here is something I am doing.. JFrame.setSize(700, 700); JFrame.getContentPane().setLayout(null); . . . . JPanel.setLayout(null); JPanel.setBounds(10, 10, 900, 1200); JPanel.setSize(900, 1200); JPanel.setPrefferedSize(900, 1200); . . . JScrollPane.setBounds(10, 10, 600, 600); JScrollPane.add(JPanel); JFrame.getContentPane().add(JScrollPane); what do you think I am doing wrong??? Thank you |
| Re: JscrollPane containing JPanel with Null Layout
Author: Shark saasa (http://www.jguru.com/guru/viewbio.jsp?EID=1188347), Jul 24, 2004 I have the same problem. Someone can help me? |
| Re[2]: JscrollPane containing JPanel with Null Layout
Author: patibandla srinath (http://www.jguru.com/guru/viewbio.jsp?EID=1216628), Dec 16, 2004 Hey, if u want to make ur panel visible u have to add one more line suppose JPanel panel1=new JPanel(); JScrollPane pane=new JScrollPane(); pane.setViewportView(panel1); then u can see Ur panel Good Luck Guys! |
| Re[2]: JscrollPane containing JPanel with Null Layout
Author: dinesh babu (http://www.jguru.com/guru/viewbio.jsp?EID=1334423), Apr 19, 2007 I had this problem.. I got it solved by using setBounds of scrollpane.. jList1.setBounds(new Rectangle(26, 93, 129, 107)); JScrollPane jsp=new JScrollPane(jList1); jsp.setBounds(new Rectangle(26, 93, 129, 107)); this.getContentPane().add(jsp);Its working for me with null layout.. Now list box visible with scrollbar as well. |
| Re: JscrollPane containing JPanel with Null Layout
Author: Dave Carpeneto (http://www.jguru.com/guru/viewbio.jsp?EID=1287485), Mar 8, 2006 It seems to not matter - if you want to use a scroll pane & absolute positioning, you need to write your own 'dummy' layout manager that returns a Dimension for preferredLayoutSize() tht matches your Pane's size. The other routines need to be implemented for compile purposes, but are not important. |
| Re[2]: JscrollPane containing JPanel with Null Layout
Author: Jaime Acosta (http://www.jguru.com/guru/viewbio.jsp?EID=1310821), Aug 30, 2006 Or you can always just call jPanel1.setPreferredSize(x,y); |
| Re[3]: JscrollPane containing JPanel with Null Layout
Author: yugin Raiman (http://www.jguru.com/guru/viewbio.jsp?EID=1336930), May 15, 2007 Hi, after all these comments I still cannot add ScrollBar with a null layout. can somebody post a samlpe of code, I need help... plz. |
| Re[4]: JscrollPane containing JPanel with Null Layout
Author: aly dik (http://www.jguru.com/guru/viewbio.jsp?EID=1372157), Oct 26, 2008 Hi guys if you found a solution of the probleme concerning the scrollPane containing JPanel with a null solution, shared it with me. i have the same probleme since the beginning of this week and till now no solution. help me if you can. bye and hope read you soon |
| Re[5]: JscrollPane containing JPanel with Null Layout
Author: aly dik (http://www.jguru.com/guru/viewbio.jsp?EID=1372157), Oct 26, 2008 i found the solution. suppose that your null layout JPanel is panel and your scrollPane is scroll. you recode the appearance of the scrollbar by this ways. if(panel .getSize().height > scroll.getSize().height){ scroll.createVerticalScrollBar(); } if(panel.getSize().width>scroll.getSize().width){ scroll.createHorizontalScrollBar(); } |
| Solution found
Author: sirajuddin choudhary (http://www.jguru.com/guru/viewbio.jsp?EID=1529081), Jan 9, 2010 Thanks for telling that JscrollPane looks for preferred size :) I was using a panel with layout manager set as null. and i was not getting any solution for it. But you said that JScrollPane looks for preferred size so using panel.setPreferredSize i changed it from 0,0 to size of my panel and it works, now i am able to see scroll bars |
| Re: Solution found
Author: lalchand Omprakash (http://www.jguru.com/guru/viewbio.jsp?EID=1571619), Aug 21, 2010 need sample example . |
How can I get the size of an applet's area, as defined in HTML?
Location: http://www.jguru.com/faq/view.jsp?EID=59925
Created: May 30, 2000
Modified: 2000-05-30 08:30:27.136
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Branislav Stofko (http://www.jguru.com/guru/viewbio.jsp?EID=59366
To get the applet's size, use the getWidth(), getHeight(), and getDimension() methods. The getWidth() and getHeight() methods were added with Java 1.2. Keep in mind an applet is just a glorified component.
I show a PopupMenu from a mouseEntered event. How can I close it on a mouseExited event?
Location: http://www.jguru.com/faq/view.jsp?EID=66153
Created: Jun 6, 2000
Modified: 2000-06-06 15:43:47.417
Author: Senthil D. Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=16254)
Question originally posed by John Twomey (http://www.jguru.com/guru/viewbio.jsp?EID=48460
Comments and alternative answersIn the mouseExited method you can do the following :
public void mouseExited(MouseEvent event) { if ( _popupMenu.isVisible()) _popupMenu.setVisible(false); }
| That works for a JPopupmenu but there is no setVis...
Author: John Twomey (http://www.jguru.com/guru/viewbio.jsp?EID=48460), Jun 10, 2000 That works for a JPopupmenu but there is no setVisible() method for AWT PopupMenu. I am using this in an Applet so I am trying to avoid Swing due to browser support. The only way I can see to close the Popup without choosing a menu item, is to hit the esc key. Does anyone know how to do this with code. I know there is a robot (or similar) class in 1.3 but again, would that work with present or slightly older browsers (VM's). Anyone have any suggestions? |
|
To work around the missing hide method, I
removed...
Author: Michel Dalal (http://www.jguru.com/guru/viewbio.jsp?EID=253436), Nov 14, 2000 To work around the missing hide method, I removed the AWT PopupMenu object from the component. Its not pretty but it works. i.e. // Force the hiding of the popup. component.remove(popupMenu); // Add it back for later use. component.add(popupMenu); |
How can I show a modal dialog box from an Applet (in Internet Explorer)?
Location: http://www.jguru.com/faq/view.jsp?EID=67354
Created: Jun 7, 2000
Modified: 2000-09-14 08:30:33.177
Author: Krzysztof Raciniewski (http://www.jguru.com/guru/viewbio.jsp?EID=32358)
Question originally posed by d sdvsd (http://www.jguru.com/guru/viewbio.jsp?EID=56415
There is article about this on the Microsoft web site (http://www.microsoft.com/java/sdk/40/kb/177753.htm) Remember that this works only on Internet Explorer and is not portable.Comments and alternative answers
| Modal box
Author: Sylvain A. (http://www.jguru.com/guru/viewbio.jsp?EID=1130465), Nov 26, 2003
public Dialog createMessageBox()
{
Frame f = null;
Container c = this; // Applet
while(c != null && !(c instanceof Frame))
c = c.getParent();
if (c == null)
f = new Frame(); // won't be modal
else
f = (Frame)c; // will be modal !
return(new Dialog(f, true));
}
// tested on Internet Explorer - Netscape - Mozilla - Windows - Mac - Linux |
What is Java 2 AWT Native Interface (JAWT) and how can I use it for native rendering?
Location: http://www.jguru.com/faq/view.jsp?EID=66689
Created: Jun 7, 2000
Modified: 2000-06-07 10:18:23.536
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
There is an article at JavaWorld that explains this process:
http://www.javaworld.com/javaworld/javatips/f_jw-javatip86.html
How does one show a message in a popup-window from an applet?
Location: http://www.jguru.com/faq/view.jsp?EID=56939
Created: Jun 8, 2000
Modified: 2000-06-08 02:02:57.833
Author: Paolo Rocca (http://www.jguru.com/guru/viewbio.jsp?EID=56889)
Question originally posed by Svend-Aage Nielsen (http://www.jguru.com/guru/viewbio.jsp?EID=53075
Just popup a Frame from your applet. This is your applet://File hello.java import java.awt.*; import java.applet.*; public class hello extends Applet { Frame f = new helloFrame (); public void init() { setLayout (new FlowLayout()); add (new Button("Click me")); /* this button allows you to pop up a frame */ } public boolean action (Event evt, Object arg) { if (arg.equals("Click me")) { f.show(); // Show the popup window f.resize (150, 100); // and resize it return true; } else return false; } }
And this is your frame:
// File helloFrame.java import java.awt.*; import java.applet.*; public class helloFrame extends Frame { public helloFrame() { setLayout (new FlowLayout()); setTitle ("Hello!"); // The window title add (new Label ("This is the message")); // Your message add (new Button ("Ok")); // The button to quit } public boolean action (Event evt, Object arg) { if (arg.equals("Ok")) { dispose(); return true; } else return false; } }
You have to compile helloFrame first, and then you can compile hello. When you click on the button "click me" a popup window will be showed, with your message in it.
Can I use a mouse wheel with Swing controls?
Location: http://www.jguru.com/faq/view.jsp?EID=64267
Created: Jun 8, 2000
Modified: 2000-07-06 21:21:24.949
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Andreas Larsson (http://www.jguru.com/guru/viewbio.jsp?EID=49213
Java doesn't support this at this time. http://developer.java.sun.com/developer/bugParade/bugs/4289845.html shows it as an RFE, committed to the Merlin release, which I believe is 1.4.Comments and alternative answersIf you don't care to wait for 1.4, see http://www.codeproject.com/java/mousewheel.asp for how to add it with the help of JNI.
| The Karmira's debugger apperantly supports it.
It is...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Jun 10, 2000 The Karmira's debugger apperantly supports it. It is written in java + swing. |
| A far easier option: Just change your JFrame subclass...
Author: Ken Carpenter (http://www.jguru.com/guru/viewbio.jsp?EID=51991), Feb 28, 2001 A far easier option: Just change your JFrame subclass to JMouseWheelFrame, then include the .jar file from the URL below in your project and add the line "import gui.JMouseWheelFrame". Boom! Instant mouse wheel support in all scrollable controls in that frame. http://www.rosbaldeston.freeserve.co.uk/java/mousewheel/ |
How do i add support for Multiple Monitors in my Swing Application?
Location: http://www.jguru.com/faq/view.jsp?EID=70450
Created: Jun 9, 2000
Modified: 2000-06-09 10:56:56.289
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Multiple monitor support has been added to JDK1.3:http://java.sun.com/j2se/1.3/docs/guide/2d/new_features.html http://java.sun.com/j2se/1.3/docs/guide/2d/spec/j2d-awt.fm6.html#70485
How can I create internationalized accelerator keys (not mnemonics) for menu items? (The same menu item could have different accelerator keys for different languages.)
Location: http://www.jguru.com/faq/view.jsp?EID=61410
Created: Jun 9, 2000
Modified: 2000-06-09 11:08:11.346
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Anil Punjabi (http://www.jguru.com/guru/viewbio.jsp?EID=23218
Comments and alternative answersUse the following API
KeyStroke.getKeyStroke(String stringFormOfKeyStroke)as in the following code:
public static KeyStroke getKeyStroke(String s)Parse a string with the following syntax and return an a KeyStroke:
"<modifiers>* <key>" modifiers := shift | control | meta | alt | button1 | button2 | button3 key := KeyEvent keycode name, i.e. the name following "VK_".Here are some examples:
"INSERT" => new KeyStroke(0, KeyEvent.VK_INSERT); "control DELETE" => new KeyStroke(InputEvent.CTRL_MASK, KeyEvent.VK_DELETE); "alt shift X" => new KeyStroke(InputEvent.ALT_MASK | InputEvent.SHIFT_MASK, KeyEvent.VK_X);Now, it becomes a matter of loading a locale based ResourceBundle which contains the map. For details on ResourceBundle please see the following URL -
http://java.sun.com/products/jdk/1.2/docs/api/java/util/ResourceBundle.html
To keep the uniqueness of the key is the responsibility of the person who localizes the resource bundle. You could write a GUI to wrap that functionality.
| Java,JSP:jsptags,Struts
Author: Ratna kumari M (http://www.jguru.com/guru/viewbio.jsp?EID=1327346), Mar 20, 2007 How can i populate dropdown list in struts Using Jsptags. |
What audio file formats are supported with the Java 2 platform? Is there a difference between 1.2 and 1.3?
Location: http://www.jguru.com/faq/view.jsp?EID=72431
Created: Jun 25, 2000
Modified: 2000-06-25 09:18:12.09
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
According to http://java.sun.com/products/jdk/1.2/docs/guide/sound/index.html:The following audio file formats are supported: AIFF, AU and WAV. In addition, the following MIDI-based song file formats are supported: MIDI TYPE 0, MIDI TYPE 1, and RMF.
The 1.3 documentation [http://java.sun.com/j2se/1.3/docs/guide/sound/index.html] do not seem to add more audio formats, just a software-based mixer and access to the MIDI hardware.
Prior to the Java 2 platform, for Java 1.0/1.1, only the AU format was supported.
How can i dynamically load fonts at runtime?
Location: http://www.jguru.com/faq/view.jsp?EID=74298
Created: Jun 25, 2000
Modified: 2000-06-25 09:21:44.883
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Yes, This is possible in JDK1.3. The new method Font.createFont(int, InputStream) provides the ability to add fonts to the JVM at runtime. This font is not persistent upon termination of the JVM and is only available to the creator of the Font. At this time, only TrueTypeTM fonts can be created at runtime. The following code sample illustrates how to dynamically load the TrueType font Arial from a file:Comments and alternative answersFile file = new File("Arial.ttf"); FileInputStream fis = new FileInputStream(file); Font font = Font.createFont(Font.TRUETYPE_FONT, fis);Similarly, to load the font from a URL:URL url = new URL("Arial.ttf"); InputStream is = url.openStream(); Font font = Font.createFont(Font.TRUETYPE_FONT, is);
| Re: How can i dynamically load fonts at runtime?
Author: Sauciuc Honoria (http://www.jguru.com/guru/viewbio.jsp?EID=453331), Jul 11, 2001 Cool, but how about this situation: I am developing an applet for a book keeping application and i am required that this applet prints in text format. My first hint was that I can create a font that comes with the text printer driver and this will print via the driver in text format (right or wrong?). So how do I do this if the browser only supports jdk 1.1 for instance ? |
| Register that font as a "system font"?
Author: Stefan Stefansson (http://www.jguru.com/guru/viewbio.jsp?EID=1119203), Aug 21, 2005 I'd like to know how (if it's possible) I can register that loaded font as a "system font" (so to speak)? What I mean is I'd like to be able to load a bunch of fonts when an application starts and register those fonts with the JVM so a JTextPane for example is able to render HTML text that uses one of the fonts loaded at startup.
Does anyone know if this can be done? |
How do I use antialiasing in Java?
Location: http://www.jguru.com/faq/view.jsp?EID=79646
Created: Jun 25, 2000
Modified: 2000-07-01 22:20:13.837
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
In your paint() method, add the following hint at the top of the method:((Graphics2D)g).setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);[FAQ Manager Note] This will only work in Java2. In JDK 1.x, you cannot perform antialias automatically (you would have to write your own antialiasing routines)
What general techniques are in practice to generate Reports in java (both applets and applications)?
Location: http://www.jguru.com/faq/view.jsp?EID=79281
Created: Jun 25, 2000
Modified: 2000-07-28 12:55:02.957
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Chakree Chakree (http://www.jguru.com/guru/viewbio.jsp?EID=22927
In applets, its best to just generate another HTML page and use the printing capabilities of the browser. For applications, it is easiest to just acquire a reporting package already created, instead of trying to figure out the Java Printing API, dealing with pagination, etc. Some packages are:Comments and alternative answers
| Please direct me to some places where I can find i...
Author: Victor Stratan (http://www.jguru.com/guru/viewbio.jsp?EID=134872), Aug 25, 2000 Please direct me to some places where I can find information regarding "just generat[ing] another HTML page". |
| Open source report generator
Author: David Gilbert (http://www.jguru.com/guru/viewbio.jsp?EID=19371), Mar 27, 2002 Hi All, JFreeReport is an open source report generator, available from: http://www.object-refinery.com/jfreereport/index.html The licence is the GNU Lesser General Public Licence. Regards,
Dave Gilbert
www.object-refinery.com |
How do I draw a line of any thickness in JDK 1.1?
Location: http://www.jguru.com/faq/view.jsp?EID=72470
Created: Jun 25, 2000
Modified: 2000-06-25 09:45:26.867
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Sergey Savenkov (http://www.jguru.com/guru/viewbio.jsp?EID=44661
Prior to the Java 2D API, all lines were drawn at a thinkness of one. If you need a wider line, you would need to draw multiple lines next to each other (or a rectangle, if the line is horizontal or veritcal - diagonal lines would need to be rotated if you relied on a filled rectangle)
How can I remove all the listeners associated with a component?
Location: http://www.jguru.com/faq/view.jsp?EID=72457
Created: Jun 25, 2000
Modified: 2000-06-25 10:01:04.902
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Zaneer Babu (http://www.jguru.com/guru/viewbio.jsp?EID=53849
Prior to 1.3, there was no way to ask a component for its list of listeners. You had to manually track them yourself. Starting with 1.3, you can ask certain AWT/Swing objects for said list of listeners, then remove them. Since Component has a getListeners(Class) method, all components have support this. See http://java.sun.com/j2se/1.3/docs/guide/swing/ListenerChanges.html for a list of non-component objects that support this.Comments and alternative answers[FAQ Manager Note] To remove all listeners prior to 1.3, you can simply create a new instance of the component in question and replace the old component with the new one.
Note that the getListeners() method will only work for the standard AWT events that Component tracks (and is overridden for each subclass). If you create your own subclass, you must override it to access any events that you add. See the source for java.awt.Button for an example of how to properly override getListeners().
| Starting at JDK1.02 ...if one is talking about a i...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Jun 25, 2000 Starting at JDK1.02 ...if one is talking about a instance of a component one could always subclass the component and override addXYZListener(XYZListener) removeXYZListener(XYZListener) and keep track of them after calling super methods respectively. Then you could remove them yourself anytime you want.
|
Can I use a specifc font in a Swing application without asking the user of the application to alter the font.properties file?
Location: http://www.jguru.com/faq/view.jsp?EID=80405
Created: Jun 25, 2000
Modified: 2000-06-25 11:07:58.655
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Indranil Dasgupta (http://www.jguru.com/guru/viewbio.jsp?EID=70647
The following resources may be helpful -Comments and alternative answers
- http://java.sun.com/products/jdk/1.2/docs/guide/internat/physicalfont.html
- http://java.sun.com/products/jdk/1.2/docs/guide/internat/unicode_font.doc.html
- http://java.sun.com/products/jdk/1.2/docs/guide/internat/fontprop.html
- http://www.ibm.com/java/education/international-text/index.html
Jean-Baptiste Bugeaud adds...
You may use
Font.createfont(Font.TRUETYPE_FONT,this.getClass().getRessource("myfont.ttf"))See http://java.sun.com/j2se/1.3/docs/api/java/awt/Font.html#createFont(int, java.io.InputStream) for details ...
Cool but only available in 1.3, and also works within applets!
| It was good to see that JDK1.3 does support dynamic...
Author: Indranil Dasgupta (http://www.jguru.com/guru/viewbio.jsp?EID=70647), Jul 3, 2000 It was good to see that JDK1.3 does support dynamic fonts. I have checked Jean-Baptiste's solution and it is almost correct, except that the second parameter required by createFont has to be an InputStream and hence "this.getClass().getRessource("myfont.ttf")" will not work (being a URL). However this is easily corrected as follows. From SUN's own Release Notes: File file = new File("Arial.ttf");
FileInputStream fis = new FileInputStream(file);
Font font = Font.createFont(Font.TRUETYPE_FONT, fis);
Similarly, to load the font from a URL: URL url = new URL("Arial.ttf");
InputStream is = url.openStream();
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
Note that apparently the size of the font can not be specified by createFont and the default size I am getting is very small. But you can resize the font later. [FAQ Manager Note] Good point, but be aware you can obtain a stream using InputStream in = getClass().getResourceAsStream("myfont.ttf");
as well... This has the advantage of being able to look up the font on the classpath if you desire |
Toolkit.getFontMetrics(Font) has been deprecated in Java 2. What do I use instead?
Location: http://www.jguru.com/faq/view.jsp?EID=72441
Created: Jun 25, 2000
Modified: 2000-06-25 11:09:40.665
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Kandula Radha (http://www.jguru.com/guru/viewbio.jsp?EID=70981
The java.awt.font.LineMetrics class provides the necessary information. Just ask the Font for the specific LineMetrics with getLineMetrics(). You'll need to know the string and the FontRenderContext, where the context is acquired from the Graphics2D object.
Font font = ...
FontRenderContext context = g2d.getFontRenderContext()
LineMetrics metrics = font.getLineMetrics("jGuru", context);
Comments and alternative answers
| about [Toolkit.getFontMetrics(Font) ]
Author: haruhiko hotta (http://www.jguru.com/guru/viewbio.jsp?EID=941373), Jul 8, 2002 Why did use of [Toolkit.getFontMetrics(Font) ] become improper? it is because there were many bugs -- it is -- or is it change of a mere name? Don't someone know a reason? |
| what I was looking for...
Author: Gustavo Henrique Sberze Ribas (http://www.jguru.com/guru/viewbio.jsp?EID=1177347), Dec 2, 2004
JLabel jLabel = new JLabel("jGuru");
FontMetrics fm = jLabel.getFontMetrics(jLabel.getFont());
int width = fm.stringWidth(jLabel.getText());
System.out.println("Text: " + jLabel.getText() +
"\nWidth: " + width);
|
How can I create an application which contains multiple frames?
Location: http://www.jguru.com/faq/view.jsp?EID=88774
Created: Jun 29, 2000
Modified: 2000-06-29 15:26:57.161
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Upenra Modak (http://www.jguru.com/guru/viewbio.jsp?EID=45581
There is nothing special about having an application have multiple frames. Just create multiple Frame/JFrame objects. Each will share the same event thread so they cannot run completely independent of each other.One thing worth mentioning is that often one doesn't create multiple frames, but instead uses one main Frame and subsequent frames are actually Dialog boxes. That way, if you were to iconify the Frame, the dialog boxes would be iconified automatically with them.
If you are looking more for an MDI-like architecture, consider using Swing's JDesktopPane with multiple JInternalFrame objects.
Is there anyway I can right-align text in a TextField?
Location: http://www.jguru.com/faq/view.jsp?EID=88926
Created: Jun 29, 2000
Modified: 2000-06-29 15:42:25.125
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Deepak Mahbubani (http://www.jguru.com/guru/viewbio.jsp?EID=53227
The AWT TextField doesn't support alignment. The Swing JTextField does. If you can, consider using it, instead.jTextField.setHorizontalAlignment(JTextField.RIGHT);
Can I change the the mouse cursor to a different image when the mouse moves over a specific component in Java?
Location: http://www.jguru.com/faq/view.jsp?EID=88589
Created: Jun 29, 2000
Modified: 2000-06-29 15:43:35.03
Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588)
Question originally posed by partha sarthi (http://www.jguru.com/guru/viewbio.jsp?EID=60808
All you need to do is add a mouse listener to your component and implement the mouseEntered and mouseExited methods to set and unset the cursor respectively. Here's an example :
myComponent.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
myComponent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent e) {
myComponent.setCursor(Cursor.getDefaultCursor());
}
});
Comments and alternative answers
| Help with errors with inner class variables in adding listners directly onto the components!!!
Author: Amyn Ali (http://www.jguru.com/guru/viewbio.jsp?EID=928777), Jun 28, 2002 how can I solve the problem of: "local variable myComponent is accessed from within inner class; needs to be declared final" without making myComponent a global variable whenever I use myComponent.addActionListener or add any type of listener directly onto my component??? |
How can I flash a minimized window to get the attraction of a user?
Location: http://www.jguru.com/faq/view.jsp?EID=88676
Created: Jun 29, 2000
Modified: 2000-06-29 15:52:12.536
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Deepak Dureja (http://www.jguru.com/guru/viewbio.jsp?EID=62641
As long as the minimized window is still visible
you could do -
try {
for (int i = 0; i < 4; i++) {
window.setVisible(false);
window.setVisible(true);
}
} finally {
// leave it visible
window.setVisible(true);
}
You are out of luck if your task autohide is "on" (MS
windows only) or your minimized window is on a different virtual desktop.
What is the difference between hierarchical and delegate event handling in AWT?
Location: http://www.jguru.com/faq/view.jsp?EID=90530
Created: Jun 29, 2000
Modified: 2000-06-29 15:56:02.528
Author: RamaChandra Murthy (http://www.jguru.com/guru/viewbio.jsp?EID=74971)
Question originally posed by Aniruddh Mishra (http://www.jguru.com/guru/viewbio.jsp?EID=36169
The hierarchical event handling in AWT specifies that the component interested in specific type of events has to handle events explicitly by the component i.e.,
- By subclassing the component
- By enabling the events in which the component is interested ini.e., by invoking enableEvents(long XXXevent)
- By overriding the public void processXXXEvent(XXXEvent event) method.
This way of subclassing each component and enabling the events which the componet has to handle is a tedious and cumbersome process.Hence,generally the delegation model is preferred.
The delegation model specifies that each component can delegate the job of event handling to objects called Listeners which must register with the event source.. Whenever an event is fired from a component, an event object is propagated to an appropriate method in the Listener object, and that method contains code to handle the event. Corresponding to every AWTEvent there is a corresponding event listener. For example, for ActionEvent we have ActionListener.
How can I determine how many lines are in a TextArea or JTextArea?
Location: http://www.jguru.com/faq/view.jsp?EID=72674
Created: Jul 1, 2000
Modified: 2000-07-01 21:32:55.598
Author: Jan Borchers (http://www.jguru.com/guru/viewbio.jsp?EID=48743)
Question originally posed by Grzegorz Kunstman (http://www.jguru.com/guru/viewbio.jsp?EID=69858
If you have a JTextArea with a PlainDocument (every child element represents a single ine) then you could do this:Document doc = mytextarea.getDocument(); Element root = doc.getDefaultRootElement(); int lines = root.getElementCount();Sandip Chitale adds
In both cases you could create a java.io.StringReader out of the getText() returned text. Wrap it in a java.io.BufferedReader and then read lines using the readLine() API.
You could walk through the String object returned by getText() and look for '\n' char to count the lines.
For JTextArea there is a direct API -
public int getLineCount();John Zukowski adds
To manually count them:
String text = area.getText(); StringReader reader = new StringReader(text); LineNumberReader lnr = new LineNumberReader(reader); while (lnr.readLine() != null); System.out.println(reader.getLineNumber());
Is there a way to know what percentage of a PrinterJob is currently complete. I would like to
display a JProgressBar to show the percentage complete.
Location: http://www.jguru.com/faq/view.jsp?EID=93630
Created: Jul 2, 2000
Modified: 2000-07-02 15:35:59.975
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Steve O'Callaghan (http://www.jguru.com/guru/viewbio.jsp?EID=44533
There is no means to get this informatiom from standard Java. It might be possible with the help of JNI or Microsoft's J/Direct.
Why does the same text using the same font look different on different platforms? Is there any way to force it to look the same?
Location: http://www.jguru.com/faq/view.jsp?EID=93634
Created: Jul 2, 2000
Modified: 2000-07-02 15:39:50.103
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Kilian W (http://www.jguru.com/guru/viewbio.jsp?EID=59700
Fonts are dealt with in points from Java. How the Java runtime translates points to pixels is up to the implementor of the runtime. You have no control over this as a developer besides finding a point size that looks reasonably good on all the implementations you test with. Short of creating your own Java runtime implementation, and convincing people why it is required, you have no way to force the issue.[FAQ Manager Note] If you always use layout managers to size and position your components in a GUI, it should never be necessary to worry about how text will look. Depending on the layout manager, you use, it can size the component based on its preferred size, which in turn is based on its font size and text to display.
See http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/index.html for details on layout management and which take preferred size into account.
Is it possible for a JWindow to stay on top of the Windows taskbar
using Java code?
Location: http://www.jguru.com/faq/view.jsp?EID=93675
Created: Jul 2, 2000
Modified: 2000-07-02 17:09:40.382
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by garnet simpson (http://www.jguru.com/guru/viewbio.jsp?EID=67281
No. If the windows taskbar's 'always-on-top' property is set to true there is no way a pure Java JWindow can go on top of it.Comments and alternative answers
| What happens in CDE?
Author: satish A (http://www.jguru.com/guru/viewbio.jsp?EID=222556), Jan 26, 2001 What happens in CDE? |
| How can one expect a platform independent code to do...
Author: Arvind Goel (http://www.jguru.com/guru/viewbio.jsp?EID=210075), Feb 11, 2001 How can one expect a platform independent code to do some thing excusive for windows !! |
What is GridBagLayout?
Location: http://www.jguru.com/faq/view.jsp?EID=96096
Created: Jul 5, 2000
Modified: 2000-07-05 05:59:30.024
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by priti shah (http://www.jguru.com/guru/viewbio.jsp?EID=95484
GridBagLayout is a standard layout manager provided with all Java implementations. Layout Managers help you to arrange Graphical User Interfaces that dynamically rearrange their components due to window size changes, as well as changes in fonts or other attributes of components such as displayed text.Comments and alternative answersYou can find details about it at http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbag.html
Note that GridBagLayout is extremely complex and should be avoided when possible. See my article, Effective Layout Management at http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/index.html for better ways to create layout managers through nesting simpler layouts. Nearly everything you can do in GridBagLayout can be done by nesting a few simpler layout managers.
Many people say "GridBagLayout isn't that bad -- I learned it". But they miss the point. One of the key issues in software development is that you should write your code so someone else can easily understand it. If you use GridBagLayout, anyone reading your code must know it at least as well as you to understand it. By sticking with simpler layout managers, the layout design is easier to "see" in the code.
| I think Mr. Stanchfield's point is very good and should...
Author: Jasen Halmes (http://www.jguru.com/guru/viewbio.jsp?EID=55625), Sep 19, 2000 I think Mr. Stanchfield's point is very good and should be followed whenever possible. However Java is an API that we programmers don't have control over and although "in theory" you can create many of the layouts that GridBagLayout is used for in practice some layout managers simply treat components differently. Therefore it becomes necessary to understand the API known as Java in as much detail as possible. GridBayLayout is a powerful layout manager and shouldn't be shunned because it is more difficult. That is what programming is all about, tradeoffs. [FAQ Manager (Scott Stanchfield) Note] I agree that learning it is a pretty good idea. However, My point is that you shouldn't create new layouts using it. You may need to maintain other people's layouts, but don't use it for new work. |
How do I create scroll bars inside a dialog?
Location: http://www.jguru.com/faq/view.jsp?EID=96826
Created: Jul 5, 2000
Modified: 2000-07-08 08:05:42.879
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Amit Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=89904
The Dialog component itself doesn't provide scrollbars. If you want to make them available, you have to place your set of components within a Container like a Panel, then place that container within a ScrollPane to provide the scrollbars.
Dialog dialog = new Dialog(mainFrame); dialog.setLayout(new GridLayout(1,0)); Panel content = new Panel(); // set layout and add components for dialog to content panel ScrollPane pane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED); pane.add(content); dialog.add(pane);Note that if you are using Swing, you'll want to use JScrollPane instead of ScrollPane.
When is it recommended to use Java Advanced Imaging (JAI) instead of the Java 2D API?
Location: http://www.jguru.com/faq/view.jsp?EID=98328
Created: Jul 7, 2000
Modified: 2000-07-08 08:15:05.979
Author: Curtis Hatter (http://www.jguru.com/guru/viewbio.jsp?EID=62466)
Question originally posed by Bruno Randolf (http://www.jguru.com/guru/viewbio.jsp?EID=94633
Basically it depends on the requirements of the program.
If I were able to do the required graphics with Java 2D, then I did so. But if I needed more advanced graphical capabilities then I would import the JAI package and convert my buffered image to a planar image and do what I needed.
For image loading I actually use Java Imaging I/O (since it will be part of 1.4 release) unless I need to read in images other then gif, jpg, or png.
Which brings me to another point.. if you wish to use images other than gif, jpg, or png, your only options (that I know of offered by SUN) are JIMI, and JAI. JAI offers a lot more then JIMI but does seem to use up a lot more memory and processing time. JIMI also is supposed to be jdk 1.1 compliant which could be a plus if you have to use a older jdk.
JAI also provides more information on the images then Java2D does, so if you need that info once again you might be better off with JAI.
How do I create my own events to pass between objects?
Location: http://www.jguru.com/faq/view.jsp?EID=98547
Created: Jul 8, 2000
Modified: 2000-07-08 17:51:44.77
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Sivasankar Murugesan (http://www.jguru.com/guru/viewbio.jsp?EID=94465
Comments and alternative answersEvent firing in Java requires the following elements
- An event class to transmit information about the event
- An interface that describes how the bean will notify interested parties, known as listeners
- A data structure to track listeners
- Registration methods to add and remove listeners
- Code to fire the events
For example, suppose that you were creating a WeatherStation bean that notifies any interested parties when the sun rises or sets. This example is used throughout this FAQ.
An Event Class
The first requirement for event firing is a class to represent information about the event. The SunEvent object contains the time of the event and a boolean property that tells us if the event represents the sun rising or setting.
Event classes should be immutable. Immutable objects are ones that cannot be changed. Event firing passes a reference to a single event instance to each listener in an unspecified order. It is important that those listeners cannot modify the event, or it could change the way processing continues for other listeners. Note that the following class is not a bean, because its superclass does not implement java.io.Serializable. If you like, you can define the event object as a bean, but in practice this is rarely done.
Note that the event object must extend class java.util.EventObject. EventObject provides the getSource() method so you can determine the event origin. By extending EventObject, those objects can be handled generically in other methods, and some tools, like VisualAge for Java, take advantage of this when creating generic methods to forward events.
import java.util.Date; import java.util.EventObject; /** * An event that represents the Sun rising or setting */ public class SunEvent extends EventObject { private boolean risen; private Date date; public SunEvent(Object source, boolean risen, Date date) { super(source); this.risen = risen; this.date = date; } /** return a String representation of the date */ public String getDate() { // return only a String representation // so the user cannot modify the real date return date.toString(); } /** return whether the sun rose or set */ public boolean isRisen() { return risen; } }EventObject requires a source (a reference to the object that fired the event), which is set to the WeatherStation bean when firing the event. Whenever events are fired, an instance of the EventObject class is created and passed to each registered listener.
An Event-Listener Interface
Event listeners are classes that have registered interest in an event that a bean can fire. The bean notifies listener classes by calling certain methods in those listener classes. But how does the bean know which methods to call?
When defining the event, you also define a contract between the event source and its listeners. This contract specifies which methods the event source will call. Any listeners must implement those methods. Sounds like a perfect use for a Java language interface.
Therefore, define an interface that specifies the contract. Because each listener must implement that interface, the event-source bean can determine which methods it can call. Continuing the example, define a simple interface for the sun events.
Note that the following interface extends the java.util.EventListener interface. EventListener requires no methods. It is just a tag that indicates an interface is acting as an event listener. This assists determination of the events a bean can fire.
import java.util.EventListener; /** A contract between a SunEvent source and * listener classes */ public interface SunListener extends EventListener { /** Called whenever the sun changes position * in a SunEvent source object */ public void sunMoved(SunEvent e); }Any SunEvent listeners are required to implement a single method, sunMoved(). Normally, event-listener methods should take a single parameter: the event object. However, if you have a strong need, the bean specification allows (but strongly discourages) different parameters.
An Event-Source Bean
Now you define the source of the sun events, the WeatherStation. This class needs to track its listeners and fire the events. This is implemented as follows, and a simple GUI to trigger the SunEvents is provided:
import java.util.Vector; import java.util.Date; import java.util.Enumeration; import java.awt.Button; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.Serializable; /** A sample event source - this class fires SunEvents * to anyone watching. A simple GUI is provided * with "rise" and "set" buttons that cause the * SunEvents to be fired. */ public class WeatherStation extends Frame implements Serializable { private transient Vector listeners; /** Provide a simple GUI that triggers our SunEvents */ public WeatherStation() { super("Sun Watcher"); setLayout(new GridLayout(1,0)); Button riseButton = new Button("Rise"); Button setButton = new Button("Set"); add(riseButton); add(setButton); // make the "Rise" button fire "rise" SunEvents riseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fireSunMoved(true); } }); // make the "Rise" button fire "set" SunEvents setButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fireSunMoved(false); } }); // Provide a means to close the application addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); pack(); } /** Register a listener for SunEvents */ synchronized public void addSunListener(SunListener l) { if (listeners == null) listeners = new Vector(); listeners.addElement(l); } /** Remove a listener for SunEvents */ synchronized public void removeSunListener(SunListener l) { if (listeners == null) listeners = new Vector(); listeners.removeElement(l); } /** Fire a SunEvent to all registered listeners */ protected void fireSunMoved(boolean rose) { // if we have no listeners, do nothing... if (listeners != null && !listeners.isEmpty()) { // create the event object to send SunEvent event = new SunEvent(this, rose, new Date()); // make a copy of the listener list in case // anyone adds/removes listeners Vector targets; synchronized (this) { targets = (Vector) listeners.clone(); } // walk through the listener list and // call the sunMoved method in each Enumeration e = targets.elements(); while (e.hasMoreElements()) { SunListener l = (SunListener) e.nextElement(); l.sunMoved(event); } } } }The bold text provides the support for tracking listeners and calling their event-handler methods.
The event source can now notify interested listeners. The synchronized keywords and cloning are necessary to avoid possible problems if the list of listeners changes while you are notifying listeners. Pressing the Rise and Set buttons fires an appropriate SunEvent to any registered listeners.
Typically, developers will create a fire method similar to the previous fireSunMoved() method, but the method is not required. The event-firing code can appear in any method you prefer.
A Sample Event Listener
In the example, the weather channel informs any interested parties about the sun rising or setting. Continuing this example, Mrs. Jones assigns her class the task of graphing the behavior of the sun. They must watch a weather channel to find out at exactly what time the sun rose and set each day, logging this information in their notebook. This example can be modeled using a Student class as follows:
/** A sample SunListener, logging when the sun rises and sets */ public class Student implements SunListener { private String name; /** constructor -- get the student's name */ public Student(String name) { this.name = name; } /** sunMoved method comment. */ public void sunMoved(SunEvent e) { log(name + "\tlogs : " + (e.isRisen() ? "rose" : "set") + " at " + e.getDate()); } /** A simple log method - just print the text */ protected void log(String text) { System.out.println(text); } }Note that Student implements SunListener, defining the details of a sunMoved() method. Any number of Students may watch the weather channel to hear the time of sunrise and sunset.
/** * A simple test of the SunEvent source and listeners */ public class WeatherTest { /** Run a test on the weather station, using Scott's * kids as sample students */ public static void main(String[] args) { // create a new sun event source WeatherStation w = new WeatherStation(); // add some students to listen for sun rise/set w.addSunListener(new Student("Nicole")); w.addSunListener(new Student("Alex")); w.addSunListener(new Student("Trevor")); w.addSunListener(new Student("Claire")); // display the GUI for the weather channel w.setVisible(true); } }Running WeatherTest and pressing the Rise and Set buttons results in something like the following:
Nicole logs : rose at Thu Apr 29 14:55:21 PDT 1999 Alex logs : rose at Thu Apr 29 14:55:21 PDT 1999 Trevor logs : rose at Thu Apr 29 14:55:21 PDT 1999 Claire logs : rose at Thu Apr 29 14:55:21 PDT 1999 Nicole logs : set at Thu Apr 29 14:55:22 PDT 1999 Alex logs : set at Thu Apr 29 14:55:22 PDT 1999 Trevor logs : set at Thu Apr 29 14:55:22 PDT 1999 Claire logs : set at Thu Apr 29 14:55:22 PDT 1999Warning
The above listener methods run in a specific order each time an event is fired. This is because we stored the listeners in an ordered data structure. There is no guarantee of event-notification order in the bean specification! Unless a bean documents its event-firing behavior as ordered, you should not assume any particular order of notification. Beans could store their listeners in any data, and they may report them in a different order every time they fire an event.
Also note that event firing is synchronous. That is to say, the event source calls only one event handler at a time. Most beans fire their events in this manner (although there is nothing to stop you from writing a bean that fires events asynchronously). Because of this, you should perform only short operations in your event handlers. Think of it this way: The next listener has to wait for you, so you should be courteous and return as quickly as possible. If you need more complex operations, spawn another thread from your event handler.
| What a cheap trick!!
Author: Gumaro Godinez (http://www.jguru.com/guru/viewbio.jsp?EID=746582), Feb 4, 2002 You're doing nothing special here. I want to see this happen without using AWT events at all !!!! |
| Re: What a cheap trick!!
Author: Timido Innocente (http://www.jguru.com/guru/viewbio.jsp?EID=1226181), Feb 9, 2005 obviously you didnt understand the subject which was: "How do I create my own events to pass between objects?" And I think this is explained here pretty well. For me this article was very useful, Thanx anyway :D |
| Re: What a cheap trick!!
Author: shabbir hussain (http://www.jguru.com/guru/viewbio.jsp?EID=1527490), Dec 21, 2009 how can u say that this was a cheap trick. do know any other trick for doing that. |
| Thanks
Author: Ra Daniel (http://www.jguru.com/guru/viewbio.jsp?EID=959049), Aug 2, 2002 A good explanation. Although you demonstrate this using awt events you can use this anywhere. |
| Not a "cheap trick" at all...
Author: Andrew Biggs (http://www.jguru.com/guru/viewbio.jsp?EID=387596), Oct 24, 2002 To those who are seeing this for the first time I'd just like to comment that I've found this to be a pretty powerful design-pattern with usefulness extending well beyond GUI's and beans. Granted, the example above is obviously contrived for illustrative purposes. But when dealing with a more complicated event-driven application, this pattern can go a long way toward simplifying your life. |
| Re: Not a "cheap trick" at all...
Author: Guanglin du (http://www.jguru.com/guru/viewbio.jsp?EID=715730), Jul 17, 2003 I agree. Scott Stanchfield has given me one of the most enlightening articles when I was learning the event-handling mechanism in Java. I own him many thanks. |
| Re[2]: Not a "cheap trick" at all...
Author: Babu Madhikarmi (http://www.jguru.com/guru/viewbio.jsp?EID=1226917), Feb 13, 2005 By supposedly following this design pattern, a VB application knows that a Bean can throw events and thus VB can handle the event itself... and as far as i know it doesn't work. VB registers itself as a listener (for unicast sources you cannot add another listener so it must mean VB at work), but when you go to object browser and view the Java Beans Members... your custom event is not even there! If anyone knows better or has custom events being forwarded to a VB container, i would more than happy to be corrected. I think this is more about good use of design patterns... It would be more useful to have guides on handling Java Bean events through Active X bridge in a VB container. I think this works between java beans... |
| External hardware interface signal to trigger event
Author: Aldo Cappa (http://www.jguru.com/guru/viewbio.jsp?EID=959731), Dec 17, 2008 GoodMornig to everybody. How can use an hardware signal, captured trough dll wrapper to triggers our SunEvents? I have tried using a sw cicle but is too sloow. I lost several events. I am trying to implement an electronic drum using javasound and piezoelectric sensors. Thanks |
How do I scale, shear, translate, and/or rotate an image?
Location: http://www.jguru.com/faq/view.jsp?EID=98950
Created: Jul 9, 2000
Modified: 2000-07-11 17:17:20.488
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Use the AffineTransform class, and pass it along to the drawImage() method.Comments and alternative answers
- Create: AffineTransform trans = new AffineTransform()
- Scale: trans.scale(scalex, scaley)
- Shear: trans.shear(shiftx, shifty)
- Translate: trans.translate(deltax, deltay)
- Rotate: trans.rotate(radians)
- Draw: g2d.drawImage(image, trans, this)
| How do I scale an Image (JPG) ?
Author: Svein Are Gronsund (http://www.jguru.com/guru/viewbio.jsp?EID=384663), Mar 22, 2001 How do I scale an JPG image? (It has been uploaded, and I want to make an thumbnail as well as retainging a default width). I have found the JPGCodec so I can encode/decode to an BufferedImage, but then I can only get the W&H, not set it. I have searched and searched for this, but havn't found anything concrete yet. Please help.. - Svein Are (sag@portalen.no) |
| Re: How do I scale an Image (JPG) ?
Author: Russell Beattie (http://www.jguru.com/guru/viewbio.jsp?EID=1725), Aug 13, 2001 Here's my code that did it, maybe you can get someone to explain how it works... ;-D
import java.util.*;
import java.io.*;
import java.text.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
public class Thumbnailer{
public File file;
public File newDirFile;
Thumbnailer (File file, File newDirFile){
this.file = file;
this.newDirFile = newDirFile;
}
public boolean process()
{
try{
String fileInString = file.getAbsolutePath();
String fileOutString = newDirFile.getPath() + File.separator + "thumbs" + File.separator + "tn" + file.getName().replace(' ','_');
File fileIn = new File(fileInString);
File fileOut = new File(fileOutString);
fileOut.createNewFile();
InputStream input = new FileInputStream(fileIn);
OutputStream output = new FileOutputStream(fileOut);
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(input);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
BufferedImage imageSrc = decoder.decodeAsBufferedImage();
int width = imageSrc.getWidth();
int height = imageSrc.getHeight();
int thumbWidth = 100;
int div = width/thumbWidth;
height = height/div;
Image img = imageSrc.getScaledInstance(thumbWidth, height ,Image.SCALE_FAST);
BufferedImage bi = new BufferedImage(thumbWidth, height, BufferedImage.TYPE_INT_RGB);
Graphics2D biContext = bi.createGraphics();
biContext.drawImage(img, 0, 0, null);
encoder.encode(bi);
input.close();
output.close();
} catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
}
|
How do I move the mouse cursor on the screen?
Location: http://www.jguru.com/faq/view.jsp?EID=98951
Created: Jul 9, 2000
Modified: 2000-07-11 17:22:35.055
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Starting with 1.3 you can use the java.awt.Robot class:Comments and alternative answersRobot robot = new Robot(); robot.mouseMove(x, y);Be sure your user is expecting this. Under normal circumstances, this should not be done.
| Thank You
Author: Vintesh Patel (http://www.jguru.com/guru/viewbio.jsp?EID=1538294), Mar 13, 2010 Thanks... Thank You Sir Very Very Much... |
How do I simulate keystrokes?
Location: http://www.jguru.com/faq/view.jsp?EID=98952
Created: Jul 9, 2000
Modified: 2000-07-11 17:25:02.632
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Starting with 1.3 you can use the java.awt.Robot class:Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_J); robot.keyRelease(KeyEvent.VK_J);
How do I simulate mouse events?
Location: http://www.jguru.com/faq/view.jsp?EID=98953
Created: Jul 9, 2000
Modified: 2000-07-11 17:27:35.114
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Starting with 1.3 you can use the java.awt.Robot class:Robot robot = new Robot(); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK);
How do I get the Shape from the outline of a text string?
Location: http://www.jguru.com/faq/view.jsp?EID=98976
Created: Jul 9, 2000
Modified: 2000-07-11 17:31:11.275
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The getOutline() method of TextLayout provides this information:TextLayout layout = new TextLayout(aString, aFont, g2d.getFontRenderContenxt()); // Argument is AffineTransform Shape shape = layout.getOutline(null);
How do you convert a color image to a gray-scale image?
Location: http://www.jguru.com/faq/view.jsp?EID=99027
Created: Jul 9, 2000
Modified: 2000-07-11 17:36:23.549
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Using the ColorSpace class, you can convert a multi-color image to gray with the following operation:Comments and alternative answersColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); ColorConvertOp op = new ColorConvertOp(cs, null); BufferedImage grayImage = op.filter(colorImage, null);
| Transparent image to grey
Author: Matthias Wolf (http://www.jguru.com/guru/viewbio.jsp?EID=1092669), Feb 27, 2004 This doesn`t work for transparent images! |
How do you trap a newline/Enter character in a JTextArea?
Location: http://www.jguru.com/faq/view.jsp?EID=99650
Created: Jul 10, 2000
Modified: 2000-07-11 17:58:42.17
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by tanmay patil (http://www.jguru.com/guru/viewbio.jsp?EID=22776
There are multiple ways -Comments and alternative answers
jtextArea.getDocument().addDocumentListener( new DocumentListener() { public void insertUpdate(DocumentEvent e) { // watch for newline/enter here } public void removeUpdate(DocumentEvent e) { } public void changedUpdate(DocumentEvent e) { // watch for newline/enter here } } }- Add a KeyListener and look for VK_ENTER key typed event.
jtextArea.registerKeyboardAction( KeyStroke.getKeyStroke(VK_ENTER, 0, false), new ActionListener() {...} );
| a better example
Author: i i (http://www.jguru.com/guru/viewbio.jsp?EID=1130976), Nov 29, 2003 textArea.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent evt) { } public void keyPressed(KeyEvent evt) { switch (evt.getKeyCode()) { case KeyEvent.VK_ENTER: System.out.println("enter pressed"); break; } } }); |
How can I load an image into a BufferedImage without creating a Component for the MediaTracker?
Location: http://www.jguru.com/faq/view.jsp?EID=99988
Created: Jul 11, 2000
Modified: 2000-07-11 18:02:14.539
Author: Bruno Randolf (http://www.jguru.com/guru/viewbio.jsp?EID=94633)
Question originally posed by Bruno Randolf (http://www.jguru.com/guru/viewbio.jsp?EID=94633
You can achieve this by using an ImageIcon:
private BufferedImage loadBufferedImageIcon( String filename )
{
// Get Image
ImageIcon icon = new ImageIcon(filename);
Image image = icon.getImage();
// Create empty BufferedImage, sized to Image
BufferedImage buffImage =
new BufferedImage(
image.getWidth(null),
image.getHeight(null),
BufferedImage.TYPE_INT_RGB);
// Draw Image into BufferedImage
Graphics g = buffImage.getGraphics();
g.drawImage(image, 0, 0, null);
return buffImage;
}
How can I specify the initial position and size of a Frame/JFrame?
Location: http://www.jguru.com/faq/view.jsp?EID=100082
Created: Jul 11, 2000
Modified: 2000-07-11 18:12:22.061
Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588)
Question originally posed by Yogesh Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=55604
To set the size on a frame (or JFrame), use the setSize() method, passing either a Dimension object, or the width and height values in pixels. For example :Comments and alternative answersmyFrame.setSize(640, 480);Another (and IMHO better) way of sizing a window is to use the pack() method. This sizes the window so that each of its components are visible at their preferred size.
To set the initial position for a frame (or JFrame), use the setLocation() method specifying a Point object, or the x and y coordinates. The top-left of the screen is at 0,0.
myFrame.setLocation(0, 0);These along with other useful methods are defined on java.awt.Component class.
The java.awt.Toolkit class contains the getScreenSize() method for getting the size of the screen - just in case you wish to make the window the full size of the screen or center your window.
| I think the real issue here is that
myFrame.setSiz...
Author: Raj Singh (http://www.jguru.com/guru/viewbio.jsp?EID=44099), Jul 17, 2000 I think the real issue here is that myFrame.setSize(640, 480);will not really be a 640x480 window. Even though you set the size to a certain value, usually the frame is pack()-ed or something else happens to make it smaller than you wanted. I usually override setPreferredSize() and setMinimumSize() to get consistent results. [FAQ Manager Note] If you don't call pack() it shouldn't be a problem... If there's a pack() in your code, you can always remove it... |
| How do I use pack() and center my frame?
Author: Robert Bigornia (http://www.jguru.com/guru/viewbio.jsp?EID=273094), Dec 8, 2000 How do I use pack() and center my frame? |
| Setting the size of a frame
Author: Ramprasad R (http://www.jguru.com/guru/viewbio.jsp?EID=1081409), May 7, 2003 I feel the best way is to use setBounds method. //to set size using setBounds() JFrame jf = new JFrame("title of frame"); jf.setBounds(x,y,width,height); here x,y will be the top left corner of the frame w.r.t to the screen. |
What support exists in Java for a Multi-Screen Environment?
Location: http://www.jguru.com/faq/view.jsp?EID=100694
Created: Jul 12, 2000
Modified: 2000-07-19 16:40:13.751
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
You can now render on multiple screens by creating Frame, JFrame, Window, or JWindow objects with the GraphicsConfiguration of a target GraphicsDevice. For more information look at http://java.sun.com/j2se/1.3/docs/guide/2d/spec/j2d-awt.fm6.html
What are the advantages/disadvantages of Swing over AWT?
Location: http://www.jguru.com/faq/view.jsp?EID=106026
Created: Jul 19, 2000
Modified: 2000-07-19 16:59:45.417
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by namit gautam (http://www.jguru.com/guru/viewbio.jsp?EID=96784
Swing provides a richer set of components than AWT. They are 100% Java-based.Comments and alternative answersAWT on the other hand was developed with the mind set that if a component or capability of a component wasn't available on one platform, it won't be available on any platform. Something quickly portable from platform x, to y, to z. Due to the peer-based nature of AWT, what might work on one implementation might not work on another, as the peer-integration might not be as robust. Many of the original AWT problems were traceable to differences in peer implementations.
This is not to say that there are less bugs in Swing, though most are out these days. Its just that if a bug exists in Swing, its the same problem on all platforms, which was not the case with AWT.
[FAQ Manager Note] There are a few other advantages to Swing over AWT:
- Swing provides both additional components and added functionality to AWT-replacement components
- Swing components can change their appearance based on the current "look and feel" library that's being used. You can use the same look and feel as the platform you're on, or use a different look and feel
- Swing components follow the Model-View-Controller paradigm (MVC), and thus can provide a much more flexible UI.
- Swing provides "extras" for components, such as:
- Icons on many components
- Decorative borders for components
- Tooltips for components
- Swing components are lightweight (less resource intensive than AWT)
- Swing provides built-in double buffering
- Swing provides paint debugging support for when you build your own components
Swing also has a few disadvantages:
- It requires Java 2 or a separate JAR file
- If you're not very careful when programming, it can be slower than AWT (all components are drawn)
- Swing components that look like native components might not act exactly like native components
| Other swing disadvantage
Be carefull, swing is not...
Author: Pascal Molli (http://www.jguru.com/guru/viewbio.jsp?EID=350787), Mar 14, 2001 Other swing disadvantage Be carefull, swing is not thread safe. You can get into trouble if you modify the model concurrently with the screen updater thread. Take a look at: http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html |
How can I create multiple floatable/dockable toolbars/palettes/views which stay inside the application frame (unlike Swing JToolBars)? Is it poosible to have such a framework for AWT also?
Location: http://www.jguru.com/faq/view.jsp?EID=107014
Created: Jul 20, 2000
Modified: 2000-07-20 18:35:23.076
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Sandip Chitale PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=14537
To keep toolbars within the application frame, you'll need to create your own JToolBar-like component that keeps the floating toolbar within a JInternalFrame instead of a JFrame. The UI for the JToolBar class requires that the floating frame be a JFrame: protected JFrame createFloatingFrame(JToolBar toolbar) and the drag window be a DragWindow (which extends Window).Comments and alternative answersAs far as dealing multiple toolbars goes, if you want to stick with JToolBar... You will need to create a new ToolBarUI and override public void setFloating(boolean b, Point p), protected void dragTo(Point position, Point origin), and protected void floatAt(Point position, Point origin) to deal with adding multiple toolbars to a single constraint.
| More explanation
Author: Jean-Philippe Encausse (http://www.jguru.com/guru/viewbio.jsp?EID=447560), Sep 18, 2001 Hi ! can you give us a sample component or is there somewhere to find custom component like that ? Is there multi toolbar dockable on kind of gridbaglayout that insert split between it brother ? Best Regards, NextOne |
| Re: More explanation
Author: lionel Giltay (http://www.jguru.com/guru/viewbio.jsp?EID=522467), Oct 17, 2001 Did u find something about this case ? |
| Re: More explanation
Author: David Jeske (http://www.jguru.com/guru/viewbio.jsp?EID=1050905), Jan 27, 2003 Someone posted a floating toolbar implementation at the URL below, but I've not tried it yet:
http://forum.java.sun.com/thread.jsp?thread=124397&forum=57&message=327426 |
What is the difference between a JavaBean and a traditional AWT object?
Location: http://www.jguru.com/faq/view.jsp?EID=107018
Created: Jul 20, 2000
Modified: 2000-07-20 18:37:13.034
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Dallas Dreyer (http://www.jguru.com/guru/viewbio.jsp?EID=58484
JavaBeans is a component architecture for defining reusable components for Java. The JavaBeans specification defines just how to create/define such components. These components may be graphical or may not be. There is no requirement that a bean be graphical, just that it follows the architecture defined by the specification.Comments and alternative answersOn the other hand, an AWT object, specifically the AWT components, are JavaBean components specifically designed to be reused by a drag-and-drop GUI development tool like VisualAge for Java or JBuilder. While yes, you can code everything by hand, because the AWT components are JavaBean components, you can get/set bean properties, connect events, and persist the interface, through the JavaBeans architecture.
| If you know how drag and drop work in java bean design time in JBuilder
Author: jenny zhang (http://www.jguru.com/guru/viewbio.jsp?EID=488126), Aug 31, 2001 Please send your answer to jenny.zhang@sap.com Thank you! |
How can I scroll the TextArea from an independent scrollbar in the same manner as its own scrollbar would scroll it?
Location: http://www.jguru.com/faq/view.jsp?EID=107019
Created: Jul 20, 2000
Modified: 2000-07-20 18:42:28.246
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by sudhakar chintu (http://www.jguru.com/guru/viewbio.jsp?EID=78272
The TextArea component does not expose this, as the scrollbar is part of the native component.If you can, consider using the JTextArea component which exposes this, allowing you to share the model between the JScrollBar of the JScrollPane that the JTextArea is within and your external JScrollBar.
Is it possible to use AWT layout managers with Swing components?
Location: http://www.jguru.com/faq/view.jsp?EID=107138
Created: Jul 20, 2000
Modified: 2000-07-20 19:20:18.302
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Nripesh Palikhya (http://www.jguru.com/guru/viewbio.jsp?EID=99684
But of course!Sometimes people have the impression that you can only use Swing or only use AWT. This is not the case.
Swing builds on top of AWT's Container class, and uses the same layout managers and much of the other component support that AWT does.
To use the AWT layout managers with a Swing GUI, simply include
import java.awt.*;at the top of your source, as well as the Swing package imports that you need. You will then be able to access all of the AWT layout managers.
BTW: You can also use Swing's BoxLayout layout manager in AWT-only applications -- it's just a standard layout manager. Make sure you deliver the BoxLayout class, as well as the SizeRequirements class from Swing with your AWT application if you do this.
When I change GUI (add/remove components) in an actionPerformed method, how can I force it update immediately? Calling revalidate seems delay the update until method actionPerformed returns.
Location: http://www.jguru.com/faq/view.jsp?EID=107177
Created: Jul 20, 2000
Modified: 2000-07-20 19:44:22.855
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Chuong Huynh (http://www.jguru.com/guru/viewbio.jsp?EID=77266
The actionPerformed method is being called by the AWT thread.Comments and alternative answersThe AWT thread is the thread that actually performs the repaint/revalidate request. Because that thread is tied up processing actionPerformed, it cannot do the update.
The only way you can do this (assuming you're doing some processing that takes a bit of time) is to start another thread for the processing. Note that if this other thread wants to update the GUI components, it should use Swing's invokeLater functionality to schedule the GUI update with the AWT thread. For example:
public void actionPerformed(ActionEvent e) { new Thread() { public void run() { doSomething(); // update GUI SwingUtilities.invokeLater(new Runnable() { public void run() { fooLabel.setText("working..."); }}); } }.start(); }(Sorry about the nested anon inner classes, but hopefully you'll get the point.)
Starting a thread to do a long-running action inside the actionPerformed method frees the AWT thread to actually update the GUI when you want it to
| This doesn't seem to work all the time
Author: Mike Hogarth (http://www.jguru.com/guru/viewbio.jsp?EID=6017), Dec 31, 2001 I have the following actionPerformed code and a textArea (referenced by 'output' is not updated until the thread is done... Not sure why?
void executeButton_actionPerformed(ActionEvent e) {
QueryThread qt = new QueryThread(output, hostText.getText(),portText.getText());
qt.run();
output.append("Started...");
}
|
| Re: This doesn't seem to work all the time
Author: Nikolas Colman (http://www.jguru.com/guru/viewbio.jsp?EID=793076), Apr 26, 2002 You should call qt.start() as opposed to qt.run() |
Can I change the look and feel of AWT components as can be done for Swing?
Location: http://www.jguru.com/faq/view.jsp?EID=107251
Created: Jul 20, 2000
Modified: 2000-07-20 20:28:38.696
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by shiva prasad (http://www.jguru.com/guru/viewbio.jsp?EID=73834
No. AWT components use native GUI widgets on each platform. They will always look like the current platform's look and feel.Comments and alternative answers
| You could run emulators of other look and feel e.g....
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Jul 21, 2000 You could run emulators of other look and feel e.g. run X windows server on MS Windows and connect to it. |
| Changing AWT Look and Feel
Author: Yuval Zukerman (http://www.jguru.com/guru/viewbio.jsp?EID=733629), Jan 25, 2002 You can change the AWT look and feel but only through the creation of custom components. Daunting task to say the least. |
How can I create a Java Image out of an integer array
that I got from native code (using JNI)?.
Location: http://www.jguru.com/faq/view.jsp?EID=107797
Created: Jul 21, 2000
Modified: 2000-07-21 09:23:52.694
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by gv lakshmanan (http://www.jguru.com/guru/viewbio.jsp?EID=100651
You can create an ImageIcon from a Byte Array. So all you have to do is get the Byte Array from using JNI and create an ImageIcon from it. Here's how the code looks on the java side.import javax.swing.*; public class MyImage { static { System.loadLibrary("imagelib"); } ImageIcon getImage() { return new ImageIcon(getMyImage()); } static native byte [] getMyImage(); }and here's the native codeJNIEXPORT jbyteArray JNICALL Java_MyImage_getMyImage (JNIEnv *env, jclass jC) { jbyte *buf ; jsize size ; jbyteArray jb; // fill the buf buf = .... size = .... // create the byte array jb=(*env)->NewByteArray(env, size); // fill the byte array (*env)->SetByteArrayRegion(env, jb, 0, size, buf); return jb; }
How can I display tif graphics in my Java applet?
Location: http://www.jguru.com/faq/view.jsp?EID=107798
Created: Jul 21, 2000
Modified: 2000-09-14 08:37:36.111
Author: delfim martins (http://www.jguru.com/guru/viewbio.jsp?EID=9614)
Question originally posed by Yasar Qureshi (http://www.jguru.com/guru/viewbio.jsp?EID=48204
A few options to solve this problemComments and alternative answers
- JIMI (Java Image Mangagement Interface) at http://java.sun.com/products/jimi
- JAI (Java Advanced Imaging) at http://java.sun.com/products/java-media/jai
- Lizard's TIFF Library at http://www.lizardworks.com/java.html
It is up to you which one to choose. They are all very good.
| A couple of caveats are in order here -- Having used...
Author: Joshua Turner (http://www.jguru.com/guru/viewbio.jsp?EID=122831), Aug 9, 2000 A couple of caveats are in order here -- Having used all three of the aforementionned API's, there are some things you should know before you start: Liz Marks' lizard.tiff library is small and reasonably fast. It deals well with Swing, and it deals exceptionally well with CCITT G4 images, but bogs down on large images. (on the order of 2550*3300*1bpp) Especially worth noting is that Liz's API was the first of the three to be avaialble. Kudos to her for filling a huge gap in the Java software space. JAI's API is big and hairy. This is probably best reserved for really, really hardcore applications, like medical imaging/geophysics. Performance is reasonable, and large image support is there. JIMI is a fast, well balanced API for dealing with professional image formats. Sun actually acquired this technology in buying another firm, and it was a worthwhile purchase. Worth noting is that this API really shines when it is allowed to write buffers to local storage. (ie. not in applets) |
| Example will be useful.....
Author: sohan kabra (http://www.jguru.com/guru/viewbio.jsp?EID=996554), Sep 9, 2002 Hi All, I tried using JAI 1.1, but it seems that it is a whole bunch of another APIs which a programmer needs to know. Can anybody provide the examples for this ? Thanks in advance. |
How can I save a JApplet's output (AppletWindow) as a GIF file?
Location: http://www.jguru.com/faq/view.jsp?EID=108121
Created: Jul 21, 2000
Modified: 2000-09-14 08:38:00.007
Author: Joe Hanink (http://www.jguru.com/guru/viewbio.jsp?EID=94909)
Question originally posed by karuppanan rameshkumar (http://www.jguru.com/guru/viewbio.jsp?EID=102591
Visit http://www.acme.com/java/software/Acme.JPM.Encoders.GifEncoder.html for a prebuilt utility
On my win2k system, a call to System.getProperty("awt.toolkit") returns a value of "sun.awt.windows.WToolkit". Where exactly is the "sun.awt.windows.WToolkit" value coming from?
Location: http://www.jguru.com/faq/view.jsp?EID=109481
Created: Jul 24, 2000
Modified: 2000-07-29 20:50:02.911
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by Doug Dew (http://www.jguru.com/guru/viewbio.jsp?EID=28727
The System property "awt.toolkit" is used to load alternative Toolkit's if needed. See http://java.sun.com/j2se/1.3/docs/api/java/awt/Toolkit.html for more info.The default value that you get is used and set by Sun's implementation of JDK. If you use microsoft's JVM then you will get "com.ms.awt.WToolkit" instead.
How can I write from right to left (e.g. hebrew) in a TextField/TextArea?
Location: http://www.jguru.com/faq/view.jsp?EID=109545
Created: Jul 24, 2000
Modified: 2000-07-29 20:23:57.832
Author: Kaloian Doganov (http://www.jguru.com/guru/viewbio.jsp?EID=109010)
Question originally posed by ronen portnoy (http://www.jguru.com/guru/viewbio.jsp?EID=27420
Comments and alternative answersUse ComponentOrientation property of almost all Swing components. Here is an example with JTextArea and Hebrew:
Locale hebrew = new Locale("he", "IL"); JTextArea area = new JTextArea(); area.setComponentOrientation(ComponentOrientation.getOrientation(hebrew));
| reading is Ok but writing is not
Author: Eitan Mizrahi (http://www.jguru.com/guru/viewbio.jsp?EID=1008398), Oct 6, 2002 The solution is not very good. the direction is right to left, but anyway I have to press <ALT>+<SHIFT> to change my language to hebrew - It doesn't done automatically !!! Is there any way to change the language right to left writing - automatically !!! :) |
With about 8% of men and 0.5% of women color-blind, what should I take into consideration when designing a GUI?
Location: http://www.jguru.com/faq/view.jsp?EID=109794
Created: Jul 24, 2000
Modified: 2000-07-29 05:58:43.882
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7
I do not know if the factoid about Men and Women matters :)Comments and alternative answersWell, the simple thing that comes to my mind is that you should not use only Color to encode a piece of information. A very good example is MS Word. It uses green colored wavy underline to show grammatical mistakes and red colored wavy underline to show spelling mistakes.
Having said that, in the real world the traffic signal systems in most contries use the red and green colors which reportedly are the one most confusing to the color-blind.
Second thing is that the application should try to honour the users desktop color setting. That goes for normal display as well as selection highlight and other highlight etc. User may have set a color scheme to what may seem wierd to you because of their color blindness...
| http://webdesign.about.com/library/weekly/aa080800a.htm...
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Aug 14, 2000 http://webdesign.about.com/library/weekly/aa080800a.htm offers a good look into designing for the color blind |
How can I display Help from a dialog box when the corresponding Help button is clicked?
Location: http://www.jguru.com/faq/view.jsp?EID=111805
Created: Jul 26, 2000
Modified: 2000-07-29 20:32:13.782
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Tina Balla (http://www.jguru.com/guru/viewbio.jsp?EID=62523
Add a JButton("Help") to the dialog. Add java.awt.event.ActionListener implementation to it using the button.addActionListener(...);. Then in the actionPerformed(...) callback you could show the help. The choices are -
- Show the help in another java.awt.Frame. This may run into problems if your Dialog was "modal" (this is because the "modality" has been shifting it's meaning from version to version of Java).
- Show it in another non-modal dialog
- Run an external help program e.g.
Using the Runtime.exec("external command");
- WinHelp.exe
- Browser
How can I draw a dotted line in AWT?
Location: http://www.jguru.com/faq/view.jsp?EID=114099
Created: Jul 29, 2000
Modified: 2000-07-29 20:22:52.072
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by ramesh vojjala (http://www.jguru.com/guru/viewbio.jsp?EID=103376
Prior to introducing the Java 2D API into the Java 2 platform, all lines drawn were a single pixel wide solid lines of a single color. So, if you wanted a dotted line in 1.0 or 1.1, you had to do all the intermediate drawing steps yourself.With the Java 2D API though, you can define a Stroke to define the drawing pen. For dotted lines, you would need to use the BasicStroke constructor that accepted six arguments:
public BasicStroke (float width, int cap, int join, float miterlimit, float[] dash, float dash_phase)So, for a dotted line, an example might look like:
import java.awt.*; import java.awt.geom.*; import java.applet.*; public class Stroked extends Applet { public void paint (Graphics g) { Graphics2D g2d = (Graphics2D)g; Rectangle2D rectangle = new Rectangle2D.Double ( 20, 20, 200, 100); g2d.setColor (Color.blue); g2d.setStroke (new BasicStroke( 1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] {2f}, 0f)); g2d.draw (rectangle); } }
Using Java Layout Managers, can a Container be added to another Container?
Location: http://www.jguru.com/faq/view.jsp?EID=114263
Created: Jul 29, 2000
Modified: 2000-07-29 21:08:32.67
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Khaja Hussain Muchumarri (http://www.jguru.com/guru/viewbio.jsp?EID=94096
But of course!Container is a subclass of Component, and because any Component can be added to a Container, Containers can be added to other containers.
Please see http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr for details on how you nest Containers like this to create useful layouts.
How do I convert an image from RenderedImage to BufferedImage?
Location: http://www.jguru.com/faq/view.jsp?EID=114602
Created: Jul 30, 2000
Modified: 2000-08-01 15:52:28.889
Author: clemens privacy (http://www.jguru.com/guru/viewbio.jsp?EID=114598)
Question originally posed by delfim martins (http://www.jguru.com/guru/viewbio.jsp?EID=9614
There doesn't seem to be a direct way to do it, but try the following:
BufferedImage mine =
new BufferedImage(renderimage.getWidth(),
renderimage.getHeight(),
BufferedImage.TYPE_INT_RBG);
mine.getGraphics().drawImage(renderimage,0,0,NULL);
Comments and alternative answers
| Rendered Image -> BufferedImage
Author: Brian Baumann (http://www.jguru.com/guru/viewbio.jsp?EID=707485), Jan 2, 2002 first - there is no BufferedImage.TYPE_INT_RBG second - drawImage does not take a RenderedImage object as a parameter try again |
| Rendered Image -> BufferedImage
Author: jim moore (http://www.jguru.com/guru/viewbio.jsp?EID=828090), Apr 6, 2002
public BufferedImage convertRenderedImage(RenderedImage img) {
if (img instanceof BufferedImage) {
return (BufferedImage)img;
}
ColorModel cm = img.getColorModel();
int width = img.getWidth();
int height = img.getHeight();
WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
Hashtable properties = new Hashtable();
String[] keys = img.getPropertyNames();
if (keys!=null) {
for (int i = 0; i < keys.length; i++) {
properties.put(keys[i], img.getProperty(keys[i]));
}
}
BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties);
img.copyData(raster);
return result;
}
|
How can I implement a password field like JPasswordField with AWT?
Location: http://www.jguru.com/faq/view.jsp?EID=115225
Created: Jul 31, 2000
Modified: 2000-08-01 15:54:54.578
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by Mehmet Ali OK (http://www.jguru.com/guru/viewbio.jsp?EID=55329
java.awt.TextField has a setEchoChar which can be used to implement a password field. Here's some sample code.
import java.awt.*; import java.awt.event.*; public class PasswordDemo extends Frame { public PasswordDemo() { TextField password = new TextField(10); password.setEchoChar('*'); add(password); } public static void main(String[] argv) { final PasswordDemo f = new PasswordDemo(); f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
How can I determine which card is curently being displayed in a CardLayout?
Location: http://www.jguru.com/faq/view.jsp?EID=116482
Created: Aug 1, 2000
Modified: 2000-08-01 16:25:55.332
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by ar_vin rupak (http://www.jguru.com/guru/viewbio.jsp?EID=109932
The displayed component will be the only one in the container that is visible.You can walk through the components in the container and check which one is visible.
For example, to determine if you're on the first or last component (perhaps to disable "previous" and "next" buttons) you could do something like the following (assuming p is the panel with the CardLayout)
boolean firstShowing = p.getComponent(0).isVisible(); boolean lastShowing = p.getComponent(p.getComponentCount()-1).isVisible();
What image file formats can (Applet and Tookit).getImage() use?
Location: http://www.jguru.com/faq/view.jsp?EID=118670
Created: Aug 3, 2000
Modified: 2000-08-03 17:50:04.064
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Carfield Yim (http://www.jguru.com/guru/viewbio.jsp?EID=4648
The GIF and JPEG formats have been accepted since the beginning of Java time. The XBM format has been accepted since Java 1.0 also, but is not widely mentioned as it isn't a popular format. Starting with the 1.3 release, PNG support is now standard, too.Comments and alternative answers
| How can my java program or applet read .bmp, .tif and...
Author: Carfield Yim (http://www.jguru.com/guru/viewbio.jsp?EID=4648), Aug 3, 2000 How can my java program or applet read .bmp, .tif and .pcx file? Is there a plugin or helper class I can use? |
| Re: How can my java program or applet read .bmp, .tif and...
Author: Marco Ferretti (http://www.jguru.com/guru/viewbio.jsp?EID=423555), May 17, 2001 from import java.awt.Frame; public class LookupSampleProgram { // The main
method. // Validate
input. // Create an input stream from the specified file
name to be // Store the input stream in a ParameterBlock to be
sent to // Specify to TIFF decoder to decode images as they
are and // Create an operator to decode the TIFF
file. // Find out the first image's data
type. // Convert the unsigned short image to byte
image. // Setup a standard window-level lookup table.
*/ // Create a LookupTableJAI object to be used with
the // Create an operator to lookup
image1. }
else
{ // Get the width and height of
image2. // Attach image2 to a scrolling panel to be
displayed. // Create a frame to contain the
panel.
|
| How can I display tif graphics in my Java applet? ...
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Dec 10, 2000 How can I display tif graphics in my Java applet? desribes how to read TIF images in appelts. Some of the methods described support the other image files you mention. |
How can I render a screen containing Graphics objects
like rectangle, lines, texts etc into PostScript?
Location: http://www.jguru.com/faq/view.jsp?EID=118857
Created: Aug 3, 2000
Modified: 2000-08-04 19:34:50.733
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Saptadeep Dutta (http://www.jguru.com/guru/viewbio.jsp?EID=33770
The easiest way is to install a Postscript printer driver to your native OS, use the standard Java printing API and print to a file, selecting the newly installed printer in the process.Comments and alternative answers
| Try PSGr
Author: Paul Gifford (http://www.jguru.com/guru/viewbio.jsp?EID=208048), Oct 8, 2001 Take a look at PSGr, which subclasses java.awt.Graphics and produces Postscript output. It's free. http://herzberg.ca.sandia.gov/psgr/ |
Is there a way to send Windows-specific messages from Java to IE or Netscape without using the ms package? (i.e. WM_CLOSE, WM_MOUSEEVENT...)
Location: http://www.jguru.com/faq/view.jsp?EID=118861
Created: Aug 3, 2000
Modified: 2000-08-04 19:51:43.293
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Question originally posed by Tre Guru (http://www.jguru.com/guru/viewbio.jsp?EID=98227
You can write JNI code that does the equivalent of the ms.* packages. There is no native support in Java to do this though (hence Microsoft providing this in their ms.* package).
Is it possible to change the shape of a JButton/Button to be triangular?
Location: http://www.jguru.com/faq/view.jsp?EID=119370
Created: Aug 4, 2000
Modified: 2000-08-04 19:37:26.257
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by Jenny Yang (http://www.jguru.com/guru/viewbio.jsp?EID=116713
Here's a sample based on JDC Tech Tips, August 26, 1999
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class TriangleButton extends JButton {
public TriangleButton(String label) {
super(label);
// These statements enlarge the button so that it
// becomes a circle rather than an oval.
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width,
size.height);
setPreferredSize(size);
// This call causes the JButton not to paint
// the background.
// This allows us to paint a round background.
setContentAreaFilled(false);
}
// Paint the round background and label.
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
// You might want to make the highlight color
// a property of the RoundButton class.
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
int x3Points[] = {getSize().width/2, 0, getSize().width};
int y3Points[] = {0, getSize().height, getSize().height};
g.fillPolygon(x3Points, y3Points, x3Points.length);
// This call will paint the label and the
// focus rectangle.
super.paintComponent(g);
}
// Paint the border of the button using a simple stroke.
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
int x3Points[] = {getSize().width/2, 0, getSize().width};
int y3Points[] = {0, getSize().height, getSize().height};
g.drawPolygon(x3Points, y3Points, x3Points.length);
}
// Hit detection.
Polygon polygon;
public boolean contains(int x, int y) {
// If the button has changed size,
// make a new shape object.
if (polygon == null ||
!polygon.getBounds().equals(getBounds())) {
int x3Points[] = {getSize().width/2, 0, getSize().width};
int y3Points[] = {0, getSize().height, getSize().height};
polygon = new Polygon(x3Points,y3Points,3);
}
return polygon.contains(x, y);
}
// Test routine.
public static void main(String[] args) {
// Create a button with the label "Jackpot".
JButton button = new TriangleButton("Jackpot");
button.setBackground(Color.green);
// Create a frame in which to show the button.
JFrame frame = new JFrame();
frame.getContentPane().setBackground(Color.yellow);
frame.getContentPane().add(button);
frame.getContentPane().setLayout(new FlowLayout());
frame.setSize(150, 150);
frame.setVisible(true);
}
}
Comments and alternative answers
| Triangular button
Author: vivek k (http://www.jguru.com/guru/viewbio.jsp?EID=408377), Jul 26, 2001 Hi The method given here is not satisfactory.It is just drawing a triangle on the JButton and manipulated with the color change while the button is clicked to get a feeling of Triangular button. Please try out this Class with setContentAreaFilled(false); hashed. Then the fallacy becomes obvious. There should be a better method. Thank You Vivek K |
Is there any way to generate offscreen images without relying on the native graphics support? I'd like to create an image without an X server running, or create an image with more colors than the current video mode.
Location: http://www.jguru.com/faq/view.jsp?EID=121936
Created: Aug 8, 2000
Modified: 2000-09-18 09:31:11.489
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by David Noel (http://www.jguru.com/guru/viewbio.jsp?EID=119574
You must have a graphical environment installed on your server to work with Java image routines in AWT, even though the image will only be displayed on the client's machine.Comments and alternative answersThe AWT image manipulation routines use the native platform's graphics primitives and "grab" the resulting image to send to the client.
| You can get a little tool called xvfb: http://www....
Author: Steven Newton (http://www.jguru.com/guru/viewbio.jsp?EID=44606), Aug 8, 2000 You can get a little tool called xvfb: http://www.sunworld.com/sunworldonline/swol-03-2000/swol-03-xvfb.html |
| I found the answer on my own. You can use a virtual...
Author: David Noel (http://www.jguru.com/guru/viewbio.jsp?EID=119574), Aug 8, 2000 I found the answer on my own. You can use a virtual frame buffer server that comes with Xwindows. The program is caled Xvfb. Another solution is to replace the AWT package with a 100% Java version that implements the native graphic functions. An AWT replacement can be found at www.eteks.com. Using either one of these solutions will allow you to run a headless server. |
| I have written a class called PureImage which does...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 24, 2000 I have written a class called PureImage which does this. It creates an offscreen image in a buffer, and uses another class called PureGraphics to draw to it. No Toolkit required. These classes are available at the Purple Technology web site. In addition to allowing a graphics servlet to run on a Unix box without an X server running, this also solves the problem of an NT box whose graphics card is running in black-and-white or a low-bit mode, where images end up dithered or otherwise uglified.
Unfortunately, PureGraphics hasn't been completely implemented. Its drawImage() method works, but drawLine() only works for non-diagonal lines (where either x1=x2 or y1=y2), and most other drawing methods haven't been implemented. Anyone with a copy of a Computer Graphics 101 textbook want to help?
|
| Re: I have written a class called PureImage which does...
Author: sean mcbeth (http://www.jguru.com/guru/viewbio.jsp?EID=1280488), Jan 24, 2006 you want "Bresenham's Line Algorithm" http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm |
| This option will be available in JDK1.4 code-named...
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011), Aug 25, 2000 This option will be available in JDK1.4 code-named merlin. Look at http://developer.java.sun.com/developer/bugParade/bugs/4281163.html at javasoft for more details.
You can also look at the public review draft of Merlin at http://java.sun.com/aboutJava/communityprocess/review/jsr059/merlin.pdf.
Search for "Headless" as the technical term they use for this mode of operation is named
"Headless java".
|
| Another VFB program
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 5, 2001 Alessandro A. Garbagnati reports:
There is a better package than XVFB that has better results. It's called PJA and it can be found at www.eteks.com. I've started using it about 6 months ago and it works great.
|
| Re: Another VFB program
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 15, 2001 However, see Does anyone have solved the "no default font" error in the "pja" package? for a strange issue with PJA. |
| Re: Another VFB program
Author: BRACCHI CABANNES Christophe (http://www.jguru.com/guru/viewbio.jsp?EID=513801), Oct 8, 2001 Need for assistance! On the level localhost/windows JPA goes very well but I have a problem on UNIX:
_X11TransSocketINETConnect: Can't connect: errno = 111
java.awt.AWTError: Graphics2D can't be instantiated
at com.eteks.java2d.PJAGraphicsEnvironment.createGraphics(PJAGraphicsEnv
ironment.java:110)
at com.eteks.java2d.PJABufferedImage.createGraphics(PJABufferedImage.jav
a:112) etc....
Would somebody have it an idea? Thank. |
| Re[2]: Another VFB program
Author: Stephen Oostenbrink (http://www.jguru.com/guru/viewbio.jsp?EID=1018151), Oct 28, 2002 Hi, Did you ever solve this problem? - Stephen |
| See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 2, 2001 See also What causes the error "Can't connect to X11 w... |
| Here's a thread
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 26, 2001 Here's a thread that took place on a different question. I've moved it here for organization's sake. J.P. Jarolim, Apr 18, 2001 You'll find a very usefull replacement of the awt-classes for non x-win enviroments under http://www.eteks.com/pja/en Sharmila Kannangara, Jun 1, 2001 [4] You can load up the XFree86 package from your Linux installation CDs. This has a executable called Xvfb which runs a virtual X server. Set you DISPLAY environment variable to localhost:1.0 Then invoke Xvfb thusly : Xvfb :1 -screen 0 1600x1200x8 & I've used this on Linux and Solaris 8 successfully. Herold Knauf, Aug 13, 2001 [1] I have downloaded xvfb from ftp.xfree86.org but it won't install! I have downloaded the wright version 4.1 for solaris. but when I run the "sh xinstall.sh -check" script I'll get a "No SunOS/Solaris binaries available for this architecture" message. Sharmila Kannangara, Sep 2, 2001 You may have to get the source code and recompile the binaries. I had to do this in order to install under Solaris. paul carver, Sep 2, 2001 [1] If using Tomcat, how do you associate the Xvfb and screen with the Tomcat daemon at boot time? Sharmila Kannangara, Sep 2, 2001 I didn't have to do anything special for the Tomcat configuration. Setting your DISPLAY variable as I mentioned should take of it. |
How do I store anti-aliased images as GIF files while preserving all used colors (like Photoshop does)?
Location: http://www.jguru.com/faq/view.jsp?EID=122164
Created: Aug 8, 2000
Modified: 2000-08-13 18:04:44.659
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by Mathias Bogaert (http://www.jguru.com/guru/viewbio.jsp?EID=119306
A gif file supports a maximum of 256 colours. However, the palette entries are 888RGB (24 bit) format. If you use efficient filters and colour reduction with the original image before converting to gif, you should get better results. If you need better image quality, use JPEG and low (or no) image compression.Comments and alternative answers
| ...or use PNG
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911), Jun 12, 2001 Later JDKs support the PNG file format (I think from JDK1.2 onward). This format gives you the same lossless compression as GIF but with the full colour accuracy of formats like JPG and TIFF. |
Where can I get Java source for drawing 3D graphs?
Location: http://www.jguru.com/faq/view.jsp?EID=124573
Created: Aug 10, 2000
Modified: 2000-08-13 18:01:24.331
Author: Venkatesan R (http://www.jguru.com/guru/viewbio.jsp?EID=124537)
Question originally posed by Paresh Rana (http://www.jguru.com/guru/viewbio.jsp?EID=114277
You can get 3d animations, graphs from many sites like:
- http://www.javafile.com
- http://www.javaboutique.com
- http://www.planet-source-code.com
- http://www.codeguru.com
And many more...
Is it possible to make the background of a Label (not JLabel) transparent?
Location: http://www.jguru.com/faq/view.jsp?EID=126754
Created: Aug 14, 2000
Modified: 2000-08-14 20:53:29.373
Author: John Zukowski (ht