SEARCH YOUR SOLUTION HERE  

problem in printing swing components?

i have a registration page, and after registration of a student i need to print the tc (transfer certificate), in the (Photo1430.jpg) image format, (in the same format shown in the image).
field values are coming from the database.(ie. value of name, value of dob, value of place so on...)

i am doing something like this:

import java.awt.*; import java.awt.event.*; import java.awt.print.*; import javax.swing.*; public class PrintUIWindow implements Printable, ActionListener { JFrame frameToPrint; JLabel lblStuName, lblBirthPlace, lblDob, lblLastSch, lblLastExam, lblYearOdAdd,lblStudyingStandard; JLabel d, d1, d2, d3, d4; static JPanel panel; Box horiz1, horiz2, horiz3, horiz4, horiz5, horiz6; public PrintUIWindow() { panel = new JPanel(); lblStuName = new JLabel("1.) Name of Student (in Full)"); lblBirthPlace = new JLabel("2.) Place of Birth"); lblDob = new JLabel("3.) Date of Birth, Month and year (in figures)"); lblLastSch = new JLabel("4.) Last School College Attended"); lblLastExam = new JLabel("5.) Last Examination Passed"); d1 = new JLabel(" : ........................................................."); d2 = new JLabel(" : ........................................................."); d3 = new JLabel(" : ........................................................."); d4 = new JLabel(" : ........................................................."); d = new JLabel(" : ........................................................."); horiz1 = Box.createHorizontalBox(); horiz1.add(lblStuName); horiz1.add(d); horiz2 = Box.createHorizontalBox(); horiz2.add(lblBirthPlace); horiz2.add(d1); horiz3 = Box.createHorizontalBox(); horiz3.add(lblDob); horiz3.add(d2); horiz4 = Box.createHorizontalBox(); horiz4.add(lblLastSch); horiz4.add(d3); horiz5 = Box.createHorizontalBox(); horiz5.add(lblLastExam); horiz5.add(d4); Box vert = Box.createVerticalBox(); vert.add(Box.createVerticalStrut(100)); vert.add(horiz1); vert.add(Box.createVerticalStrut(30)); vert.add(horiz2); vert.add(Box.createVerticalStrut(30)); vert.add(horiz3); vert.add(Box.createVerticalStrut(30)); vert.add(horiz4); vert.add(Box.createVerticalStrut(30)); vert.add(horiz5); panel.add(vert); } 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()); /* Now print the window and its visible contents */ frameToPrint.print(g); /* tell the caller that this page is part of the printed document */ 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) { /* The job did not successfully complete */ } } } public static void main(String args[]) { JFrame f = new JFrame("Print TC"); JButton printButton = new JButton("Print TC"); printButton.addActionListener(new PrintUIWindow()); panel.add("South", printButton); f.add(panel); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); } }

Posted On: Tuesday 25th of September 2012 09:29:08 PM Total Views:  381
View Complete with Replies




Related Messages:

