java: How to print JForm - java

I am having code of print a string, which is passed in the program itself. Here I am calling this code on Print button to get hard copy. Now I want to print a JForm in the same code, But I am not getting how to do this. JForm having some labels and textfields of user's details. This is the code where I am printing a string"Hello World".
public class PrintClass implements Printable, ActionListener {
public int display(Graphics g, PageFormat pf, int page) throws
PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Now we perform our rendering */
g.drawString("Hello World", 100, 100);
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
Please help me to call constructor of a JForm, instead of pass the string.

Draw the Graphics of your current JFrame into a BufferedImage and then draw the image into the printer's Graphics.
Graphics g = myFrame.getContentPane().getGraphics();
// draw graphics into an image
// draw the image into the printer's graphics
It is important to note that you should always get a new Graphics object from your JFrame whenever you want to print the form content

Related

Copy the contents of a JPanel onto a BufferedImage

On the first time through, I insert BufferedImages from a list onto my JPanel from my extended class:
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
if (controlWhichImage == 1){
for (BufferedImage eachImage : docList){
g.drawImage(eachImage, 0,inty,imageWidth,imageHeight,null);
intx += eachImage.getWidth();
inty += eachImage.getHeight() * zoomAdd;
}
if (intx >= this.getWidth() || inty >= this.getHeight()){
inty = 0;
}
The next time I want to copy the contents of the JPanel to a BufferedImage:
public void recordImage(){
controlWhichImage = 2;
this.createdImage = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
Image halfWay = this.createImage(this.getWidth(), this.getHeight());
//now cast it from Image to bufferedImage
this.createdImage = (BufferedImage) halfWay;
}
And then, take the modified BufferedImage and draw it back onto the JPanel:
if (controlWhichImage == 2){
g.drawImage(this.createdImage,0,inty,this.getWidth(),this.getHeight(),null);
}
This second time I get a blank panel.
I hope this is clear, any help gratefully received.
Sorry for my poor explanation. I will try to make myself clearer.
On each iteration the user is able to draw on the image in the Jpanel.
What I want to do is copy the user altered jpanel into a buffered image which will then be in the Jpanel to be edited again by the user.
This continues until the user selects print.
So apart from the code that I have put here are the controls for drawing by the user, at the moment I am struggling with putting the initial updated image from the original Jpanel into a bufferedImage and then back to the JPanel.
Hope this makes it somewhat clearer
To draw to a BufferedImage, you would do something similar to what you already do in your paintComponent method, but with your BufferedImage. Perhaps a method like:
// imgW and imgH are the width and height of the desired ultimate image
public BufferedImage combineImages(List<BufferedImage> docList, int imgW, int imgH) {
// first create the main image that you want to draw to
BufferedImage mainImg = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
// get its Graphics context
Graphics g = mainImage.getGraphics();
int intx = 0;
int inty = 0;
// draw your List of images onto this main image however you want to do this
for (BufferedImage eachImage : docList){
g.drawImage(eachImage, 0,inty,imageWidth,imageHeight,null);
intx += eachImage.getWidth();
inty += eachImage.getHeight() * zoomAdd;
}
}
// anything else that you need to do
g.dispose(); // dispose of this graphics context to save resources
return mainImg;
}
You could then store the image returned into a varaible and then draw it in your JPanel if desired, or write it to disk.
If this doesn't answer your question, then again you'll want to tell more and show us your MCVE.

Issues with passing arguments to the print function in Java

public int print(Graphics g, PageFormat pf, int page, String customer_name)
throws PrinterException {
System.out.println("The value of customer name:"+customer_name);
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
String x = layout.get("");
System.out.println("The value of x is\n"+x);
/* Now we perform our rendering */
g.drawString("Customer Name: "+customer_names, 100, 100);
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
I want to call this method from another class, while passing an additional argument to it, customer_name. I call this method from another class as follow:
Printer print = new Printer(); //making an object to access that class Printer.java
PageFormat page = job.defaultPage();
print.print(<I have no idea what to put here for graphics>, page, 5, customer_name_field.getText());
When I call the method print.print, I gives the message that it requires Graphics, PageFormat, int, String. But what should I put for Graphics, I have no idea?
It's not working because it looks like you're going about it wrong:
Your print method has an extra String parameter tacked to the end which prevents it from being a true method override for a class that implements Printable.
You're trying to call your print method directly scrounging around for a Graphics context when you shouldn't consider doing this.
If you just want to print some text then you need to follow the first sections of the Printing Tutorial. Your print method above does not conform with a Printable's print(...) method override. Please do yourself a favor and follow the tutorial. I've given you the link.
Consider creating a class that implements Printable, passing your String as a single parameter to the class's constructor, and use this to set an instance field. The print(...) method should match that found in the tutorial, should have an #Override annotation, and most important will never be called directly by you. Your PrinterJob instance will do the printing behind the scenes.
Note, that if your goal is to print a Swing GUI, then the steps are different, since Swing GUI's carry much of the innate machinery for printing within them.
Depends on the class you're in, there's a high chance that the UI framework element you are currently using already provides you with the getGraphics() function.
You might even want to override the paint() function of the class you're using, and call this method you have written from that. It depends on your use-case.
This is my github project path where i did the code for same. https://github.com/knikam/Mobile_shop_management/blob/master/src/mobile_shop_mangment/Sell_mobile.java
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
String x = layout.get("");
System.out.println("The value of x is\n"+x);
/* Now we perform our rendering */
String customer_namescustomer_names.getText();**This is work for me**
g.drawString("Customer Name: "+customer_names, 100, 100);
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}

Translate/Rotate/Move a graphics object without messing up the whole screen

I'm coding a GUI that will be doing some graphics translations/rotations, etc.
My problem is that when I try to translate my graphics,
(a) The entire screen translates instead of my one little painted area
(b) The old paint stays there, leaving a big paint blob instead of a translated image
(c) If I use the clearRect method to allow me to avoid (b), the entire screen goes white and (a) is still a problem
my DrawPanel class (I called it "LaunchTubeImage" for whatever reason)
private class LaunchTubeImage extends JPanel {
private Color colour;
public LaunchTubeImage(Color color) {
super();
this.colour = color;
}
public void paintComponent(Graphics g) {
Graphics2D gg = (Graphics2D)g;
double theta = (double)angle.getValue();
theta = Math.toRadians(theta);
gg.rotate(theta,tubeImage.getSize().width/2 + 10,
tubeImage.getSize().height - 50);
g.setColor(colour);
g.clearRect(0,0,getWidth(),getHeight());
g.fillRect(tubeImage.getSize().width/2,
tubeImage.getSize().height - 100 , 10, 50);
}
}
where this is called in my code
tubeImage = new LaunchTubeImage(Color.MAGENTA);
angle.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
tubeImage.repaint();
}
});
Case 1: Comment out clearRect in that 1st block of code I posted
http://i58.tinypic.com/2d1l5w2_th.png
Black background as desired. Not rotated yet. Looks good so far.
http://oi60.tinypic.com/1zw1sm.jpg
Rotated it with my JSpinner... you see that the previous location was not removed (and note how my buttons randomly doubled and put themselves at the top of the screen).
Case 2: Keeping in the clearRect method
oi57.tinypic.com/2s84307.jpg
Layout is fine so far, but I wanted the background to be black
oi57.tinypic.com/4rde8x.jpg
Yay! It rotated. But note the weird behavior of that random "15" that appeared in my top right corner
oi58.tinypic.com/vymljm.jpg
And finally... when I resize the window you see that my entire screen was rotated - not just the pink image I wanted to rotate
Tips/fixes/advice? Thanks!! I hope I've provided enough information
(P.s. if you insist on us asking clear/useful questions.... then DON'T limit the number of images you can post... :/ )
The first line of an overridden paintComponent method should usually be super.paintComponent(g). On a JPanel, this will cause the drawing area to be cleared with the background color. If you want to clear the background with a different color, you can do this by manually filling a rectangle (clearRect is discouraged, see the JavaDoc), but of course, this has to be done before applying any transform.
So your method should probably look like this:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(colour);
g.fillRect(0,0,getWidth(),getHeight());
Graphics2D gg = (Graphics2D)g;
double theta = (double)angle.getValue();
theta = Math.toRadians(theta);
gg.rotate(theta,tubeImage.getSize().width/2 + 10,tubeImage.getSize().height - 50);
gg.fillRect(tubeImage.getSize().width/2,tubeImage.getSize().height - 100 , 10, 50);
}

