Okay, so I have a code which gets information from one class and sends it to print in another class after the action is performed.
This code gets the Strings that are in the TextAreas
available and merges them in order to send them to the other class. This is the ActionListener
which merges the TextAreas
and opens another frame to confirm the printing action.
JButton button_2 = new JButton("Print ");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String line= textArea.getText();
String line2=textArea_1.getText();
String line3=line+line2;
Print.setLine(line3);
contentPane.setVisible(false);
dispose();
Print p=new Print();
p.setVisible(true);
}
});
This is the class code. It receives the String which is supposed to be printed. The only problem is it should be printed into a paragraph, and it prints as a straight line (because it is a String)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.print.*;
public class Print implements Printable, ActionListener {
public static String line="";
public String getLine(){
return line;
}
public static void setLine(String x){
line=x;
}
public int print(Graphics g, PageFormat pf, int page) throws
PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
g.drawString(this.linea, 100, 100);
return PAGE_EXISTS;
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
}
}
}
public static void main(String args[]) {
}
public void setVisible(boolean b) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f = new JFrame("Print");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
JButton printButton = new JButton("Click to print");
printButton.addActionListener(new Print());
f.add("Center", printButton);
f.pack();
f.setVisible(true);
}
}
How do I break the long String into paragraphs? Would it be better if I generated a Word document?