ava Microsoft Access Database Interrogator import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.sql.*; import java.util.*; import javax.swing.table.*; public class AccessApp extends JFrame implements ActionListener { private JPanel panel = new JPanel(); private Container container = this.getContentPane(); private JList jList = new JList(); private JScrollPane jScrollPane = new JScrollPane(jList); private JFileChooser jfChooser = new JFileChooser(); private File dbFile = null; private DefaultTableModel model = new CustomerDefaultTableModel(); private JTable jTable = new JTable(model); private JScrollPane jSjTable = new JScrollPane(jTable); private JMenuBar menu = new JMenuBar(); private JMenu mnuFile = new JMenu("File"); private JMenuItem miOpen = new JMenuItem("Open"); private JMenuItem mExit = new JMenuItem("Exit"); private Vector tableNames = new Vector(); private String dbFileName = ""; private Connection connection = null; private boolean firstRun = true; private chooser mChooser = new chooser(); String dbUrl = ""; public AccessApp() { jScrollPane.getViewport().setView(jList); jScrollPane.setPreferredSize(new Dimension(100,403)); panel.add(jScrollPane); panel.add(jSjTable);
container.setLayout(new BorderLayout()); this.setContentPane(container); container.add(panel); jList.setFixedCellWidth(100); jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.setJMenuBar(menu); menu.add(mnuFile); mnuFile.add(miOpen); mnuFile.add(mExit); //Mouse listener for the table jList. MouseListener mouseListener = new MouseAdapter() { //The mouse listener for the click of the jList items. public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if (( jTable.getColumnCount() > 0 ) '' ( firstRun )) { while(jTable.getColumnCount() != 0 ) { removeColumn(jTable, 0); } Object index = jList.getSelectedValue(); displayTableData(index.toString()); firstRun = false; } } } }; //Window listener. this.addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { jList.setListData((tableNames)); jList.setSelectedIndex(tableNames.size()-1); } } );
//listeners. jList.addMouseListener(mouseListener); mExit.addActionListener(this); miOpen.addActionListener(this); //JFrame specific stuff. this.setTitle("Access Database Interrogation"); this.setBounds(150, 150, 580, 460); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setResizable(false); this.setVisible(true); } //The button listener actions. public void actionPerformed(ActionEvent e) { if ( e.getSource() == mExit ) { int opt = JOptionPane.showConfirmDialog(null, "Fo' real?", "Quit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if ( opt == 0 ) { System.exit(0); } } else if ( e.getSource() == miOpen ) { jfChooser.setFileFilter(mChooser); int result = jfChooser.showOpenDialog(this); if ( result == JFileChooser.APPROVE_OPTION ) { dbFile = jfChooser.getSelectedFile(); //Just test that its a normal file. if ( dbFile.isFile() ) { displayTableNames(); } } } } //This is executed when the user double clicks a table name in the jList. All the data //in that table, is printed out in the jTable.
public void displayTableData(String tableName) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection(dbUrl); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * from " + tableName); ResultSetMetaData rsmd = resultSet.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); for ( int i = 1; i < numberOfColumns + 1; i++ ) { Statement statement1 = connection.createStatement(); ResultSet resultSet1 = statement1.executeQuery("SELECT " + rsmd.getColumnName(i) + " from " + tableName); Vector store = new Vector(); while(resultSet1.next()) { store.addElement(resultSet1.getString(rsmd.getColumnName(i)).toString()); } model.addColumn(rsmd.getColumnName(i), store); } model.fireTableStructureChanged(); } catch(NullPointerException ex) { //This is being thrown occasionally, I'll fix it soon :) } catch(Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.OK_OPTION); } } // Loads up all the table names in the database, and prints them into the JList. public void displayTableNames() { dbFileName = dbFile.getAbsolutePath(); String[] types = {"TABLE"};
dbUrl = "jdbc:odbc:Driver= {Microsoft Access Driver (*.mdb)};DBQ="+dbFileName.trim()+";}"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection(dbUrl); DatabaseMetaData dbmd = connection.getMetaData(); ResultSet resultSet = dbmd.getTables(null, null, "%", types); while ( resultSet.next() ) { tableNames.addElement(resultSet.getString(3)); } } catch(Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.OK_OPTION); } } public static void main(String args[]) { AccessApp newInstance = new AccessApp(); } //Executed when the user clicks a table name, and if there is data in the jTable, this //removes it. public void removeColumn(JTable table, int vColIndex) { CustomerDefaultTableModel model = (CustomerDefaultTableModel) table.getModel(); TableColumn col = table.getColumnModel().getColumn(vColIndex); int columnModelIndex = col.getModelIndex(); Vector dataVector = model.getDataVector(); Vector colIds = model.getColumnIdentifiers(); table.removeColumn(col); colIds.removeElementAt(columnModelIndex); for (int i = 0; i < dataVector.size(); i++) { Vector row = (Vector)dataVector.get(i); row.removeElementAt(columnModelIndex); }
model.setDataVector(dataVector, colIds); Enumeration eNum = table.getColumnModel().getColumns(); for (; eNum.hasMoreElements(); ) { TableColumn column = (TableColumn) eNum.nextElement(); if (column.getModelIndex() >= columnModelIndex) { column.setModelIndex(column.getModelIndex() - 1); } } model.fireTableStructureChanged(); } class CustomerDefaultTableModel extends DefaultTableModel { public Vector getColumnIdentifiers() { return columnIdentifiers; } } /* * This class is the chooser class to make it so that only certiain files * with certain extensions are seen. */ class chooser extends javax.swing.filechooser.FileFilter { public boolean accept(File file) { String filename = file.getName(); //Enables that only jpegs and gifs are only returned. return filename.endsWith(".mdb")''file.isDirectory(); } public String getDescription() { return "*.mdb"; } } }
Greet on basis of Time.. Ex, say good morning when its morning package greeting; import java.awt.*; import java.util.*; public class Greeting extends Canvas { private final static int XPAD = 10; private final static int YPAD = 10; private String morning, afternoon, evening; private boolean border; public Greeting() { morning = "Good morning"; afternoon = "Good afternoon"; evening = "Good evening"; border = true; } public String getMorning() { return morning; } public void setMorning(String morning) { this.morning = morning; adjustSize(); } public String getAfternoon() { return afternoon; } public void setAfternoon(String afternoon) { this.afternoon = afternoon; adjustSize(); } public String getEvening() { return evening; } public void setEvening(String evening) { this.evening = evening; adjustSize(); }
public boolean getBorder() { return border; } public void setBorder(boolean border) { this.border = border; repaint(); } public void setFont(Font font) { super.setFont(font); adjustSize(); } public Dimension getPreferredSize() { Graphics g = getGraphics(); FontMetrics fm = g.getFontMetrics(); int w = fm.stringWidth(selectGreeting()) + 2*XPAD; int h = fm.getHeight() + 2*YPAD; return new Dimension(w, h); } private void adjustSize() { Dimension d = getPreferredSize(); setSize(d.width, d.height); Component parent = getParent(); if(parent != null) { parent.invalidate(); parent.doLayout(); } } public void paint(Graphics g) { String greeting = selectGreeting(); Dimension d = getSize(); FontMetrics fm = g.getFontMetrics(); int x = (d.width - fm.stringWidth(greeting))/2; int y = (d.height + fm.getMaxAscent() fm.getMaxDescent())/2; g.drawString(greeting, x, y); if(border) { g.drawRect(0, 0, d.width - 1, d.height - 1); } }
private String selectGreeting() { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); if(hour < 12) { return morning; } else if(hour < 19) { return afternoon; } else { return evening; } } } Reminder code in Thread import java.util.Timer; import java.util.TimerTask; /** * Simple demo that uses java.util.Timer to schedule a task to execute once 5 * seconds have passed. */ /** * */ public class Reminder { Timer timer; /** * * @param seconds */ public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds * 1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); timer.cancel(); //Terminate the timer thread } }
/** * * @param args */ public static void main(String args[]) { System.out.println("About to schedule task. for 5 Seconds"); new Reminder(5); System.out.println("Task scheduled."); } } timer for various time zones import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; public class TimerTest { public static void main(String[] args) { JFrame f = new TimerTestFrame(); f.show(); } } class TimerTestFrame extends JFrame { public TimerTestFrame() { setSize(450, 300); setTitle("TimerTest"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); Container c = getContentPane(); c.setLayout(new GridLayout(2, 3)); c.add(new ClockCanvas("San Jose", "GMT-8")); c.add(new ClockCanvas("Taipei", "GMT+8")); c.add(new ClockCanvas("Berlin", "GMT+1")); c.add(new ClockCanvas("New York", "GMT-5")); c.add(new ClockCanvas("Cairo", "GMT+2")); c.add(new ClockCanvas("Bombay", "GMT+5")); }
} interface TimerListener { void timeElapsed(Timer t); } class Timer extends Thread { public Timer(int i, TimerListener t) { target = t; interval = i; setDaemon(true); } public void run() { try { while (!interrupted()) { sleep(interval); target.timeElapsed(this); } } catch(InterruptedException e) {} } private TimerListener target; private int interval; } class ClockCanvas extends JPanel implements TimerListener { public ClockCanvas(String c, String tz) { city = c; calendar = new GregorianCalendar(TimeZone.getTimeZone(tz)); Timer t = new Timer(1000, this); t.start(); setSize(125, 125); } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawOval(0, 0, 100, 100); double hourAngle = 2 * Math.PI * (seconds - 3 * 60 * 60) / (12 * 60 * 60); double minuteAngle = 2 * Math.PI * (seconds - 15 * 60) / (60 * 60); double secondAngle = 2 * Math.PI * (seconds - 15) / 60;
g.drawLine(50, 50, 50 + (int)(30 * Math.cos(hourAngle)), 50 + (int)(30 * Math.sin(hourAngle))); g.drawLine(50, 50, 50 + (int)(40 * Math.cos(minuteAngle)), 50 + (int)(40 * Math.sin(minuteAngle))); g.drawLine(50, 50, 50 + (int)(45 * Math.cos(secondAngle)), 50 + (int)(45 * Math.sin(secondAngle))); g.drawString(city, 0, 115); } public void timeElapsed(Timer t) { calendar.setTime(new Date()); seconds = calendar.get(Calendar.HOUR) * 60 * 60 + calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.SECOND); repaint(); } private int seconds = 0; private String city; private int offset; private GregorianCalendar calendar; private final int LOCAL = 16; }