problem with jcombobox   (207 Views)
hey you all, i have combobox with big list and when i drag the list back and forth the list get messed up. what i have to do in order to avoid this
FINAL problem whit GUI   (164 Views)
i have in a text file the following: Charlize Theron 77777777 Maria Sharapova 44444444 Nicola Tesla 33333333 Mario Bros 11111111 and a gui were you can modify this text file whit the following code: private void ModifyActionPerformed(java.awt.event.ActionEvent evt) { try{ FileReader Ficher=new FileReader("C:\\Documents and Settings\\Chelo\\Mis documentos\\NetBeansProjects\\Obligato\\src\\presentacion\\Grupo.txt"); BufferedReader lee=new BufferedReader(Ficher); ArrayList ar= new ArrayList(); while((Tex=lee.readLine())!= null){ ar.add(Tex); if((Tex).contains(jTextField6.getText().trim())) { ar.remove(Tex); ar.add(Tex=jTextField7.getText()+" "+jTextField8.getText()+" "+jTextField9.getText()); } File fl= new File("C:\\Documents and Settings\\Chelo\\Mis documentos\\NetBeansProjects\\Obligato\\src\\presentacion\\Grupo.txt"); fl.createNewFile(); PrintWriter out = new PrintWriter(new FileWriter(fl)); for (Object s : ar) { out.println(s); } out.close(); } }catch(IOException e){ e.printStackTrace(); } catch(NullPointerException s){}; }
a baffling problem   (167 Views)
i have a Paint program that i am improving. it used a custom class called StandardColorSelector which used a JComboBox to select a color. i changed it to use a JColorSelector instead. the problem is that now when i change either the background color or the foreground color, it fails to store(or redraw) the previously drawn shapes like it used to . it is pretty long so i will try to select relevant parts that might be the problem. please excuse the indentation. old private StandardColorSelector backcolor = new StandardColorSelector(); private StandardColorSelector forecolor = new StandardColorSelector(); public Color getBack() { return backcolor.getSelectedColor(); } public Color getFore() { return forecolor.getSelectedColor(); }
SWT-Chart example problem to execute   (142 Views)
, I checked out SWT-Chart with the following command: svn co https://swt-chart.svn.sourceforge.net/svnroot/swt-chart/trunk swt-chart
Dialog focus problem on java 7 and mac osx   (174 Views)
, I'm currently validating a swing application that runs on a browser (on an applets). I came across with a problem for the java JRE 7 released by Oracle - this was not happening on Applet JRE 6 (1.6.0_33) Every time I open a dialog within my application, that dialog comes to the front of the browser window but it does not request the focus as expected. THIS HAPPENS ONLY WHEN THE APPLET RUNS ON THE BROWSER. Here is a small program to show the problem: package com.macosx.tests; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class AppletDialogExample extends JApplet{ private JPanel panel; private JButton openDialogBtn; private void doStart() { panel = new JPanel(); panel.setPreferredSize(new Dimension(500,500)); panel.setBackground(Color.GRAY); openDialogBtn = new JButton("open dialog"); openDialogBtn.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { Runnable run = new Runnable() { public void run() { JPanel dialogPanel = new JPanel(new GridLayout(1,1)); JTextField textField = new JTextField(); dialogPanel.add(textField); JOptionPane.showConfirmDialog(null, dialogPanel); } }; SwingUtilities.invokeLater(run); } }); panel.add(openDialogBtn); setContentPane(panel); } @Override public void start() { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { doStart(); } }); } catch (Exception e) { throw new RuntimeException(e); } } }
JSlider update another JSlider problems   (160 Views)
Hi , I am taking Java classes at a college level. I am playing around with JSliders and an addChangeListener. The gist of my code is I have two sliders, one is MPH the other is KPH. When one slider is slid, the two fields update and the other slider follows. if you move the other slider, the same happes. My problems seems that when the addChangeListener updates the other slider, it calls the same addChangeListener and then they both stick at 0. I am using an if statement to run seperate commands depending on which slider calls the addChangeListener. in this code if I uncomment the statements to update the other slider in the addChangeListener then it doesnt work, with them commented, the other slider does not update. Im stuck.
having problems with setting the color of a buffered Imaghe   (199 Views)
I created a buffered image in my programme and I want it to have a green (orany color other than black)background however i have been unable to get it to change from black to any other other color.hers the code i have been working with .
problem to execute java script in jwebbrowser in swing   (280 Views)
HI , I have a problem in my swing application, in this application I use the jwebbrowser, and the problem with the jwebbrowser is, it does not execute the java script properly. it does not show all button in browser. but when i resize the frame of my application it appears properly. Can any one have any idea about to solve this problem
problem with JTextField null   (178 Views)
, i've a problem when i try to return the object "JTextField" because this is empty (null) and i don't know wich is the structure to use. In my method i use a Queue but this structure can't contains null objects. Please HELP. public static JTextField checkJTextField(JPanel panel) { int i = 0; Boolean flag = true; Queue queue = null; JTextField objectReturned; java.awt.Component[] component = panel.getComponents(); try { while (i < component.length && flag) { if (component[i] instanceof JTextField) { if (((JTextField) component[i]).getText().equals("")) { queue.offer((JTextField) component[i]); flag = false; } } else if (component[i] instanceof JPanel) { queue.offer(WindowsMethods.checkJTextField((JPanel) component[i])); } i++; } } catch (NullPointerException NPE) { System.out.println("Error."); } objectReturned = (JTextField) queue.peek(); return objectReturned; }
Having some problem with FileDialog   (210 Views)
Hi , I wrote a porgam where there is a textarea and two buttons ,one to load files into the textarea and other button to save what is written in the text area. I have two problems though 1)The methods filedialog.getDirectory(),filedialog.getFile() return nulll so i am not able to load any file in the text area 2)When i try to save a file ,i used filedialog.setDirectory("C:"+"\" ") and filedialog.setFile("untitled.txt").The problem is it doesnt show the c:\ as the default directory when the dialog box opens . import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class button3 { public static void main(String[]args) { test t=new test(); t.go(); } } class test {JFrame frame =new JFrame(); JTextArea area=new JTextArea(10,20); void go() { JButton button1=new JButton("open"); JButton button2=new JButton("save"); JScrollPane scroller=new JScrollPane(area); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); frame.setVisible(true); frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new FlowLayout()); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { FileDialog filedialog=new FileDialog(new Frame(),"Load",FileDialog.LOAD); String name=filedialog.getDirectory()+filedialog.getFile(); try { System.out.println(name); BufferedReader myreader=new BufferedReader(new FileReader(name)); try { while(myreader.readLine()!=null) { area.setText(myreader.readLine()); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } filedialog.setTitle("Load & Save"); filedialog.setVisible(true); } } ); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { FileDialog filedialog=new FileDialog(new Frame(),"Save",FileDialog.SAVE); filedialog.setDirectory("C:"+"\" "); filedialog.setFile("untitled.txt"); try { BufferedWriter mywriter=new BufferedWriter(new FileWriter("untitled.txt")); mywriter.write(area.getText()); mywriter.flush(); mywriter.close(); } catch (IOException e) { e.printStackTrace(); } filedialog.setTitle("Load & Save"); filedialog.setVisible(true); } } ); frame.add(button1); frame.add(button2); frame.add(scroller); } }
JTREE problem   (139 Views)
hi, i want load structured text in to JTree. can some one tell how to do that i want to group it when it on same nodes find attachment below. i want to load text from 'channel' field Thank you
Using AbstractTableModel to show data from user defined Classes - problem passing/defining the data   (152 Views)
Hi all, I have a problem when passing a user defined class to an extended AbstractTableModel I will ask up front for some patience as I am new to Java having done most of my (bad) coding in .NET Scenario: I have a form with a jTree, I make several calls to a database and I populate the jTree (lazily) with the returned objects, I pass these objects to different Classes (defined by me) to store the relevant information. When the use selects a Node in the jTree I would like to retrieve the user object and display its details in a jTable (in .NET I used the ListView and jTable seems to be the best thing in Java) I coded a new AbstractTableModel inside the main class and call it when the user selects a node, this code works fine and I can set column names and return tree node data, however this is within the main class.....so..... After doing some reading and looking at some examples I decided to create my own AbstractTableModel class for each of my own classes and then instantiate them on demand by passing the selected tree node to the relevant table model (sounds reasonable ) The problem is that for some reason my class object is not being passed correctly and I get a null exception, I have debugged and can see that the object I pass is the correct one but it never gets used in my table model My table model class is here: public class TableModelRNC extends AbstractTableModel { private RNC myRNC; public TableModelRNC(RNC tmpRNC){ myRNC = tmpRNC; } //set the data to be passed to the columns Object columnData[][] = {{myRNC.rncID, myRNC.rncName, myRNC.rncOMSip}}; //set the column names Object columnNames[] = {"RNC ID", "RNC Name", "OMS IP"}; //below is required for the jtable to function @Override public String getColumnName(int column) { return columnNames[column].toString(); } @Override public int getRowCount() { return columnData.length; } @Override public int getColumnCount() { return columnNames.length; } @Override public Object getValueAt(int row, int col) { return columnData[row][col]; } @Override public Class getColumnClass(int columnIndex) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void addTableModelListener(TableModelListener l) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void removeTableModelListener(TableModelListener l) { throw new UnsupportedOperationException("Not supported yet."); } }
overlapping problem of jpanels   (193 Views)
As i got reply from Wendy Gibbons in JDBC section's topic which i created worry about other considerations when you have the simplest version working. Here i try simplest version as per my thought. I make simple swing program (Just swing no jdbc or hibernate & db), Name simpleExample.java Contains 1 JFrame, Array of jpanels.(only 3 jpanels i create by array). Major code is here., but i modified it as i try in 2-3 days after last post in that question. If you want to see how it developed, 1. 3 questions regarding JPanel. Creation of problem:- When program runs 3 panels we can see, 0,1,2. If we drag & drop panel 0 on panel 2, it will locate beside it because code goes to check_overlap_panel(); & run for loop & check if condition & set as below. simpledm.comp_panel.setLocation(simpledm.comp_panel.getX()+25, simpledm.comp_panel.getY()+25); but when we drag & drop panel 1 on panel 2,it will do same for checking ovelaping against panel 2, & setlocation as per above quote,but it forget already that location occupy by panel 0. Problem panel 1 not try to cross check overlap against panel 0. If i increase myindex = any number, then it should be try to setlocation of panel as avoid overlap against another panel. I try my best & then post question...I also try sscce for code What i do:- Here i try to create 13 boolean flags to check many if-else conditions & for easiness i create 5 functions Conditions like 1. In check_resolutionboundries() function i check panel should not move beyond systems resolution, so if program run on any monitor which has any resolution, then it will run without trouble. This function i called in mousedragged event. 2. When program runs all integers are 0 so 1st condition is check integer against 0 in function check_int_zero(). 3. When function check_int_zero() calls in chek_flags(), to check probability of flags true & false. 4. check_overlap_panel() function contain code for checking panels overlap or not. private void check_overlap_panel() { for (Counter= 0; Counter < panels.length; Counter++) { if (simpledm.comp_panel.getBounds().intersects(simpleExample.panels[Counter].getBounds())) { if (Integer.parseInt(simpledm.comp_panel.getName()) != Integer.parseInt(panels[Counter].getName())) { Flag_over= false; }else { Flag_over = true; }}}}
JcomboBox duplicates problem   (125 Views)
, I have two JComboBoxs, the first one is filled from database, the second one is filled after user's choice on the first comboBox. Once a choice in second comboBox is done, some JLabels are filled from database. The problem is that when I select an item in the first combobox and then I change the choice thr first item is always present and the second is added with dupplicates. final JComboBox comboBox1 = new JComboBox(); final JComboBox comboBox2 = new JComboBox(); try { String sql = "Select matricule FROM clients"; rs = stat.executeQuery(sql); comboBox1.addItem("Select item"); while(rs.next()) { comboBox1.addItem(rs.getInt("matricule")); } } catch (SQLException e) { e.printStackTrace(); } comboBox1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { int matricule = (Integer) comboBox1.getSelectedItem(); String sqll = "Select * FROM clients WHERE matricule = " +matricule; try { rs = stat.executeQuery(sqll); while(rs.next()) { nom.setText(rs.getString("nom")); prenom.setText(rs.getString("prenom")); cin.setText(rs.getString("cin")); adresse.setText(rs.getString("adresse")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql = "Select DISTINCT p.code FROM parcelle p, clients c WHERE c.matricule = p.exploitant AND c.matricule = " +matricule; try { rs = stat.executeQuery(sql); while(rs.next()) { comboBox2.addItem(rs.getInt("code")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); comboBox1.setBounds(154, 317, 105, 20); contentPane.add(comboBox1); comboBox2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { int code = (Integer) comboBox2.getSelectedItem(); String sqll = "Select * FROM parcelle WHERE code = " +code; try { rs = stat.executeQuery(sqll); while(rs.next()) { sau.setText(rs.getString("sau")); sol.setText(rs.getString("type_sol")); irrigation.setText(rs.getString("mode_irrigation")); exploitation.setText(rs.getString("type_exploitation")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); comboBox2.setBounds(154, 423, 105, 20); contentPane.add(comboBox2);
JTextField focus problem   (235 Views)
Hi , I have problem with active textfield when start the GUI. Got the JTextField component inside JTable, and the jTable inside another JTable ie. JTableOuter - > JTableInner - > JTextField. If window is displayed, I set up the focus for the first JTextField component, but nothing happened, the focus occurs and component is active when I do mouse clicking on it. I modified this source code: http://pekalicious.com/blog/custom-jpanel-cell-with-jbuttons-in-jtable/ Any ideas
Focus problem using JOptionPane.showInternalMessageDialog   (150 Views)
I have JFrame, which contain JInternalFrame. JInternalFrame contains 3 labels, 3 textfield and 2 buton. When user after entering details in textfield click OK, if any of the textfield is left blank a message is displayed and focus should return to that textfield. When JOptionPane.showMessageDialog is used it works perfect, it display message and focus return to empty textfield. The problem is when using JOptionPane.showInternalMessageDialog it display message and focus remain on OK button. Please help and let me know what i am missing in the code. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class JFrameFocusTest extends JFrame { JDesktopPane desktopPane; public JFrameFocusTest() { setTitle("Main Frame"); setSize(600, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); desktopPane = new JDesktopPane(); setContentPane(desktopPane); createFrame(); } protected void createFrame() { JInternalFrameFocusTest iframe = new JInternalFrameFocusTest(); iframe.setVisible(true); desktopPane.add(iframe); iframe.pack(); try { iframe.setSelected(true); } catch (java.beans.PropertyVetoException e) {} } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrameFocusTest frame = new JFrameFocusTest(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] arg) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } // end class JFrameFocusTest class JInternalFrameFocusTest extends JInternalFrame implements ActionListener { JLabel firstNameLabel; JLabel middleNameLabel; JLabel lastNameLabel; JTextField firstNameTextField; JTextField middleNameTextField; JTextField lastNameTextField; JButton okButton; JButton cancelButton; public JInternalFrameFocusTest() { super("Internal Frame", true, true, true, true); JPanel inputPanel = new JPanel(); JPanel buttonPanel = new JPanel(); firstNameLabel = new JLabel("First Name"); middleNameLabel = new JLabel("Middle Name"); lastNameLabel = new JLabel("Last Name"); firstNameTextField = new JTextField(5); middleNameTextField = new JTextField(5); lastNameTextField = new JTextField(5); inputPanel.add(firstNameLabel); inputPanel.add(firstNameTextField); inputPanel.add(middleNameLabel); inputPanel.add(middleNameTextField); inputPanel.add(lastNameLabel); inputPanel.add(lastNameTextField); this.add(inputPanel,BorderLayout.NORTH); okButton = new JButton("Ok"); okButton.setActionCommand("OK"); okButton.addActionListener(this); cancelButton = new JButton("Cancel"); cancelButton.setActionCommand("CANCEL"); cancelButton.addActionListener(this); buttonPanel.add(okButton); buttonPanel.add(cancelButton); this.add(buttonPanel,BorderLayout.SOUTH); setSize(400, 100); setLocation(50, 50); } public void actionPerformed(ActionEvent e) { String Message = ""; String actionCommand = e.getActionCommand(); if (actionCommand.equalsIgnoreCase("OK")) { Message = ValidateForm(); if (Message == "") { System.out.println("Everything is OK"); } else //JOptionPane.showMessageDialog(this, Message, "Focus Test", JOptionPane.WARNING_MESSAGE); JOptionPane.showInternalMessageDialog(this, Message, "Focus Test", JOptionPane.WARNING_MESSAGE); } } // end actionPerformed private String ValidateForm() { String validateForm=""; if (firstNameTextField.getText().equals("")) { validateForm = "Enter First Name"; firstNameTextField.requestFocusInWindow(); } else if (middleNameTextField.getText().equals("")) { validateForm = "Enter Middle Name"; middleNameTextField.requestFocusInWindow(); } else if (lastNameTextField.getText().equals("")) { validateForm = "Enter Last Name"; lastNameTextField.requestFocusInWindow(); } return validateForm; } // end Method ValidateForm } // end class JInternalFrameFocusTest
Main Method problem in netbeans7.1 J Frame form   (150 Views)
Hi! I am having an issue with my java form. It won't run because it doesn't have a main method. I know that in the main method I have need has some hidden components. I was wondering if there is some magic button you can press that will insert the main method, or should I start all over again. It's not my first form and I know that most of the time I don't create the main method its automatically there for me. If there is no other choice that to start all over again could you please point me in the right direction so I won't run into this problem again. This is not the first time I've had this problem, but there must be an easier way to solve this problem than deleting the page and starting again. Any information would be greatly appreciated.
problem with selecting multiple rows in JTable   (207 Views)
hi i'm facing problem with selecting multiple rows in JTable. only single row is getting selected even though table.setRowSelectionowed(true); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
How to maintain session in swing?   (169 Views)
Can anyone tell me how to maintain session in swing desktop applications I want to maintain session for user logins and sessions to be invalidated when logout from application. I know the session implementation in JSF. Is there a way to do this in swing
Problem with Java swing directory chooser   (128 Views)
I have used swing directory chooser to select input directory for my application to process. But if I select a particular directory, for example.. c:/Desktop/user/documents/myfolder filechooser.getcurrentDirectory() returns only "c:/Desktop/user/documents/". Why Can anyone say why this is happening