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;
}
Related
In my computer science class we are learning Java and we have come to the point in the course where we are learning about object orientation and how it is useful. We started a project a couple days ago, however instead of being tasked with basic object orientation, my teacher decided to challenge me and a few others by creating graphics right away without really teaching us.
We were tasked with creating a "Molecules" program that would accept an integer to create an array, and for each available section in the array, create a random x and y coordinate, as well as a size for the radius. Using these variables, a oval would be created. My teacher also told us that we should do this using either JFrame or JPanel, I chose JFrame.
In the code below you can see my attempt at this and where I am getting stuck. I have commented out the portion of setting the different colours because it is not important to this case.
/**
* Name: Dylan Eisen
* Date: May 1, 2017
* Project: Object Oriented
* Program: Molecules.java
*/
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class Molecules extends JFrame
{
static Graphics g;
public Molecules(Graphics g, int x, int y, int size)
{
super.paint(g);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int num = in.nextInt();
int x = 20, y = 20, size = 20;
object elements[] = new object[num];
for(int i = 0; i < elements.length; i++)
{
x = (int)(Math.random()*1600);
y = (int)(Math.random()*900);
size = (int)(Math.random()*100);
elements[i] = new object(g, x, y, size);
}
Molecules f = new Molecules(g, x, y, size);
f.setSize(1600, 900);
f.setVisible(true);
//f.getContentPane().setBackground(Color.BLACK);
f.setTitle("Molecules Program - Dylan Eisen");
}
}
class object
{
Graphics g;
int x, y, size;
public object(Graphics g, int x, int y, int size)
{
this.x = x;
this.y = y;
this.size = size;
}
void paint(Graphics g)
{
//g.setColor(Color.WHITE);
g.fillOval(x, y, size, size);
}
}
If anyone could help me but also explain to me where I am going wrong, and how to fix this in the future, it would be really helpful!
If anyone could help me but also explain to me where I am going wrong, and how to fix this in the future, it would be really helpful!
The first problem is, you don't seem to understand how painting actually works in Swing. Painting is a little bit of black magic, it seems like Swing "magically" calls the paint methods. It's not overly complex, but I would highly recommend having a look at Painting in AWT and Swing and Performing Custom Painting to better understand how the painting process works and how you can intergrate with it.
My teacher also told us that we should do this using either JFrame or JPanel, I chose JFrame.
I would recommend using a JPanel as the base component, you can add this to whatever container you want later, which provides for a much more flexible solution.
As general recommendation, you should override the paintComponent of JPanel. If you find yourself overriding paint, you're probably doing something wrong.
You may also find that you have other issues with JFrame, as it's painting process is not double buffered and could also be interfered with by other components contained within the frame itself
A JFrame is actually a container for the JRootPane, which contains the contentPane, JMenuBar and glassPane
When you override paint of JFrame, the other components can paint over your stuff without you been notified (they can can be painted independently)
Generally speaking, a Graphics context is a abstract concept of a series of routines which can generate a image. Swing passes the Graphics context used to paint the window through the paint methods, you should never maintain a reference to this context and you should only use it when the paint method is called. This means that your object class won't need a constructor which needs a Graphics context, it should only ever be painted within the context of a paint method/cycle.
object is a really, really bad name of a class, as Java defines a Object class of it's own, which all other classes extended from by default (if they don't specify a parent class)
I'd also highly recommend that you take a look at Code Conventions for the Java Programming Language. It will make it easier for other people to read your code and for other people to read yours
so i got this error:
java cannot be applied to given types; required: java.lang.String,int,int; found:java.lang.String; reason: actual and formal argument lists differ in lenghhs
when i typed this in one Actor (im using Greenfoot):
public String getPunkte()
{
String stringPunkte = Integer.toString(punkte);
return(stringPunkte);
}
and this in the other:
public void malePunkte()
{
GreenfootImage img = new GreenfootImage(50, 10);
img.drawString(getPunkte());
}
for those who dont understand:
this is supposed to convert the int (punkte)(means points in german) into a String and then return the amount of points in one actor to the other, wich then displays that number.
if you still don't understand or you need another piece of code just ask.
Thx
Well error is quite self explanatory isn't it ?
what you expect to get back is String, int, int and you only 'supply' String
try this
public void malePunkte() {
GreenfootImage img = new GreenfootImage();
img.drawString(getPunkte(), 50, 10);
}
ps. on return statement you do not need to surround with bracket the variable you want to return. Just do
return stringpunkte
ps. i have no idea what the GreenfootImage is ;)
edit: According to helpful link provided by - Gyro Gearless
www.greenfoot.org/files/javadoc/greenfoot/GreenfootImage.html
drawImage(GreenfootImage image, int x, int y)
Draws the given Image onto this image
and
GreenfootImage(int width, int height)
Create an empty (transparent) image with the specified size.
As you can see drawImage draws on top of the created 'empty' image. So as Constructor argument you can specify the size of empty image, and as to a method you can specify the size of the new image that will go on top of the empty one
Solved.
I had a question before but it was very badly posted so here it goes again, according to better rules.
I want to create some style of a graph such as this image:
.
It's based on a physics law, Snell's Law. As of now I've managed to paint the graph it self with a basic Line2D.Double which you can see here (Line.java). Then all I need to do is, in the interface class, add the lines to the array in that class as so:
LinesArray.addLine(150 , 25 , 150 , 275);
And every time it adds a new one, it repaints as you can see in the code sample.
But the problem is that I have no idea how to make this interactive. I wanted to make it interactive, as in that you could actually move those lines and at the same time you move the first line, the second would move accordingly to the Snell's Law formula, which is:
n1 * sin( a1 ) = n2 * sin ( a2 )
Considering that a1 is the first (left) angle, and a2 the second (right) angle in the first image posted.
A perfect example of what I'd hope to achieve is this one.
And if interactive movement is too hard (I'm on a 2 days schedule), this example is also a possibility.
Correct me if I'm wrong but for the second one, all that I'd need to do is calculate the mouse's coordinates and draw and calculate everything from there.
Here (menu_ui.java) is my interface class, in which the method I'm currently working with the lines is "menuSnell()" and here (Snell.java is my Snell class which contains the logic. Apologies for portuguese comments but it's fairly simple code which you don't really need comments to understand, plus I've separated it into readable methods.
So basically, my question is how do I make those lines interactive in the way I've described above.
Thanks!
I am not a graphic expert, but I had similar work a long time ago. I had an object that I need to repaint. I created my own JPanel, which holds my objects that should be paint. Whenever something changed, I call repaint method on JPanel. It looked like this
http://sourceforge.net/p/scribbler-cvut/code/132/tree/Tuzka/src/cz/cvut/scribbler/panel/RewritableGlassPane.java.
private LinkedList<ColoredArea> background = new LinkedList<ColoredArea>();
/**
* Vykreslí všechny položky v senamu vykreslených obrazců
* #param g2d grafika k vykreslení
*/
public void paintShape(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (ColoredArea area : background) {
area.fill(g2d);
}
if (mouse != null && !block) {
g2d.setColor(mouse_color);
g2d.draw(mouse);
}
if (point!=null){
SetPointsDialog.paintPoints(point, maxPoint, parent.getChildsSize(), g2d);
}
}
#Override
public void paint(Graphics g) {
paintShape((Graphics2D) g);
}
#Override
protected void paintComponent(Graphics g) {
paintShape((Graphics2D) g);
}
Everything I need to paint was stored in background variable. When something I LinkedList changed, I invoke repaint () method on the window.
I have a full source code store here: http://sourceforge.net/projects/scribbler-cvut/ but it was my long term project, so it is a little bit big.
I have question how to check how many pages will be printed when i use my own Printable class.
I need it, because i want to have "page_number/total_pages" in footer of each page.
In my case problem with estimation of rows is that rows are wrapped. Additionaly the are empty rows beetwen some of the lines of text and there are some other cases which can prevent regular spreading of text. Generally this is not uniform printing.
As you know, rendering process is done after calling all print dialog windows.
Is any way to deal with this issue or should i somehow launch printing simulation , to receieve real number of pages? Or maybe should i implement some other class?
Regards
You can use following to get no. of pages:
int linesPerPage; // No. of lines per Page to be drawn.
static int numPages; // No. of pages too be rendered.
public int getNumberOfPages() // Override method to get Number Of Pages.
{
return numPages;
}
in main..
linesPerPage = (int)Math.floor(format.getImageableHeight()/linespacing);
numPages = (DATA_to_Print.length - 1)/linesPerPage + 1;
in override print method..
if ((pagenum < 0) | (pagenum >= numPages))
{
return NO_SUCH_PAGE;
}
Each time when print method will be call, value of the numPages will increment.
I figured out how to do it. Maybe this is no elegant, but it works (i tested estimation with document with 1200 pages and estimation is accurate). I will show you rather concept supported with couple line of code because my Printable classes are complex.
This is class which calls all operations connected with printing:
package print_manager;
import icd_searcher.ResultContainer;
import java.awt.Point;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import others.MeasuredBox;
public class PrintManager
{
private PrinterJob printerJob;
private SimpleResultPrinter srp;
/**
* Print printable object.
*
* #param toPrint
*/
public void initPrint(ResultContainer resultToPrint)
{
printerJob = PrinterJob.getPrinterJob();
PageFormat selectedArea = printerJob.pageDialog(printerJob.defaultPage());
MeasuredBox margin = new MeasuredBox(new Point((int) selectedArea.getImageableX(), (int) selectedArea.getImageableY()), (int) selectedArea.getImageableWidth(), (int) selectedArea.getImageableHeight() - 72);
srp = new SimpleResultPrinter(resultToPrint, margin);
SimpleResultPrinterSimulator srpSimulation = new SimpleResultPrinterSimulator(resultToPrint, margin);
// total pages simulation
int totalPages = 0;
try
{
while (srpSimulation.print(selectedArea, totalPages) != Printable.NO_SUCH_PAGE)
{
totalPages++;
}
}
catch (PrinterException e)
{
e.printStackTrace();
}
printerJob.setPrintable(srp, widenedPage);
if (printerJob.printDialog())
{
try
{
printerJob.print();
}
catch (PrinterException exc)
{
System.out.println(exc);
}
}
}
}
Method print in SimpleResultPrinter
public int print(Graphics g, PageFormat page, int pageIndex) throws
PrinterException {...}
Method print in SimpleResultPrinterSimulator
public int print(PageFormat page, int pageIndex) throws PrinterException
{...}
You need to know about this:
MeasuredBox and ResultContainer are my custom classes that have no meaning in this conception - treat them as a "some classes".
Class SimpleResultPrinter which is Printable has method print(...) which is called by printerJob.print().
SimpleResultPrinterSimulator has the same method print(...) like SimpleResultPrinter except there is no draw actions in it for better performance and of course SimpleResultPrinterSimulator has only this method. Also SimpleResultPrinterSimulator extends Component because i need Graphics object to measure font height.
My solution is just to launch simulation of printing and print(...) makes the same actions like will be done soon during printing except of real drawing to any Graphics object. Finally i recieves total number of pages.
I know this is not elegant and i make the same action twice (lost of performance), but i don't see any other way to estimate number of pages in complex printing.
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