problem in printing to file (JSE 6)

I tried using printing support in JTextComponent, as provided in Java SE 6.

The code I used is really simple:
try { boolean complete = jTextArea1.print(); if (complete) { /* show a success message */ System.out.print("success"); } else { /*show a message indicating that printing was cancelled */ System.out.print("cancelled"); } } catch (PrinterException pe) { /* Printing failed, report to the user */ System.out.print("exception"); }

Posted On: Monday 22nd of October 2012 01:51:43 AM Total Views:  456
View Complete with Replies

Related Messages:

repaint() in loop problem   (173 Views)
I'm writing a Swing application that needs to be able to repaint() rectangular regions on a JPanel many times in a loop. Because repaint() only calls the component's paint() or update() method "as soon as possible," the repaint() does not work reliably in a loop. I tried to put a Thread.sleep() before repaint(), but it still does not always work. Sometimes it works perfectly, sometimes only some of the repaints work, and sometimes nothing is ever repainted. Why is this happening and what do I do to be able to repaint() in a loop reliably Thank you, Bob
GridBagLayout problem   (181 Views)
i'm trying to build the following: lbl1 txt1 bt1 bt2 bt3 bt4 lbl2 txt2 bt5 bt6 but when i try to add button bt5 it allways goes right to bt4 right side! here's my code: import javax.swing.*; import java.awt.*; public class Test extends JFrame { static final long serialVersionUID = 2889265010042717001L; private JPanel panel; private GridBagConstraints c; public Test() { super("Editar Conven es"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new JPanel(); panel.setLayout(new GridBagLayout()); c = new GridBagConstraints(); c.insets = new Insets(2, 2, 2, 10); // LINHA 1 c.gridx = 0;// coluna 0 c.gridy = 0;// fila 0 c.anchor = GridBagConstraints.EAST; panel.add(new JLabel("Comparticipa o"), c); c.gridx = 1; c.fill = GridBagConstraints.HORIZONTAL; JTextField txt1 = new JTextField(20); panel.add(txt1, c); c.gridx = 2; JButton b1 = new JButton("||||")); // LINHA 2 c.gridx = 0; c.gridy = 1;// fila 1 panel.add(new JLabel("A pagar pelo Utente"), c); c.gridx = 1; c.fill = GridBagConstraints.HORIZONTAL; panel.add(new JTextField(), c); c.gridx = 2; //c.fill = GridBagConstraints.NONE; panel.add(new JButton("Actualizar")); getContentPane().add(panel); setSize(800, 140); setVisible(true); } public static void main(String args[]) { new Test(); } }
Any one faced a similar problem ?   (192 Views)
My working area consists of two JTextAreas and a JTree. The user can drag a text file from the JTree to the JtextAreas where the header of the file is displayed in one area and the body in the second. My problem is that i need to erase a particular file. ie: if i erased the header from one area, the corresponding body will be erased also.
problem with file chooser   (180 Views)
Hi all, just got a small query regarding JFileChooser. i want the user to restrict only to select .jar files . so i used JFileChooser fileChooser = new JFileChooser("Select a jar file..."); JarFilter1 jFilter = new JarFilter1( "jar", "Only Jars" ); fileChooser.setFileFilter(jFilter); FileFilter allfileFilter = fileChooser.getAcceptFileFilter(); fileChooser.removeChoosableFileFilter(allfileFilter); The jarFilter is just like this public class JarFilter1 extends FileFilter { String m_desc = null; String m_ext = null; public JarFilter1(String m_ext, String m_desc) { this.m_ext = m_ext; this.m_desc = m_desc; } public boolean accept ( File f ) { if ( f == null ) return false; if ( f.isDirectory () ) return true; return f.getName().toLowerCase().endsWith(m_ext); } public String getDescription () { return m_desc; } } int returnVal = fileChooser.showOpenDialog(this); it shows only directories and jar files, that is fine.. but when i type sample.class or *.class in the filename text box of the dialog, *.class filter gets added to the combo box, so i can select the class file and press ok. and this file is returned back to me.. but i dont want the user to get out of the open dialog until he selects a .jar file...could you please let me know how could this be possible
JSTL tag library problem.   (165 Views)
I am not able to run a jsp page which has some JSTL code . I am using sun one web server 6.1.While running it always complains about some appsolute url problem.I had included taglib ective in the web.xml too.
Cursor problem when moving around the frames   (181 Views)
This is the problem which can be easily solvable. But, I'm not getting right point to look into it. When I set the cursor to busy state on one of the frames in my application under process of a task, I move the cursor out of this frame and take back again into this. Here my cursor is changed to default cursor( which I should get after completing my task process). After a few seconds it again goes to busy state. Finally after my task is completed it comes to normal state which is expected. I wonder why the cursor is changing to normal state and again to busy state after I move it into the frame. How this problem be solved Please help me into this.
Application path problem   (208 Views)
Hi , I'm having a problem with file paths. Basically, if you launch the application in Windows by double-clicking an associated file, the application seems to take the path as that of the file, not the actual application. If I load the application normally, it takes the correct path. To illustrate: /application/myexe.exe /application/myimage.jpg double clicking myexe.exe loads the image fine because I use: File file = new File(""); file.getAbsolutePath() + File.separator + "myimage.jpg"; but if I load the application by double-clicking a file: /desktop/file.txt file.getAbsolutePath() returns /desktop, not /application. So it can't find the image file then because it thinks it should be at /desktop. Is there any way to get around this
JTable Cell data validation/blank cell problem   (199 Views)
I am fairly new to Swings. I have a JTable that has to do some validations before its data is saved: (1) Each row of the Table allows values within a set range ex:0.5 to 100 (2) The cell may allow blank (later replaced before save with the lower range value) cell data will be Float data. My questions: (a) Right now I am iterating through JTable cells and checking each row-wise cell to see if they are within range. What is the correct way to do such validations (b) JTable by default is not allowing me to leave the cell blank (the focus remains on the cell if I try to leave it blank). How can I allow blank cell entries (c) If user enters an invalid data (say a String) in the cell that expects Float value, the text stays in the cell even though I clear the TableModel and repopulate the data. Any idea how to get over this [ October 07, 2004: Message edited by: Yash Sharma ]
Table Row Selection problem while adding any Image in a JTable   (256 Views)
I am adding an Image in JTable public class BrowserLabelCellRenderer extends AbstractCellEditor implements TableCellRenderer, TableCellEditor,ActionListener
problem in executing swing application   (190 Views)
hello i'm facing a strange problem while ruuning a swing applet program. my program is compiling alright, but wenevr i mtrying to run it from command prompt, it's showing the following exception:: "Exception in thread"main" java.lang.NoSuchMethodError: main" even in netbeans ide it's showing the same thing where m i going wrong
JTable inside JScrollPane - background coloring problem   (228 Views)
I have a situation with a table that's narrower and shorter than the enclosing scroll pane's viewport, and column auto-resizing is turned off, so there's empty space below and to the right of the table. I'd like to fill the empty space with a single background color. I can fill in the bottom using scrollPane.setBackground(), and I can set most of the right side using scrollPane.getViewport().setBackground(). But I'm still left with an uncolored strip to the right of the table's column headers. I've tried using setBackground on the scroll pane's enclosing panel, and also tried using scrollPane.setColumnHeaderView() to force a new colored JPanel, but neither method has worked. Is there any way to fill in that strip right of the table's column headers Below is the code I'm using, a slight variation of from Oracle's Swing Example set.
Display problem in JFrame   (171 Views)
I am developing on application in swing. I want to display some big data on JFrame. If I display a big string on frame, it does not go to next line when it ends at the current line as it works on pixel. What is the solution for this. How people display data generatlly. In my case I have 5 fields. something like key value. but value is big string. Please help on this.
JEditorPane HTML parsing problem with about CSS   (215 Views)
my I have a problem about JEditorPane html source. When I read html source to my editor it changes html source. How can make it unchangable or what is the reason of problem There is parsing problem style='font-size:11.0pt;font-family:"Palatino Linotype"' changes to font face="Palatino Linotype" size="11.0pt". My input HTML: JEditorPane Test Test
Printing invisible JTable containing JTables - problem   (196 Views)
I am trying to print an invisivle JTable that contains inner JTables (nested). The outer JTable prints as it should, but for some reason the inner JTables header is never printed, even though everything else of the inner JTables is printed as it should, and that is where the problem is. I have tried everything I can think of without solving it. I would be happy if someone could help me with this. Thatnks in advance for any help. In my code the table is made visible after it is printed to show what it should be like. Here's my example code: import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.print.PrinterException; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; public class TestNestedJTable2 extends JFrame{ private static final long serialVersionUID = -722808327091366767L; private JTable mainTable; private JTable leftTable; private JTable rightTable; private Object[][] tableList; private Container container; private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"}; private Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)}, {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)}, {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}, }; private String[] columnNames2 = {"", "Last Name", "Group", "Year"}; private Object[][] data2 = { {false, "Li", "Tiger", new Integer(1997), }, {false, "Roy", "Lion", new Integer(1996)}, {false, "Lee", "Dragon", new Integer(1989)}, {false, "Jones", "Lion", new Integer(1981)}, {false, "Lam", "Dragon", new Integer(1980)}, }; private String[] names = {"sdf", "sdf", "dfs"}; public TestNestedJTable2(){ container = this.getContentPane(); leftTable = new JTable(data, columnNames); rightTable = new JTable(data2, columnNames2); leftTable.getTableHeader().setVisible(true); rightTable.getTableHeader().setVisible(true); leftTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); leftTable.setSize(leftTable.getPreferredSize()); JTableHeader header = leftTable.getTableHeader(); header.setSize(header.getPreferredSize()); rightTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); rightTable.setSize(rightTable.getPreferredSize()); header = rightTable.getTableHeader(); header.setSize(header.getPreferredSize()); tableList = new Object[1][]; tableList[0] = new Object[3]; tableList[0][0] = leftTable; tableList[0][1] = rightTable; tableList[0][2] = "dfgfdg"; mainTable = new JTable(new DefaultTableModel(tableList, names)); TableColumn tc = mainTable.getColumnModel().getColumn(0); tc.setCellRenderer(new CustomTableCellRenderer(leftTable)); tc = mainTable.getColumnModel().getColumn(1); tc.setCellRenderer(new CustomTableCellRenderer(rightTable)); mainTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); DefaultTableColumnModel colModel = (DefaultTableColumnModel) mainTable.getColumnModel(); TableColumn col = colModel.getColumn(0); col.setPreferredWidth(leftTable.getSize().width + 2); col.setWidth(leftTable.getSize().width + 2); col = colModel.getColumn(1); col.setPreferredWidth(rightTable.getSize().width + 2); col.setWidth(rightTable.getSize().width + 2); mainTable.setRowHeight(leftTable.getPreferredSize().height+leftTable.getTableHeader().getPreferredSize().height+1); mainTable.setMinimumSize(mainTable.getPreferredSize()); mainTable.setSize(mainTable.getPreferredSize()); header = mainTable.getTableHeader(); header.setSize(header.getPreferredSize()); try { mainTable.print(JTable.PrintMode.FIT_WIDTH); } catch (PrinterException e) { // TODO Auto-generated catch block e.printStackTrace(); } container.add(new JScrollPane(mainTable)); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setSize(800,800); setVisible(true); } class CustomTableCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 4415155875184525824L; JTable table; CustomTableCellRenderer(JTable table){ this.table=table; this.table.setOpaque(true); this.table.setAlignmentY(JTable.LEFT_ALIGNMENT); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { this.table=(JTable)value; this.table.setPreferredScrollableViewportSize(this.table.getSize()); JScrollPane jCrollPane = new JScrollPane(this.table); jCrollPane.setBorder(BorderFactory.createEmptyBorder()); jCrollPane.getViewport().setSize(new Dimension(this.table.getSize().width-1, this.table.getSize().height+16)); return jCrollPane; } } /** * @param args */ public static void main(String[] args) { new TestNestedJTable2(); } }
Facing problems printing a ScrolledComponent in SWT   (464 Views)
Hi , I am facing problems printing a ScrolledComponent in SWT . I am able to print the contents that are visible but not able to print the contents below the scroll . This happens for both vertical and horizontal scroll . Can some one please suggest how to proceed .
Animation problem with swing   (180 Views)
I'm trying to create an applet of a rain storm. i've already have the program working, pretty much. the only problem that i have is... well let me explain it this way: RainDrop is the class that has the methods to draw the raindrop to the screen, move it down the screen, and destroy it when it reaches the bottom of the frame. (Note: if you want 20 raindrops on the screen, you need 20 instances of RainDrop by the way i have it setup.) each instance of RainDrop implements Runnable. the run methods of each class will paint a blue oval to the screen, move the coordinates down, then call repaint(). this paints to an image, ALL instances of raindrop paint to one image, then the call to paint well paints that image onto the frame, double buffering it. the problem i'm having is the stupid Thread system in java. here's an example of what i mean: 2 instances of raindrop are in the part of the thread sequence where it paints the raindrop to the screen. well, at the same time, another instance of raindrop is executing the command to draw a rectangle the size of the screen, to cover up the other traces of the left behinds raindrop images, making the raindrops look animated. what i'm basically getting at is that because of this system, the final result is that the raindrops flicker all the way down the screen, and i'm pretty sure that sun has created a class or a method that i have not seen yet that will take care of this problem. PLEASE HELP!!!
Interdepenent JSpinners problem   (182 Views)
I have two JSpinner which represent the width and the height of an image. These values can be manipulated freely unless "Maintain ratio" checkbox is selected. Then, when e.g. width changes, the height value is changed accordingly automatically using the previously calculated size ratio for the image. This little program represents the idea (I hard-coded the size ratio): import java.awt.FlowLayout; import javax.swing.*; import javax.swing.event.*; public class SpinnerTest extends JFrame{ JSpinner widthSpinner = new JSpinner(); JSpinner heightSpinner = new JSpinner(); JCheckBox ratioBox = new JCheckBox("MaintainRatio"); double ratio = 0.85; public SpinnerTest() { setLayout(new FlowLayout()); getContentPane().add(ratioBox); getContentPane().add(widthSpinner); getContentPane().add(heightSpinner); widthSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if(ratioBox.isSelected()){ Integer width = (Integer) widthSpinner.getValue(); int w = width.intValue(); heightSpinner.setValue((int)(w/ratio)); } } }); heightSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if(ratioBox.isSelected()){ Integer height = (Integer) heightSpinner.getValue(); int h = height.intValue(); widthSpinner.setValue((int)(h*ratio)); } } }); } public static void main(String[] args) { SpinnerTest frame = new SpinnerTest(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.setSize(300, 200); frame.setLocationRelativeTo( null ); frame.setVisible(true); } }
Cardlayout problem   (184 Views)
wow its a long time since i wrote a message here (or worked on my project at all) but i decided enough was enough i need to set aside some time to work on it. so i have done and i have run into a brick all after about an hour my problem is to do with the show() class in the cardlayout. Im hoping i've cut my code down enough for you (it still shows the same error) import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class Main { public static JPanel passwordPanel(){ JPanel passwordPanel = new JPanel(); JLabel test = new JLabel("hoping this works"); passwordPanel.add(test); return passwordPanel; } public static JPanel encryptionPanel(){ JPanel encryptionPanel = new JPanel(); JLabel test = new JLabel("test"); encryptionPanel.add(test); return encryptionPanel; } public static JPanel selectToolPanel() { final JPanel selectToolPanel = new JPanel(); LayoutManager lay = new BoxLayout(selectToolPanel, BoxLayout.PAGE_AXIS); selectToolPanel.setLayout(lay); class pageSwitch implements ActionListener { public void actionPerformed(ActionEvent select) { CardLayout cl = (CardLayout)(masterToolPanel().getLayout());, select.getActionCommand()); } } JButton test = new JButton("TEST"); JButton test2 = new JButton("TEST2 has a different size"); test.addActionListener(new pageSwitch()); test2.addActionListener(new pageSwitch()); selectToolPanel.add(test); selectToolPanel.add(Box.createRigidArea(new Dimension(0,10))); selectToolPanel.add(test2); return selectToolPanel; } public static JPanel masterToolPanel(){ final JPanel switchPanel = new JPanel(); switchPanel.setLayout(new CardLayout()); JPanel card1 = passwordPanel(); JPanel card2 = encryptionPanel(); switchPanel.add(card1, "TEST"); switchPanel.add(card2, "TEST2 has a different size"); return switchPanel; } public static JPanel masterLayout() { JPanel masterPanel = new JPanel(); LayoutManager lay = new BorderLayout(); masterPanel.setLayout(lay); masterPanel.add(masterToolPanel(), BorderLayout.CENTER); masterPanel.add(selectToolPanel(), BorderLayout.WEST); return masterPanel; } public static void centerScreen(JFrame frame){ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); int x = ge.getMaximumWindowBounds().width; int y = ge.getMaximumWindowBounds().height; frame.setSize(Math.min(x, 800), Math.min(y, 500)); frame.setLocation((x - frame.getWidth()) / 2,(y - frame.getHeight()) / 2); } public static void createAndShowGUI(){ JFrame frame = new JFrame("Hacking Utility"); frame.add(masterLayout()); frame.setResizable(false); centerScreen(frame); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
container Repaint problem   (219 Views)
In my application i am using the same window and change the components at various button events using remove(),revalidate() and repaint(). in this code i am i have three different methods 1. initialWindow() 2. actionPerformed() in SubmitHandler class (inner class to SCJPTestApplication class) 3. actionPerformed() in BeginTest class (inner class to SCJPTestApplication class) the initialWindow () method displays the initial window which asks the user to select and submit the chapter from which he/she expects the test. On clicking the submit button on the initial window the actionPerformed method in the SubmitHandler listener class is invoked which removes the current components, revalidates, adds new components (a button called "Begin Test" and a label showing the chapter name selected for the test). DURING THE RUN THE PROGRAM WORKS PERFECTCLY TILL THIS POINT. Clicking the "Begin Test" button calls the actionPerformed() in the BeginTest class which removes the current components, adds new ones (a non-editable JTextpane holding the current question, few radiobuttons for options, and the submit button) and repaints the JPanel holding the components. The problem is that the window does not get Repainted. I have put several println() statemnts to check on the console if this actionPerformed method in the BeginTest class is executing. On the console it shows complete execution of the actionPerformed method. but the window is not repainted. I dont know why below given is the code. /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package testWindow; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextPane; import javax.swing.SwingUtilities; /** * * @author hp */ public class SCJPTestApplication { private JFrame window; Container content; private JLabel qString; private JPanel question; private JButton submit; private JRadioButton op; private JList chlist; private JTextPane qPane; private String chapterSelected; private SCJPTestGenerator tg; private int qIndex; SCJPTestApplication(){ tg = new SCJPTestGenerator(); } void initialWindow(){ System.out.println("Initial Window"); window = new JFrame("SCJP 1.5 Test"); window.setBounds(100,100, 400,300); content = window.getContentPane(); String topics[]=tg.generateTopicList(); chlist = new JList(topics); submit = new JButton("Submit"); question = new JPanel(); question.add(new JLabel("Please Select the Chapter")); question.add(chlist); question.add(submit); content.add(question); submit.addActionListener(new SubmitHandler()); window.setVisible(true); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } class SubmitHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ System.out.println("Submit Window"); chapterSelected = (String)chlist.getSelectedValue(); question.remove(); question.revalidate(); question.add(new JLabel(chapterSelected)); submit.setText("Begin Test"); question.add(submit); submit.addActionListener(new BeginTest()); question.repaint(); } } class BeginTest implements ActionListener{ ArrayList test ; Question q; BeginTest(){ test = tg.generateChapterTest(chapterSelected); qPane = new JTextPane(); } public void actionPerformed(ActionEvent e){ question.remove(); question.revalidate(); if(qIndex
Caps Action problem   (173 Views)
i've this swing aplication that has a label inside a jPanel; i want this label to get enabled if caps lock is on some code i'm using: //invoked inside aplication constructor capsAction = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { JPanel rodape = (PanelRodape)e.getSource(); JLabel labelCaps = (JLabel)rodape.getComponent(0); Toolkit toolkit = Toolkit.getDefaultToolkit(); labelCaps.setEnabled(toolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK)); } }; //some code for panel creation:(rodape is the panel containing the label) rodape.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(CAPS_LOCK), CAPS_SELECCIONADO);// CAPS_SELECCIONADO means "clicked" rodape.getActionMap().put(CAPS_SELECCIONADO, capsAction);