how to print contents of a jpanel as text?

I'm using netbeans and I have the code to print a jpanel and it works fine. However, its output is that it prints the jpanel as an image. This is not ideal for me as it also prints a faded gray color in the background which is the size of the jpanel. I only want to print the text in the jpanel which consists of many jlabels. Is there a way to print the contents of a jpanel as text and not an image?
This is the code that I used to print the contents of my jpanel
PrinterJob job = PrinterJob.getPrinterJob();
job.setJobName("jPanel13");
job.setPrintable (new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum){
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
jPanel13.paint(g2);
return Printable.PAGE_EXISTS;
}
});
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
}
This is a printscreen of the jpanel that I need to print. In my program, the text values of the jlabels can be changed by the user. The jlabels texts will then be printed to fill in the blank lines a form. The form will already have writing on it; it is only the blank lines that I will fill-up when printing. That is why it is important that the jlabels are positioned in that way.
http://i.stack.imgur.com/kPKWe.jpg
If the JPanel background is the only problem, you can call print() on it instead of paint(), and override printComponent() to do nothing (the default just calls paintComponent()).
Alternately, just set the background color to white while printing.

Jlabel with Image Fade Out Strange Effect

Hope this question could emphasize more about the fading out effect of Jlabel (swing).
Certainly, yes... I already follow some guide and some answers given from This Link Thread, but mine is quite a bit different. It's not just only A text inside the JLabel, there's an image i put on.
I proceed to follow on the Thread Located out of stackoverflow. And yet, it gives me a fade out effect. But there's horrible thing occured; the white background.
How to solve this out?
I share the interface here...
The First screenshot taken here is the earlier phase when the fade out have not occured yet. While,
The Second screenshot taken here is the unwanted result i mentioned.
Tobe honest, I used the Trident Library to do animatiing;
So, whenever the user click over the image it will execute this code;
Timeline tm = new Timeline(jll_btnProceed);
tm.addPropertyToInterpolate("intensity", 1.0f, 0.0f);
tm.setDuration(1000);
tm.play();
and... the JLabel itself, I used to override it using this source code;
/**
*
* #author Gumuruh
*/
public class JLabelFader extends JLabel {
private float intensity = 1.0f;
public void setIntensity(float intensity) {
this.intensity = intensity;
this.setOpaque(false);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
final Composite oldComposite = g2.getComposite();
g2.setComposite(AlphaComposite.SrcOver);
final Color c = getBackground();
final Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int) (255 * (1.0f - intensity)));
g2.setColor(color);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setComposite(oldComposite);
}
}
My hand and my head can't stop for making this trully solved. Thus I tried to follow up some example from the Java Filthy Rich Client ebook and then applying the source code given below, but first I need to COMMENT the protected void paint(Graphic g) method written above, and simply adding this source code;
private BufferedImage buttonImage = null;
public void paint(Graphics g) {
// Create an image for the button graphics if necessary
if (buttonImage == null || buttonImage.getWidth() != getWidth()
|| buttonImage.getHeight() != getHeight()) {
buttonImage = getGraphicsConfiguration().
createCompatibleImage(getWidth(), getHeight());
}
Graphics gButton = buttonImage.getGraphics();
gButton.setClip(g.getClip());
// Have the superclass render the button for us
super.paint(gButton);
// Make the graphics object sent to this paint() method translucent
Graphics2D g2d = (Graphics2D) g;
AlphaComposite newComposite =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, intensity);
g2d.setComposite(newComposite);
// Copy the button's image to the destination graphics, translucently
g2d.drawImage(buttonImage, 0, 0, null);
}
in which at the end... giving me nice fade out effect. But At first, it gave me the 2nd horrible effect which is BLACK BACKGROUND rendered first. Can't believe me?? Okay, Here is First screen shot AFTER applying code from ebook. and here is the nice fade out effect result.
If there's somebody telling me;
"YOUR PNG IS NOT TRANSPARENT!".
Please, dont say like that. Because, I followed the creation of PNG inside the Photoshop nicely using this Tut.
Now, My head's spinned, but my heart laughed and can't handle it over. OMG. Geeezzz....!
And the New Stories begun...
* UPDATED FROM HERE AND BELOW *
Ehm, depply thank you very much to our friend called... MKorbel,
from his thread given at this link. Providing a clear example of fading out effect the Swing JButton and I tried to implement it into my JLabel, and violaaa...!!
IT works.
Let's give a big clap for MKorbel. :D
SO anyway, how could I fix the earlier code? Pretty simple, just COMMENT the Paint() method, and use again the paintComponent() method and it should be overriden with the new source code below;
#Override
public void paintComponent(java.awt.Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, intensity));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
g2.dispose();
}
Now the JLabel become easy to be changed with its intensity -variable.
Fading out and Fading in is accomplished.
Okay. Now everything seems "OKAY". BUt hold a moment, there's something strangely occured again here. Have you noticed it? Hmmm....
I tried to give a Mouse Event (Hover On) into the JLabel that we override the paintComponent() method discussed earlier.With this line of code;
myJLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Logically, it should change the Cursor when Hover ON. But, Here comes another strange effect. (Really sorry, but this is stil the continue of the main case). The strange effect now is the Mouse Cursor can't be changed when we Hover On the Jlabel. It still can't change the Cursor. Seems the paintComponent() method effecting the way Cursor react. Is that true?

Categories