SEARCH YOUR SOLUTION HERE  

Problem in printing JTable values

Dear Friends,
I have to print the JTable values (on paper using print dialogue box).
I'm using jtableObj.print to print the table values. But jtableObj.print takes more time to print the table values because it prints the values as a image(approximately 5 mins to print 10 pages).

My code is ,

boolean complete = tableObj.print(mode, header, footer, showPrintDialog, null, interactive, null);

Posted On: Wednesday 17th of October 2012 10:00:13 PM Total Views:  530
View Complete with Replies




Related Messages:

problem in attached file .   (209 Views)
Help me out in solving 1 error in my code: /* please run this code and try to sort out the error.*/ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; import java.util.Enumeration; import java.util.zip.*; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Zip extends JPanel implements ActionListener { JButton button1, button2, button3; JFileChooser chooser; String choosertitle; JTextField field1, field2; //private int BUFFER; static final int BUFFER = 2048; public Zip() { this.setLayout(null); button1 = new JButton("Browse"); button2 = new JButton("Browse"); button3 = new JButton("Zip"); field1 = new JTextField(); field2 = new JTextField(); field1.setBounds(30, 50, 200, 25); button1.setBounds(240, 50, 100, 25); this.add(field1); this.add(button1); field2.setBounds(30, 150, 200, 25); button2.setBounds(240, 150, 100, 25); this.add(field2); this.add(button2); button1.addActionListener(this); add(button1); button2.addActionListener(this); add(button2); button3.setBounds(30, 200, 90, 25); this.add(button3); button3.addActionListener(this); add(button3); button1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { button1actionPerformed(e); } }); button2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { button2ActionPerformed(e); } }); button3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { button3ActionPerformed(e); } }); } public void unzip(String argv){ try { BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(argv); Enumeration e = zipfile.entries(); while(e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); System.out.println("Extracting: " +entry); is = new BufferedInputStream (zipfile.getInputStream(entry)); int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); is.close(); } } catch(Exception e) { e.printStackTrace(); } } public void button2ActionPerformed(java.awt.event.ActionEvent e) { int result; /* Chooser frame=new Chooser(); field2.setText(frame.fileName1);*/ chooser = new JFileChooser(); //chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle(choosertitle); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // // disable the " files" option. // chooser.setAcceptFileFilterUsed(false); // if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); field2.setText(chooser.getSelectedFile().toString()); } else { System.out.println("No Selection "); } } public void button1actionPerformed(java.awt.event.ActionEvent e) { int result; /* Chooser frame=new Chooser(); field2.setText(frame.fileName1);*/ chooser = new JFileChooser(); //chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle(choosertitle); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // // disable the " files" option. // chooser.setAcceptFileFilterUsed(false); // if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); field1.setText(chooser.getSelectedFile().toString()); } else { System.out.println("No Selection "); } } public void button3ActionPerformed(java.awt.event.ActionEvent evt) { this.zip (field1.getText()) ; } /* private void zip(String argv[]) { try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("c.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); //out.setMethod(ZipOutputStream.DEFLATED); byte data[] = new byte[BUFFER]; // get a list of files from current directory File f = new File("."); String files[] = f.list(); for (int i=0; i
getting a problem ,can't see the button   (200 Views)
hi , i was testing out card layout. What i want in my application is three panels At first i want the frame to be Divided into two panels and then add buttons on it . This is where the problem is coming. The button is not visible on the panel . It is visible when i remove the second panel . Another question is that can i control the size of the button on it here's the full code : import java.awt.event.*; import java.awt.*; public class CardLayoutEg extends Frame { public static void main(String... args) { CardLayoutEg cd=new CardLayoutEg(); cd.setVisible(true); } private Panel p1,first,second,third; Button b1; CardLayoutEg() { setSize(700,800); p1=new Panel(); Checkbox c1=new Checkbox("wierd"); b1=new Button("next"); b1.setBounds(40,50,200,100); p1=new Panel(); p1.setLayout(null); first=new Panel(); second=new Panel(); third=new Panel(); first.add(c1); first.add(b1); b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CardLayout c=(CardLayout)p1.getLayout(); c.next(p1); } }); p1.setSize(700,600); third.setSize(700,200); p1.setLayout(new CardLayout()); p1.add(first,"1"); p1.add(second,"2"); first.setBackground(Color.green); second.setBackground(Color.red); add(p1); add(third); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
Scroll panel problems   (223 Views)
I am having alot of problems getting this scroll panel to work. Specifically I have the [panel on my GUI, but I cant figure out how to get the text area to populate it. Can someone please tell me what I a,m doing wrong here. These are the code portions that pertain to the scroll panel only. private JTextArea jtextarea1;//define textarea private JScrollPane scrollpane1;
if statement problem   (206 Views)
I am new to Java Scripting and I am trying to write some code or if statement for the following. I have 2 JButtons (one labeled btnAddTwo and one lableled btnSubOne) and one text field.I am trying to get the btnAddTwo to add 2 when I click it and the btnSubOne to subtract one from the total in the text field. I built my program in netbean as a gui frame. Everthing works except for my counting.
Printing invicible JTable with Column removed - JTable.PrintMode.FIT_WIDTH problem   (200 Views)
My JTable is a table with some columns including a checkbox column. When the user clicks on the print button, the program will create an invisible copy of the visible table, then add a rowsorter to exclude all the rows with a checkbox that is set to false. then remove the checkbox column from the table. For the table to print I manually change the size of the table (else the content will not print). That is how I set up the table, I hope it made sense. But it is when I set the table to print with JTable.PrintMode.FIT_WIDTH thats not working as it should. The table is not printed across the whole page, like it still believes that the removed column is still there, resulting in that the rigthmost column will be cut, and not all data will be printed. I don't have this problem when printing JTable.PrintMode.NORMAL. I hope my explanation made sense. I have tried a long time to fix this but without result. I'd be gratefull if someone could help me. Here is the code. edit: I have removed the code till someone who knows tells me it is okay (see the two posts below).
Tricky JTextArea problem   (220 Views)
I have a JTextArea (or more than one) inside a JScrollPane The JScrollPane, has VERTICAL_SCROLLING_AS_NEEDED, no horizontal scrolling. When the frame is resized the scrollpane resizes accordingly. My problem is: Suppose I have 1000 words of text to put into the JTextArea. If I squash the frame horizontally, the words wrap around which is fine, and vertically, the scrollbar kicks in. But I just want to display 3 lines of text, and always finish with three dots ... when there is more text, but no room for it. I used setPreferredSize on the JTextArea which makes sure I get three lines worth. But when I select the text, the left over text is still hidden below the 3 lines. I don't want to display this text, just use 3 dots... Can anyone help
thread problem   (266 Views)
In a swing application, when ok button is clicked, i want to new a class ScanCard (implements ScannerListener and PropertyChangeListener), and I want to wait till ScanCard is finished then doAction(), if like the code showed, the doAction() is performed before or during ScanCard runing, what should I do to achieve the purpose this.okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvt){ if (btnGroup.getSelection() == null) doSomething; else { dispose(); try { ScanCard scanCard = new ScanCard(); if (true) doAction(); }catch() {} } } });
problem drawOval() cant be found.   (239 Views)
I am trying out this tutorial to get this drawOval() to work but the compiler tells me that the drawOval cant be found. I triple checked that my initialization is in place, and I have imported the proper library to get it to work. So I am at a loss here. my code: import java.awt.*; import java.awt.Graphics; import javax.swing.*; import javax.swing.event.*; public class Oval_Sub extends JFrame { private JSlider slider; private drawOval myPanel; public void Oval_Sub() { super("the title"); myPanel = new drawOval(); myPanel.setBackGroundColor(Color.ORANGE); // SwingConstants.HORIZONTAL sets the slider to move left to right or vise versa // 0, 200 sets the min and max value the slider has on the appropriate ends slider = new JSlider(SwingConstants.HORIZONTAL, 0, 200, 10); // sets the ticks or hash marks on the slider to determine intervals in values // the argument 10 refers to setting a tick every 10 pixels slider.setMajorTickSpacing(10); slider.setPaintTicks(true); slider.addChangeListener( new ChangeListener() { public void StateChanged(ChangeEvent e) { // setD() comes from Oval.java // get the value from slider and pass it to setD() myPanel.setD(slider.getValue()); } } // end ChangeListener() ); // end addChangeListener(); add(slider, BorderLayout.SOUTH); add(myPanel, BorderLayout.CENTER); } }
interface updating problem   (228 Views)
Hi all, I am displaying image histograms on a user interface. Each histogram is represented by a class I wrote which extends JComponent. The painting is done the proper way through paintComponent and repaint() and it works great. In my GUI constructor, I display the histograms.. pane7.add(graphs[0]); pane7.add(graphs[1]); pane7.add(graphs[2]);
GUI Fluctuation problem in swing   (276 Views)
I have a dialogue in which i am entering values. After submit I am checking for duplicate values in database and if exist I am again creating the same dialogue. As it can happen many times. I want to continue with that code. So I have used while loop and I am checking the flag value which I get after calling action_insertok() See the code while (!result) { result=true; DialogFactory.showDialog(null, "Add Assessment Type", assessDialogPage, new ACTION_InsertOk(), true, true); }
JTable and data binding problem [please close, found solution]   (181 Views)
, I am using NetBeans 6.8 and got some problems when I want to add something to binded data. I have created a JTable (myListTable) that is binded with LinkedList (myList). I have created JButton (addRowButton) that should add new MyItem to myList which (probably) should add a row with that item to myListTable... and this is where the problem occurs. Firstly I have tried this:@Action public void addRow() { myList.add(new MyItem(myList.size(), "Random num: "+Math.random())); }
problem of MouseListener interface   (244 Views)
I'm developing a dialog for that I've written a class. In that class I've to implement an interface MouseListener but dont want to implement all method. but I have already extended one class JDialog. Is there any way to not to implement all method
JProgressbar problem!   (172 Views)
Hi Members, First of all thanks to Javaranch for providing this nice tutorial JProgressBar. This has almost solved my problem. I am not able to understand that how should I calculate and update my JProgessBar in case of reading long file and parse it accordingly. Each time the progress bar does not update immediately . I do not know how should I do
JTable printing problem   (568 Views)
I have sample of JTable with data that i would like to be right aligned, also orange background color cell renderer is applied, and font is set to be Tahoma BoldItalic with font size of 13. Problems that arise are, grid lines are over cell text, and also applied background color looks strange when PDF printer is used and document is zoomed. Interesting thing is that when font is set to be even grid lines doesn't intersect cell text. import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.JTable.PrintMode; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class TablePrintTest extends JFrame { private static final long serialVersionUID = 1L; private static final Object[] COLUMN_NAMES = { "Column1", "Column2", "Column3" }; private static final Object[][] CELL_VALUES = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; private JButton printButton; private JTable table; public TablePrintTest() { super("TablePrintTest"); createGui(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void createGui() { table = new JTable(new DefaultTableModel() { private static final long serialVersionUID = 1L; @Override public Class getColumnClass(int columnIndex) { return Number.class; } @Override public int getColumnCount() { return COLUMN_NAMES.length; } @Override public int getRowCount() { return CELL_VALUES.length; } @Override public String getColumnName(int column) { return COLUMN_NAMES[column].toString(); } @Override public Object getValueAt(int row, int column) { return CELL_VALUES[row][column]; } }); table.setDefaultRenderer(Number.class, new DefaultTableCellRenderer() { private static final long serialVersionUID = 1L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel) super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); label.setHorizontalAlignment(SwingConstants.RIGHT); return label; } public java.awt.Color getBackground() { return Color.orange; }; }); table.setFont(new Font("Tahoma", Font.ITALIC | Font.BOLD, 13)); printButton = new JButton("Print"); printButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Printable printable = table.getPrintable(PrintMode.NORMAL, null, null); PrinterJob pJob = PrinterJob.getPrinterJob(); pJob.setPrintable(printable); if (pJob.printDialog()) { try { pJob.print(); } catch (PrinterException e1) { e1.printStackTrace(); } } } }); JPanel contentPane = new JPanel(new BorderLayout()); contentPane.add(printButton, BorderLayout.NORTH); contentPane.add(new JScrollPane(table), BorderLayout.CENTER); setContentPane(contentPane); pack(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TablePrintTest().setVisible(true); } }); } }
wriring code for an EDITOR big problem??   (139 Views)
i am developing code for an editor like tool. as we work in some IDE`S like eclipse or netbeans or even any editor like edit plus or notepad++ etc. whenever we write any keyword for specified language that keyword changes it`s attributes eg change in color etc.. i`ve tried my best to do that but it`s not working.... here is the code for that stuff .. actually m is an object for frame and t is JTextPane associated with it it changes the color of selected text but after updating caret the text changes again it`s color.. import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.text.rtf.*; public class EditorPane extends JTextPane implements CaretListener,KeyListener { private String[] KEY_WORDS={"class","public","void","static"}; String str=""; Font f; Mymenu m; protected RTFEditorKit m_kit; static int count=0; static int edit=0; EditorPane() { } EditorPane(Mymenu m,String text) { super(); this.setText(text); this.m_kit=new RTFEditorKit(); this.m=m; //this.setEditorKit(this.m_kit); JScrollPane ps = new JScrollPane(this); //m.getContentPane().add(ps, BorderLayout.CENTER); m.getContentPane().add(ps); //not working,,... this.str=this.getText(); f=new Font("Dialog",Font.PLAIN,15); setFont(f); this.addCaretListener(this); this.addKeyListener(this); repaint(); } public void caretUpdate(CaretEvent ce) { int i=this.getCaretPosition(); if(i>0) { count=i; } } String[] parse(String text) { String[] tokens=text.split("\\s"); return tokens; } public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } public void keyTyped(KeyEvent ke) { char c=ke.getKeyChar(); ke.getKeyLocation(); Thread thread=new Thread(){ public void run() { EditorPane obj=new EditorPane(); try { String text=m.t.getText(); String[] tokens=obj.parse(text); int i=0; for(String tok:tokens) { int j=i; i=i+tok.length(); for(String KEY_WORD:obj.KEY_WORDS) { if(tok.equals(KEY_WORD)) { int caret=m.t.getCaretPosition(); m.t.select(j, i+1); System.out.println(m.t.getSelectedText()); //Font f=new Font(Font.DIALOG,Font.BOLD,20); m.t.setSelectedTextColor(Color.RED); } } } } catch(Exception ex) { ex.printStackTrace(); } } }; if(c==' ') thread.start(); } }
problem with displaying dynamic list in Jpanel   (196 Views)
i added a dynamic list which displays the items starts with the string entered in the Jtextfield i was able to display the list properly but when the list is clicked if there is underlying focusable object like Jtextfield list is not selected. some strange error i'm getting i have attached the screenshot of what actually happened.i'm new to swings so finding difficult to fix the bugs..please help me. private void jTextField_itemTypeKeyReleased(java.awt.event.KeyEvent evt) { try { // TODO add your handling code here: ItemMaster itemMaster = new ItemMaster(); int iCount = itemMaster.getItemNamesCount(jTextField_itemType.getText()); if (iCount == 0) { if (jList1 == null) { return; } jList1.remove(); jList1.setVisible(false); jList1.setVisibleRowCount(iCount); return; } else { strItemNamesList = new String[iCount][2]; } String[] strDisplayList = new String[iCount]; System.out.println("icount :" + iCount); strItemNamesList = itemMaster.getItemNames(jTextField_itemType.getText()); System.out.println("string text :" + jTextField_itemType.getText()); for (int iLoopIndex = 0; iLoopIndex < iCount; iLoopIndex++) { strDisplayList[iLoopIndex] = strItemNamesList[iLoopIndex][1]; System.out.println(strDisplayList[iLoopIndex]); } if (jList1 != null) { remove(jList1); System.out.println("removed"); repaint(); } //this is the popuplist class defined by me jList1 = new PopUpList(strDisplayList); jList1.setOpaque(true); ilistXpos = jTextField_itemType.getX(); MDIApplication.jTextField_selected = jTextField_itemType; iListYpos = jTextField_itemType.getY() + jTextField_itemType.getHeight(); add(jList1); jList1.setBounds(ilistXpos, iListYpos, jTextField_itemType.getWidth(), iCount * 20); System.out.println("x pos:" + ilistXpos + " ypos :" + iListYpos); jList1.setVisible(true); jList1.setRequestFocusEnabled(true); validate(); } catch (SQLException ex) { Logger.getLogger(addItem.class.getName()).log(Level.SEVERE, null, ex); } } this is the popuplist class /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package UI; import java.awt.Container; import javax.swing.JList; import javax.swing.event.ListSelectionEvent; /** * * @author Administrator */ public class PopUpList extends JList { public PopUpList(String strDisplayList[]) { remove(); setListData(strDisplayList); addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { jList1ValueChanged(evt); } }); } public void jList1ValueChanged(ListSelectionEvent evt) { MDIApplication.jTextField_selected.setText((String)getSelectedValue()); Container parent=getParent(); parent.remove(this); parent.repaint(); } }
Boolean problem   (167 Views)
I'm implementing a login form, with two inputs, allowing a maximum of 3 tries for authentication; username and password. Scanner class reads input from notepad, and matches it with input from user. However, without a boolean statement, the program will search every line for a match until file ends, displaying every error message until match is found. For example, if the username/password combination is on the 5th line, it will display 4 error messages (invalid username/password) before allowing the user to login. Once boolean statements in the code are implemented, it matches the username/password combination immediately. However, the error message for wrong combination of username/password does not work anymore. Can anyone please help check if the boolean statement is done properly Code is as below. public void actionPerformed(ActionEvent o){ try{ String value1 = text1.getText(); String value2 = text2.getText(); File file = new File("name.txt"); Scanner input = new Scanner(file); boolean ok = false; int i = 1; while(input.hasNext()){ String user = input.next(); String password = input.next(); if((ok==false) && (i!=4)){ if(user.equals(value1) && password.equals(value2)){ NextPage page = new NextPage(); page.setVisible(true); JLabel label = new JLabel("Welcome :"+ value1); page.getContentPane().add(label); break; } else if((ok!=false) && (i!=4)){ i++; JOptionPane.showMessageDialog(this, "Incorrect username or password. Please re-enter username and password", "Error", JOptionPane.ERROR_MESSAGE); continue; } else if((ok==false)&&(i==4)){ System.exit(0); } } }input.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, e.getMessage()); } } }
JSplitPane problem   (150 Views)
; I'm creating a GUI where I have a JFrame which has a JSplitPane that works as a divider between a JDesktopPane on one side and JTextArea on the other side. The problem is that I'm using the JDesktopPane side to: 1- Add new "JInternalFrames" 2- Draw some "graphics" When I try to resize the JSplitPane. My JDesktopPane is repainted which undo all the changes I made in it. For example, I moved several JInternalFrames and then I resized the JSplitPane and that made my JInternalFrames go back to their initial locations. How can I avoid this In other words, How can I cancel the effect of resizing JSplitPane on the contents of my JDesktopPane
problem with gui   (147 Views)
hi, i am trying to design a monitoring system for my university. i have several files but i have only listed the files that i am having problem. during the process of coding, i was trying to show a panel a scrollpane which was a success. the jscrollpane is in a jframe. this jpanel has a jbutton. on clicking the button it should load a another panel into the scrollpane but it does not. how ever if i make a object of the main frame and then add to the jscrollpane and then show this frame it shows the jscrollpane with the new jpanel. but there is a problem. now i have 2 jframe showing. how do i get rid of the original jframe or just show one jframe with the new jpanel in it code is as under :--- main jframe ------------- package System_Monitor; import java.awt.*; import java.sql.*; import java.text.*; import java.util.Date; import java.util.TimeZone; import java.util.logging.*; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JOptionPane; public class main1 extends JFrame { private String s=null; private int a=0; private Graphics g; private JMenuItem jMenuItem12; /** Creates new form main */ public main1() throws SQLException { this.setTitle(" Patient Monitoring System "); // this.setDefaultCloseOperation(main1.DO_NOTHING_ON_CLOSE); ///////////// database String c = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } // defining the location of the driver and the database String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}"; Connection cont; try { cont = DriverManager.getConnection(url, "", ""); } catch (SQLException ex) { Logger.getLogger(newrecord.class.getName()).log(Level.SEVERE, null, ex); } Statement stmt; try { Class.forName("myDriver.ClassName"); } catch(java.lang.ClassNotFoundException ev) { } PreparedStatement pstmt; Connection con; try { con = DriverManager.getConnection(url,"", ""); Connection contt=DriverManager.getConnection(url,"", ""); ResultSet rset; stmt=con.createStatement(); String query="Select * from SYSTEM WHERE ACTIVE='yes'"; rset=stmt.executeQuery(query); c=rset.getString(7); System.out.println(c); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println("SQLException: " +" 1 " +ex.getMessage()); } ///////date and time TimeZone tz = TimeZone.getTimeZone("Europe/London"); DateFormat df = DateFormat.getInstance(); df.setTimeZone(tz); Date now = new Date(); String nowStr = df.format(now); ///////////////// label2 = new java.awt.Label(); label1 = new java.awt.Label(); label4 = new java.awt.Label(); // label3 = new java.awt.Label(); label5 = new java.awt.Label(); scrollPane1 = new java.awt.ScrollPane(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu7 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenu8 = new javax.swing.JMenu(); jMenuItem8 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem6 = new javax.swing.JMenuItem(); jMenuItem7 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenuItem9 = new javax.swing.JMenuItem(); jMenu4 = new javax.swing.JMenu(); jMenuItem10 = new javax.swing.JMenuItem(); jMenu5 = new javax.swing.JMenu(); jMenu6 = new javax.swing.JMenu(); jMenuItem11 = new javax.swing.JMenuItem(); jMenuItem12 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setAlwaysOnTop(true); setBounds(new java.awt.Rectangle(0, 0, 600, 600)); ////////////////////////////////////////////////////////////////////////////// /////// login name ///////// Login1 l1=new Login1(); //label2.setText(rset1.getString("NAME")); label1.setText("Logged in as "+c); ////////////////////////////////////////////////////////////////////////////////// label4.setText(nowStr); label5.setAlignment(java.awt.Label.CENTER); label5.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N scrollPane1.setEnabled(false); jMenu1.setText("Patients"); jMenu7.setText("Admit"); jMenuItem1.setText("New"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu7.add(jMenuItem1); jMenuItem2.setText("Open"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu7.add(jMenuItem2); jMenuItem3.setText("Edit"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { jMenuItem3ActionPerformed(evt); } catch (SQLException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } } }); jMenu7.add(jMenuItem3); jMenu1.add(jMenu7); jMenu8.setText("Discharge"); jMenuItem8.setText("Discharge"); jMenuItem8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem8ActionPerformed(evt); } }); jMenu8.add(jMenuItem8); jMenu1.add(jMenu8); jMenuItem5.setText("View"); jMenu1.add(jMenuItem5); jMenuItem4.setText("Print"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu1.add(jMenuItem4); jMenuBar1.add(jMenu1); jMenu2.setText("Ward"); jMenuItem6.setText("View"); jMenuItem6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { jMenuItem6ActionPerformed(evt); } catch (SQLException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } } }); jMenu2.add(jMenuItem6); jMenuItem7.setText("Monitor"); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem7ActionPerformed(evt); } }); jMenu2.add(jMenuItem7); jMenuBar1.add(jMenu2); jMenu3.setText("Contacts"); jMenu3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu3ActionPerformed(evt); } }); jMenuItem9.setText("Contacts"); jMenuItem9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem9ActionPerformed(evt); } }); jMenu3.add(jMenuItem9); jMenuBar1.add(jMenu3); jMenu4.setText("Settings"); jMenuItem10.setText("Set Defaults"); jMenuItem10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem10ActionPerformed(evt); } }); jMenu4.add(jMenuItem10); jMenuBar1.add(jMenu4); jMenu5.setText("Help"); jMenu5.add(jMenuItem12); jMenuItem12.setText("Help Section"); jMenuItem12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { jMenuItem12ActionPerformed(e); } }); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { jMenuItem5ActionPerformed(evt); } catch (SQLException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } } }); jMenuBar1.add(jMenu5); jMenu6.setText("Sign Out"); jMenu6.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jMenu6ComponentShown(evt); } }); jMenu6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu6ActionPerformed(evt); } }); jMenuItem11.setText("Log Out"); jMenuItem11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem11ActionPerformed(evt); } }); jMenu6.add(jMenuItem11); jMenuBar1.add(jMenu6); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(398, 398, 398) .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) ) .addGroup(layout.createSequentialGroup() .addComponent(scrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(167, 167, 167) .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(125, 125, 125)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(scrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); setLabel2text(); pack(); }// public void setLabel2text() { Login1 log; log=new Login1(); String f=null; f=log.Username(); label2.setText(f); } private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { label5.setText(" New Patient Record "); r=new newrecord(); scrollPane1.setVisible(true); scrollPane1.setEnabled(true); scrollPane1.add(r); r.show(true); } private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) { open op; op=new open();// TODO add your handling code here: op.show(true); op.setFocusable(true); scrollPane1.remove(); label5.setText(" Patients Record "); scrollPane1.add(op); scrollPane1.setVisible(true); scrollPane1.setEnabled(true); } private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) { } private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) throws SQLException, ClassNotFoundException { label5.setText(" Edit Patients Records "); // patients/view item DFEdit factory = new DFEdit("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}", "",""); QFEdit fr=new QFEdit(factory); scrollPane1.add(fr); scrollPane1.setEnabled(true); JOptionPane.showMessageDialog(this," Double click and enter the new value for a patient..."); } private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) { PrintUtilities.printComponent(scrollPane1); this.toBack(); } private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) throws SQLException, ClassNotFoundException { label5.setText(" Patients Records "); // patients/view item DataFactory factory = new DataFactory("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}", "",""); QueryFrame fr=new QueryFrame(factory); scrollPane1.add(fr); scrollPane1.setEnabled(true); } private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) throws SQLException, ClassNotFoundException { label5.setText(" View Wards "); // patients/view item DataFactory factory = new DataFactory("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}", "",""); WardQuery wq=new WardQuery(factory); scrollPane1.add(wq); scrollPane1.setEnabled(true); } private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) { label5.setText("Monitor Patient In A Ward"); MonitMenu mm=new MonitMenu(); scrollPane1.setVisible(true); scrollPane1.setEnabled(true); scrollPane1.add(mm); scrollPane1.setFocusable(true); mm.show(true); } private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) { label5.setText("Discharge Patient Form"); scrollPane1.setEnabled(true); Discharge dsc=new Discharge(); scrollPane1.add(dsc); scrollPane1.isEnabled(); scrollPane1.setEnabled(true); scrollPane1.setVisible(true); scrollPane1.setFocusable(true); } public void SetScrollPane() { scrollPane1.setEnabled(false); } private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) { Contacts c; c=new Contacts(); // TODO add your handling code here: label5.setText(" Contacts "); scrollPane1.repaint(); scrollPane1.setVisible(true); scrollPane1.setEnabled(true); scrollPane1.add(c); c.show(true);// TODO add your handling code here: } private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) { Setting sett; sett=new Setting();// TODO add your handling code here: label5.setText(" Set Default Sensor Settings "); scrollPane1.repaint(); scrollPane1.setVisible(true); scrollPane1.setEnabled(true); scrollPane1.add(sett); } private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) { label5.setText("Help Section"); Help lp=new Help(); scrollPane1.add(lp); scrollPane1.show(true); } private void jMenu6ActionPerformed(java.awt.event.ActionEvent evt) { } private void jMenu6ComponentShown(java.awt.event.ComponentEvent evt) { // TODO add your handling code here: } private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) { Logout lout; lout=new Logout(); lout.show(true);// TODO add your handling code here: // TODO add your handling code here: lout.setFocusable(true); lout.setFocusableWindowState(true); this.toBack(); } @SuppressWarnings("static-access") public void ShowWardDetails() throws ClassNotFoundException, SQLException // this method shows the details query of a ward with all patients { ///////////////////////////////////////////// try { // Class.forName("org.apache.derby.jdbc.ClientDrive"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } // defining the location of the driver and the database String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}"; Connection cont; try { cont = DriverManager.getConnection(url, "", ""); } catch (SQLException ex) { Logger.getLogger(newrecord.class.getName()).log(Level.SEVERE, null, ex); } Statement stmt; try { Class.forName("myDriver.ClassName"); } catch(java.lang.ClassNotFoundException ev) { } Connection con; try { con = DriverManager.getConnection(url,"", ""); ResultSet rset; stmt=con.createStatement(); String query="Select * from WARD"; rset=stmt.executeQuery(query); rset.next(); s=rset.getString(1); PreparedStatement pst=con.prepareStatement("Delete from WARD WHERE NAME='"+s+"'"); //pst.setString(1, s); pst.executeUpdate(); this.setVisible(false); // this.add(rc); // this.show(true); this.show(false); // execute method to execute the query // stmt.executeUpdate(); System.out.println(" Successful Opening of Record"); stmt.close(); pst.close(); con.close(); } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } //////////////////////////////////////////////////////// DataFactory factory = new DataFactory("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}", "",""); Monitor fr=new Monitor(factory,s); this.show(false); // this.hide(); // this.setVisible(false); // this.scrollPane1.add(fr); // this.label5.setText(" Monitor Patient In A Ward"); // scrollPane1.add(fr); // scrollPane1.repaint(); //label5.setText(" Monitoring Patient in a Ward"); main1 m=new main1(); m.show(false); m.show(); m.setVisible(true); m.scrollPane1.add(fr); m.label5.setText(" Monitor Patients In A Ward "); } public void showpat(String astring[]) { Rcontents v; v=new Rcontents(); label5.setText(" Patients Record"); repaint(); scrollPane1.setVisible(true); scrollPane1.setEnabled(true); v.setfield1(astring[0]); v.setfield2(astring[1]); v.setfield3(astring[2]); v.setfield4(astring[3]); v.setfield5(astring[4]); v.setfield6(astring[5]); v.setfield7(astring[6]); v.setfield8(astring[7]); v.setfield9(astring[8]); v.setfield10(astring[9]); v.setfield11(astring[10]); v.setfield12(astring[10]); v.setfield13(astring[12]); v.setfield14(astring[13]); v.setfield15(astring[14]); v.setfield16(astring[15]); v.setfield17(astring[16]); v.setfield18(astring[17]); scrollPane1.add(v); v.show(true); System.out.println(" Values Added to the screen"); } // MAIN FUNCTION public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { new main1().setVisible(true); } catch (SQLException ex) { Logger.getLogger(main1.class.getName()).log(Level.SEVERE, null, ex); } } }); } /////////////// this is the method for the username /////// /* public void LSet() { String c = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(CreateRecord.class.getName()).log(Level.SEVERE, null, ex); } // defining the location of the driver and the database String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}"; Connection cont; try { cont = DriverManager.getConnection(url, "", ""); } catch (SQLException ex) { Logger.getLogger(newrecord.class.getName()).log(Level.SEVERE, null, ex); } Statement stmt; try { Class.forName("myDriver.ClassName"); } catch(java.lang.ClassNotFoundException ev) { } PreparedStatement pstmt; Connection con; try { con = DriverManager.getConnection(url,"", ""); Connection contt=DriverManager.getConnection(url,"", ""); ResultSet rset; stmt=con.createStatement(); String query="Select * from SYSTEM WHERE ACTIVE='yes'"; rset=stmt.executeQuery(query); c=rset.getString(7); System.out.println(c); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println("SQLException: " +" 1 " +ex.getMessage()); } this.label1.setText("Logged in as "+c); } */ // Variables declaration - do not modify private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu5; private javax.swing.JMenu jMenu6; private javax.swing.JMenu jMenu7; private javax.swing.JMenu jMenu8; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem10; private javax.swing.JMenuItem jMenuItem11; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItem6; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JMenuItem jMenuItem8; private javax.swing.JMenuItem jMenuItem9; private java.awt.Label label1; private java.awt.Label label2; private java.awt.Label label3; private java.awt.Label label4; private java.awt.Label label5; private java.awt.ScrollPane scrollPane1; // End of variables declaration private newrecord r; } ////////////////// the 1st jpanel file ------------------------- package System_Monitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JPanel; public class MonitMenu extends JPanel implements ActionListener { private Connection con; private String s; /** Creates new form MonitMenu */ public MonitMenu() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel1.setText("Enter The Ward Number To View Details"); jButton1.setText("View"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 68, Short.MAX_VALUE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(49, 49, 49)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(67, 67, 67) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(114, 114, 114) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(42, Short.MAX_VALUE)) ); }// private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { this.setEnabled(true); this.setVisible(true); try { factory = new DataFactory("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}", "", ""); } catch (ClassNotFoundException ex) { Logger.getLogger(MonitMenu.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(MonitMenu.class.getName()).log(Level.SEVERE, null, ex); } ///////////////////////////////////////////////////////////////////////////// try { System.out.println(" Check 1"); // Class.forName("org.apache.derby.jdbc.ClientDrive"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(CreateRecord.class.getName()).log(Level.SEVERE, null, ex); } // defining the location of the driver and the database String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}"; Connection cont; try { cont = DriverManager.getConnection(url, "", ""); } catch (SQLException ex) { Logger.getLogger(newrecord.class.getName()).log(Level.SEVERE, null, ex); } PreparedStatement stmt; try { Class.forName("myDriver.ClassName"); } catch(java.lang.ClassNotFoundException ev) { } try { con = DriverManager.getConnection(url,"", ""); /* stmt = con.createStatement(); stmt.executeUpdate(createString); */ stmt=con.prepareStatement("insert into WARD values()"); stmt.setString(1,jTextField1.getText()); // execute method to execute the query stmt.executeUpdate(); System.out.println(" Successful Insertion of data"); stmt.close(); con.close(); this.show(false); this.setVisible(false); this.hide(); stmt.close(); /* try { // WMonitor wm = new WMonitor(); // this.add(wm); } catch (ClassNotFoundException ex) { Logger.getLogger(MonitMenu.class.getName()).log(Level.SEVERE, null, ex); } */ main1 ns=new main1(); try { ns.ShowWardDetails(); } catch (ClassNotFoundException ex) { Logger.getLogger(MonitMenu.class.getName()).log(Level.SEVERE, null, ex); } } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } ////////////////////////////////////////////////////////////////////////// /* Monitor mon=new Monitor(factory); mon.WNum(jTextField1.getText()); mon.displayQueryResults("Select NAME,DATE_OF_BIRTH,ADMIT_DATE,WARD_NUMBER, SYMTOMS,MEDICATION,COMMENTS From Records Where WARD_NUMBER='"+jTextField1.getText()+"'"); this.remove(jButton1); this.remove(jLabel1); this.remove(jTextField1); this.validate(); this.add(mon); */ } DataFactory factory; // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JTextField jTextField1; // End of variables declaration public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } } //////////////////////////////////////////////// 2nd jpanel ----------------------------- package System_Monitor; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; public class WMonitor extends JFrame { private String s; WMonitor() throws SQLException, ClassNotFoundException { try { // Class.forName("org.apache.derby.jdbc.ClientDrive"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(WMonitor.class.getName()).log(Level.SEVERE, null, ex); } // defining the location of the driver and the database String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}"; Connection cont; try { cont = DriverManager.getConnection(url, "", ""); } catch (SQLException ex) { Logger.getLogger(newrecord.class.getName()).log(Level.SEVERE, null, ex); } Statement stmt; try { Class.forName("myDriver.ClassName"); } catch(java.lang.ClassNotFoundException ev) { } Connection con; try { con = DriverManager.getConnection(url,"", ""); /* stmt = con.createStatement(); stmt.executeUpdate(createString); */ Rcontents rc; rc=new Rcontents(); ResultSet rset; stmt=con.createStatement(); String query="Select * from WARD"; rset=stmt.executeQuery(query); rset.next(); s=rset.getString(1); PreparedStatement pst=con.prepareStatement("Delete from WARD WHERE NAME='"+s+"'"); //pst.setString(1, s); pst.executeUpdate(); // execute method to execute the query // stmt.executeUpdate(); System.out.println(" Successful Opening of Record"); stmt.close(); pst.close(); con.close(); } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } //////////////////////////////////////////////////////// DataFactory factory = new DataFactory("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}", "",""); Monitor fr=new Monitor(factory,s); this.add(fr); this.show(); } } //////////////////////////// other files required with the project package System_Monitor; import javax.swing.*; import java.awt.*; import java.sql.SQLException; public class Monitor extends JPanel { DataFactory factory; // A factory to obtain our table data JTextField query; // A field to enter a query in JTable table; // The table for displaying data JButton msgline; // For displaying messages String wn=null; /** * This constructor method creates a simple GUI and hooks up an event * listener that updates the table when the user enters a new query. **/ public Monitor(DataFactory f,String astring) { this.factory = f; table = new JTable(); // Displays the table msgline = new JButton(); // Displays messages msgline.setText("Click To View Records"); this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); this.add(new JScrollPane(table)); displayQueryResults("Select NAME,DATE_OF_BIRTH,ADMIT_DATE,WARD_NUMBER, SYMTOMS,MEDICATION,COMMENTS From Records Where WARD_NUMBER='"+astring+"'"); } public void displayQueryResults(final String q) { EventQueue.invokeLater(new Runnable() { public void run() { try { table.setModel(factory.getData(q)); } catch (SQLException ex) { JOptionPane.showMessageDialog(Monitor.this,new String[] { ex.getClass().getName() + ": ", ex.getMessage() }); } } }); } public void WNum(String astring) { wn=astring; } public static void main(String args[]) throws Exception { // Create the factory object that holds the database connection using // the data specified on the command line DataFactory factory = new DataFactory("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}", "",""); //String a = null; // Create a QueryFrame component that uses the factory object. Monitor qf = new Monitor(factory,args[1]); // Set the size of the QueryFrame, then pop it up qf.setSize(400,550); qf.setVisible(true); } } //////////////// package System_Monitor; import javax.swing.*; import java.awt.*; import java.sql.SQLException; public class Monitor extends JPanel { DataFactory factory; // A factory to obtain our table data JTextField query; // A field to enter a query in JTable table; // The table for displaying data JButton msgline; // For displaying messages String wn=null; /** * This constructor method creates a simple GUI and hooks up an event * listener that updates the table when the user enters a new query. **/ public Monitor(DataFactory f,String astring) { this.factory = f; table = new JTable(); // Displays the table msgline = new JButton(); // Displays messages msgline.setText("Click To View Records"); this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); this.add(new JScrollPane(table)); displayQueryResults("Select NAME,DATE_OF_BIRTH,ADMIT_DATE,WARD_NUMBER, SYMTOMS,MEDICATION,COMMENTS From Records Where WARD_NUMBER='"+astring+"'"); } public void displayQueryResults(final String q) { EventQueue.invokeLater(new Runnable() { public void run() { try { table.setModel(factory.getData(q)); } catch (SQLException ex) { JOptionPane.showMessageDialog(Monitor.this,new String[] { ex.getClass().getName() + ": ", ex.getMessage() }); } } }); } public void WNum(String astring) { wn=astring; } public static void main(String args[]) throws Exception { // Create the factory object that holds the database connection using // the data specified on the command line DataFactory factory = new DataFactory("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Records.mdb;}", "",""); //String a = null; // Create a QueryFrame component that uses the factory object. Monitor qf = new Monitor(factory,args[1]); // Set the size of the QueryFrame, then pop it up qf.setSize(400,550); qf.setVisible(true); } } ///////////////////// package System_Monitor; import java.sql.*; import javax.swing.table.*; import javax.swing.event.*; public class Data implements TableModel { ResultSet results; // The ResultSet to interpret ResultSetMetaData metadata; // Additional information about the results int numcols, numrows; // How many rows and columns in the table /** * This constructor creates a TableModel from a ResultSet. It is package * private because it is only intended to be used by * DataFactory, which is what you should use to obtain a * Data **/ Data(ResultSet results) throws SQLException { this.results = results; // Save the results metadata = results.getMetaData(); // Get metadata on them numcols = metadata.getColumnCount(); // How many columns results.last(); // Move to last row numrows = results.getRow(); // How many rows } /** * Call this when done with the table model. It closes the ResultSet and * the Statement object used to create it. **/ public void close() { try { results.getStatement().close(); } catch(SQLException e) {}; } /** Automatically close when we're garbage collected */ protected void finalize() { close(); } // These two TableModel methods return the size of the table public int getColumnCount() { return numcols; } public int getRowCount() { return numrows; } // This TableModel method returns columns names from the ResultSetMetaData public String getColumnName(int column) { try { return metadata.getColumnLabel(column+1); } catch (SQLException e) { return e.toString(); } } // This TableModel method specifies the data type for each column. // We could map SQL types to Java types, but for this example, we'll just // convert all the returned data to strings. public Class getColumnClass(int column) { return String.class; } /** * This is the key method of TableModel: it returns the value at each cell * of the table. We use strings in this case. If anything goes wrong, we * return the exception as a string, so it will be displayed in the table. * Note that SQL row and column numbers start at 1, but TableModel column * numbers start at 0. **/ public Object getValueAt(int row, int column) { try { results.absolute(row+1); // Go to the specified row Object o = results.getObject(column+1); // Get value of the column if (o == null) return null; else return o.toString(); // Convert it to a string } catch (SQLException e) { return e.toString(); } } // Our table isn't editable public boolean isCellEditable(int row, int column) { return false; } // Since its not editable, we don't need to implement these methods public void setValueAt(Object value, int row, int column) {} public void addTableModelListener(TableModelListener l) {} public void removeTableModelListener(TableModelListener l) {} } /////////////
JTable setMinimumSize problem   (151 Views)
I have a JTable, which will auto-adjust its column widths based on the data in the cells. And to make this work I have to turn auto resize off by calling table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); The table sits in a JPanel with certain width. The problem is that with auto_resize_off, when initially there is no data in the table or when the data in the grid is not long enough, the table will not expand across the entire width of the JPanel. So there is an empty gap between the right-end of the table and the right edge of the JPanel. So I tried to do table.setMinimumSize(new Dimension(MyJPanelWidth, whateverHeight)) to make the initial width of the table same as that of the JPanel. But it does not work! Nothing gets changed for the table width. However, table.setPreferredSize will change the table width, but my table will not auto-expand its columns, which does not serve my purpose either. So my question is -- how do I set the initial/minimum table width without impacting its ability to auto-adjust its columns based on data Any advice is much appreciated!