JDO database and Java Swing
Was just wundering if it is possible to query a java jdo database with a swing frontend, and if so if anybody can direct me to any helpful websites.
Cheers
Sure it is possible.
Do you know JDO? Googling for "JDO tutorial" should get you well on your way. Ditto for Swing / Swing tutorial.
Keep the database stuff and the GUI stuff in separate classes. That way you can write quickie command line main() functions to test a database method. Or, as you advance, you may want to learn about jUnit (->google).
There are application architecture issues that are mucho difficult to guess at without more details. Such as if your application is pretty big, you might want to look into some sort of client/server distributed architecture. But for simpler stuff, a single application should be a fine way to start.
Similar Messages
-
Are JFC Swing and java Swing both different?
Thanks.Nope. Swing is Swing.
http://java.sun.com/docs/books/tutorial/uiswing/14start/about.html -
PL/SQL and Java Swing interface
Everybody in this forum knows that Oracle is the best database around
with many functionalities, stability, performance, etc. We also know
that PL/SQL is a great language to manipulate information directly
in the database with many built in functions, OOP capability,
transaction control, among other features. Today an application that
manipulates information, which needs user interface, requires components
to be developed using different technologies and normally running in
different servers or machines. For example, the interface is done using
a dynamic HTML generator like JSP, PHP, PL/SQL Web Toolkit, etc.
This page is executed in an application server like Oracle iAS or
Tomcat, just to name two, which in turn access a database like Oracle to
build the HTML. Also rich clients like Java applets require an intermediate
server to access the database (through servlets for example) although
it is possible to access the database directly but with security issues.
Another problem with this is that complexity increases a lot, many
technologies, skills and places to maintain code which leads to a greater
failure probability. Also, an application is constantly evolving, new
calculations are added, new tables, changed columns. If you have an
application with product code for example and you need to increase its
size, you need to change it in the database, search for all occurrences
of it in the middle-tier code and perhaps adjust interfaces. Normally
there is no direct dependency among the tier components. On another
issue, many application interfaces today are based on HTML which doesn't
have interactive capabilities like rich-client interfaces. Although it
is possible to simulate many GUI widgets with JavaScript and DHTML, it is
far from the interactive level we can accomplish in rich clients like
Java Swing, Flash MX, Win32, etc. HTML is also a "tag-based" language
originally created to publish documents so even small pages require
many bytes to be transmitted, far beyond of what we see on the screen.
Even in fast networks you have a delay time to wait the page to be
loaded. Another issue, the database is in general the central location
for all kinds of data. Most applications relies on it for security,
transaction and availability. My proposal is to use Oracle as the
central location for interface, processing and data. With this approach
we can create not only the data manipulation procedures in the database,
but procedures that also control and manage user interfaces. Having
a Oracle database as the central location for all components has many
advantages:
- Unique point of maintenance, backup and restore
- Integrated database security
- One language for everything, PL/SQL or Java (even both if desired)
- Inherited database cache, transaction and processing optimizations
- Direct access to the database dictionary
- Application runs on Oracle which has support for many platforms.
- Transparent use of parallel processing, clusters and future
background technologies
Regarding the interface, I already created a Java applet renderer
which receives instructions from the database on how to create GUI
objects and how to respond to events. The applet is only 8kb and can
render any Swing or AWT object/event. The communication is done
through HTTP or HTTPS using Oracles's MOD_PLSQL included in the Apache
HTTP server which comes with the database or application server (iAS).
I am also creating a database framework and APIs in PL/SQL to
create and manipulate the client interface. The applet startup is
very fast because it is very small, you don't need to download large
classes with the client interface. Execution is done "on-demand"
according to instructions received from the database. The instructions
are very optimized in terms of network bandwidth and based on preliminary
tests it can be up to 1/10 of a similar HTML screen. Less network usage
means faster response and means that even low speed connections will
have a good performance (a future development can be to use this in
wireless devices like PDAs e even cell phones, just an idea for now).
The applet can also be executed standalone by using Java Web Start.
With this approach no business code, except the interface, is executed
on the client. This means that alterations in the application are
dynamically reflected in the client, no need to "re-download" the
application. Events are transmitted when required only so network
usage is minimized. It is also possible to establish triggering
events to further reduce network usage. Since the protocol used is
HTTP (which is stateless), the database framework I am creating will
be responsible to maintain the state of connections, variables, locks
and session information, so the developer don't need to worry about it.
The framework will have many layers, from communication up to
application so there will be pre-built functions to handle queries,
pagination, lock, mail, log, etc. The final objective is to have a
rich client application integrated into the database with minimum
programming and maintenance requirements, not forgetting customization
capabilities. Below is a very small example of what can de done. A
desktop with two windows, each window with two fields, a button with an
image to switch the values, and events to convert the typed text when
leaving the field or double-clicking it. The "leave" event also has an
optimization to only be triggered when the text changes. I am still
developing the framework and adjusting the renderer but I think that all
technical barriers were transposed by now. The framework is still in
the early stages, my guess is that only 5% is done so far. As a future
development even an IDE can be created so we have a graphical environment
do develop applications. I am willing to share this with the PL/SQL
community and listen to ideas and comments.
Example:
create or replace procedure demo1 (
jre_version in varchar2 := '1.4.2_01',
debug_info in varchar2 := 'false',
compress_buffer in varchar2 := 'false',
optimize_buffer in varchar2 := 'true'
) as
begin
interface.initialize('demo1_init','JGR Demo 1',jre_version,debug_info,compress_buffer,optimize_buffer);
end;
create or replace procedure demo1_init as
begin
toolkit.initialize;
toolkit.create_icon('icon',interface.global_root_url||'img/switch.gif');
toolkit.create_internal_frame('frame1','Frame 1',50,50,300,136);
toolkit.create_label('frame1label1','frame1',10,10,50,20,'Field 1');
toolkit.create_label('frame1label2','frame1',10,40,50,20,'Field 2');
toolkit.create_text_field('frame1field1','frame1',50,10,230,20,'Field 1','Field 1',focus_event=>true,mouse_event=>true);
toolkit.create_text_field('frame1field2','frame1',50,40,230,20,'Field 2','Field 2',focus_event=>true,mouse_event=>true);
toolkit.set_text_field_event('frame1field1',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 1','false');
toolkit.set_text_field_event('frame1field2',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 2','false');
toolkit.set_text_field_event('frame1field1',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 1','false');
toolkit.set_text_field_event('frame1field2',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 2','false');
toolkit.create_button('button1','frame1',10,70,100,25,'Switch','Switch the values of "Field 1" and "Field 2"','S','icon');
toolkit.set_button_event('button1',toolkit.action_performed_event,'demo1_switch_fields(''frame1field1'',''frame1field2'')','frame1field1:'||toolkit.get_text_method||',frame1field2:'||toolkit.get_text_method);
toolkit.create_internal_frame('frame2','Frame 2',100,100,300,136);
toolkit.create_label('frame2label1','frame2',10,10,50,20,'Field 1');
toolkit.create_label('frame2label2','frame2',10,40,50,20,'Field 2');
toolkit.create_text_field('frame2field1','frame2',50,10,230,20,'Field 1','Field 1',focus_event=>true,mouse_event=>true);
toolkit.create_text_field('frame2field2','frame2',50,40,230,20,'Field 2','Field 2',focus_event=>true,mouse_event=>true);
toolkit.set_text_field_event('frame2field1',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 1','false');
toolkit.set_text_field_event('frame2field2',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 2','false');
toolkit.set_text_field_event('frame2field1',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 1','false');
toolkit.set_text_field_event('frame2field2',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 2','false');
toolkit.create_button('button2','frame2',10,70,100,25,'Switch','Switch the values of "Field 1" and "Field 2"','S','icon');
toolkit.set_button_event('button2',toolkit.action_performed_event,'demo1_switch_fields(''frame2field1'',''frame2field2'')','frame2field1:'||toolkit.get_text_method||',frame2field2:'||toolkit.get_text_method);
end;
create or replace procedure demo1_set_upper as
begin
toolkit.set_string_method(interface.global_object_name,toolkit.set_text_method,upper(interface.array_event_value(1)));
toolkit.set_text_field_event(interface.global_object_name,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(1)),'false');
end;
create or replace procedure demo1_set_lower as
begin
toolkit.set_string_method(interface.global_object_name,toolkit.set_text_method,lower(interface.array_event_value(1)));
toolkit.set_text_field_event(interface.global_object_name,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(1)),'false');
end;
create or replace procedure demo1_switch_fields (
field1 in varchar2,
field2 in varchar2
) as
begin
toolkit.set_string_method(field1,toolkit.set_text_method,interface.array_event_value(2));
toolkit.set_string_method(field2,toolkit.set_text_method,interface.array_event_value(1));
toolkit.set_text_field_event(field1,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(2)),'false');
toolkit.set_text_field_event(field2,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(1)),'false');
toolkit.set_text_field_event(field1,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(2)),'false');
toolkit.set_text_field_event(field2,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(1)),'false');
end;Is it sound like Oracle Portal?
But you want to save a layer 9iAS.
Basically, that was the WebDB.(Oracle changed the name to Portal when version 3.0)
Over all, I agree with you.
>>Having a Oracle database as the central location for all components has many
>>advantages:
>>
>>- Unique point of maintenance, backup and restore
>>- Integrated database security
>>- One language for everything, PL/SQL or Java (even both if desired)
>>- Inherited database cache, transaction and processing optimizations
>>- Direct access to the database dictionary
>>- Application runs on Oracle which has support for many platforms.
>>- Transparent use of parallel processing, clusters and future
>>background technologies
I would like to build 'ZOPE' inside Oracle DB as a back-end
Using Flash MX as front-end.
Thomas Ku. -
What is difference between C# Gzip and Java swing GZIPOutputStream?
Hi All,
I have a Java swing tool where i can compress file inputs and we have C# tool.
I am using GZIPOutputStream to compress the stream .
I found the difference between C# and Java Gzip compression while a compressing a file (temp.gif ) -
After Compression of temp.gif file in C# - compressed file size increased
while in java i found a 2% percentage of compression of data.
Could you please tell me , can i achieve same output in Java as compared to C# using GZIPOutputStream ?
Thank a lot in advance.797957 wrote:
Does java provides a better compression than C#?no idea, i don't do c# programming. and, your question is most likely really: "does java default to a higher compression level than c#".
Btw what is faster compression vs. better compression?meaning, does the code spend more time/effort trying to compress the data (slower but better compression) or less time/effort trying to compress the data (faster but worse compression). most compression algorithms allow you to control this tradeoff depending on whether you care more about cpu time or disk/memory space. -
How to use java api while java programming especially using javase and java swing?
i need help for java api for undo, redo, htmleditorkit,editorkit.
in my project i have to use java swing for desktop application but, i need help for how to implement and how to retrieve java api.
please reply with example or code..i need help for java api for undo, redo, htmleditorkit,editorkit.
in my project i have to use java swing for desktop application but, i need help for how to implement and how to retrieve java api.
please reply with example or code..
You find examples and code by searching the internet, not by using forums.
Start with The Java Tutorials - it has trails for the bulk of the Java functionality.
See the trail 'How to Write an Undoable Edit Listener'
http://docs.oracle.com/javase/tutorial/uiswing/events/undoableeditlistener.html
You learn by DOING - not by reading. Actually DO the tutorial example and try to understand WHAT it does and HOW it does it.
Then search for other tutorial trails that are of interest. -
Java.io and java.swing help
i'm writing a program that write the byte representation of numbers and outputs them to a joptionpane window
it keeps telling me that void functions are not allowed
is there any way that i can use void functions in my output? or would i need to change to a method that returns a value?
here is my code, please help me, it will be greatly appreciated :)
GUI Part
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class zero2nineTest extends JFrame{
zero2nine show;
public static void main(String[] args){
zero2nineTest x = new zero2nineTest();
x.setVisible(true);
public zero2nineTest(){
super("File IO and Byte Representation Tests");
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
JButton readFile1 = new JButton("Create and Read 1st Byte Representations");
readFile1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
zero2nine.writeFile(out);
JOptionPane.showMessageDialog(
zero2nineTest.this,
"Odd numbers: " + zero2nine.readFile(), "Byte Representation of Odd Numbers",
JOptionPane.PLAIN_MESSAGE);
cp.add(readFile1);
JButton readFile2 = new JButton("Create and Read 2nd Byte Representations");
readFile1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
zero2nine.writeFile2(out);
JOptionPane.showMessageDialog(
zero2nineTest.this,
"Even numbers: " + zero2nine.readFile2(), "Byte Representation of Even Numbers",
JOptionPane.PLAIN_MESSAGE);
cp.add(readFile2);
JButton quit = new JButton("Quit Program");
quit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int decision;
decision = JOptionPane.showConfirmDialog(
null, "Are you sure?", "Are you sure?", JOptionPane.YES_NO_OPTION);
if(decision == 0){
System.exit(0);
cp.add(quit);
pack();
Class Part
import java.io.*;
class zero2nine{
static String fileName = "zero2nine.txt";
// public static void main(String[] args){
// try{
// FileOutputStream out = createFile();
// writeFile(out);
// writeFile2(out);
// readFile();
// readFile2();
// }catch(IOException io){
// System.out.println("closing program");
static FileOutputStream createFile() throws IOException{
File f = new File(fileName);
FileOutputStream out = new FileOutputStream(f);
return out;
static void writeFile(FileOutputStream out) throws IOException{
DataOutputStream ds = null;
try{
ds = new DataOutputStream(out);
int x = 0;
for(int i = 0; i < 10; i++){
x = i * i;
ds.writeInt(x);
}finally{
System.out.println("File written this far");
static void writeFile2(FileOutputStream out) throws IOException{
DataOutputStream ds = null;
try{
ds = new DataOutputStream(out);
int x = 0;
for(int i = 10; i < 20; i++){
x = i * i;
ds.writeInt(x);
}finally{
System.out.println("File written this far again");
public int readFile() throws IOException{
DataInputStream dataIn = null;
try{
FileInputStream in = new FileInputStream("zero2nine.txt");
dataIn = new DataInputStream(in);
//Output odd numbers
for(int i = 0; i < 10; i++){
if(dataIn.readInt() % 2 == 0){
int b = dataIn.readInt();
System.out.println(b);
}finally{
System.out.println("File read this far");
return(b);
static void readFile2() throws IOException{
DataInputStream dataIn = null;
try{
FileInputStream in = new FileInputStream("zero2nine.txt");
dataIn = new DataInputStream(in);
//Output even numbers
for(int i = 10; i < 20; i++){
if(dataIn.readInt() % 2 == 1){
int b = dataIn.readInt();
System.out.println(b);
}finally{
System.out.println("File read this far again");
}F:\Computer Science\Java\zero2nineTest.java:28: cannot resolve symbol
symbol: variable out
zero2nine.writeFile(out);
^
public void actionPerformed(ActionEvent e){
zero2nine.writeFile(out);
JOptionPane.showMessageDialog(
F:\Computer Science\Java\zero2nineTest.java:31: 'void' type not allowed here
"Odd numbers: " + zero2nine.readFile(), "Byte Representation of Odd Numbers",
^
zero2nineTest.this,
"Odd numbers: " + zero2nine.readFile(), "Byte Representation of Odd Numbers",
JOptionPane.PLAIN_MESSAGE);
F:\Computer Science\Java\zero2nineTest.java:41: cannot resolve symbol
symbol: variable out
zero2nine.writeFile2(out);
^
zero2nine.writeFile2(out);
JOptionPane.showMessageDialog(
zero2nineTest.this,
F:\Computer Science\Java\zero2nineTest.java:44: 'void' type not allowed here
"Even numbers: " + zero2nine.readFile2(), "Byte Representation of Even Numbers",
^
zero2nineTest.this,
"Even numbers: " + zero2nine.readFile2(), "Byte Representation of Even Numbers",
JOptionPane.PLAIN_MESSAGE);
4 errors
Tool completed with exit code 1 -
Is there a tool that automatic create a java class related to a database? Similar dataset in .NET?
create a database? nyet.
There are relational databases written in Java and there are tools in java with which one can access a DBMS.
Either use a search engine, look at the java.sql and javax.sql packages, or post more information. -
I am almost finished with this program, but I am getting a strange error. Here is the assignment description: http://condor.depaul.edu/~jpetlick/extra/212/A07_212.html I would greatly appreciate any help. Thank you! (I know I eventually need to output this to files, but I currently left that out for debugging purposes.)
-------------Error Message------------------------
The balance of accounts prior to money transfers is:
Account Balance
1 $10,000.00
2 $10,000.00
3 $10,000.00
4 $10,000.00
5 $10,000.00
6 $10,000.00
7 $10,000.00
8 $10,000.00
9 $10,000.00
10 $10,000.00
Total $100,000.00
TranID From Balance to Balance
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
-------------------Code----------------------
import java.sql.*;
import java.util.*;
import java.io.*;
import java.text.NumberFormat;
public class Transfer
public static void main(String[] args)
throws ClassNotFoundException, SQLException, IOException
String file = "Report.dat", file2 = "Log.dat", sql = "";
int sum = 0, trans = 1, accountWithdraw = 0, accountDeposit = 0, total = 0;
int randomAcctWithdraw = 0, randomAcctDepo = 0;
//-----Load database driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//-----File Writers
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
FileWriter fw2 = new FileWriter (file2);
BufferedWriter bw2 = new BufferedWriter (fw2);
PrintWriter outFile2 = new PrintWriter (bw2);
NumberFormat money = NumberFormat.getCurrencyInstance();
try
//-----Create Database Connection object.
Connection c = DriverManager.getConnection("jdbc:odbc:Banking");
//-----Create Statement object.
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
s.execute("CREATE TABLE MyBank " + "(AccountNum Number, Balance Number)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('1', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('2', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('3', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('4', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('5', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('6', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('7', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('8', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('9', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('10', 10000)");
String selection = "SELECT AccountNum, Balance FROM MyBank";
ResultSet r = s.executeQuery(selection);
System.out.println ("The balance of accounts prior to money transfers is:");
System.out.println ("\tAccount\t Balance");
while(r.next())
System.out.println("\t" + r.getInt(1) + "\t" + money.format(r.getInt(2)));
sum += r.getInt(2);
System.out.println("\tTotal\t" + money.format(sum));
System.out.println ("\nTranID\tFrom\tBalance\tto\tBalance");
r = s.executeQuery(selection);
r.first();
for (int i=0; i <= 1000; i++)
accountWithdraw = (int) ((Math.random() * 10) + 1);
accountDeposit = (int) ((Math.random() * 10) + 1);
r.first();
while(r.next())
while ( (accountWithdraw == r.getInt(1)) || (accountWithdraw == accountDeposit) )
accountWithdraw = (int) ((Math.random() * 10) + 1);
accountDeposit = (int) ((Math.random() * 10) + 1);
r.absolute(accountWithdraw);
s.executeUpdate("UPDATE MyBank SET Balance = " + (r.getInt(2) - 1000) + " WHERE AccountNum = " + accountWithdraw);
r = s.executeQuery(selection);
r.absolute(accountDeposit);
s.executeUpdate("UPDATE MyBank SET Balance = " + (r.getInt(2) + 1000) + " WHERE AccountNumber = " + accountDeposit);
System.out.print (trans + "\t" + accountWithdraw + "\t" + s.executeQuery("SELECT Balance FROM MyBank WHERE AccountNum = " + accountWithdraw) + "\t" + accountDeposit + "\t" + s.executeQuery("SELECT Balance FROM MyBank WHERE AccountNum = " + accountDeposit));
r.first();
trans++;
r.first();
System.out.println ("\nThe balance of accounts after money transfers is:");
System.out.println ("\tAccount\t Balance");
while (r.next())
System.out.println("\t" + r.getInt(1) + "\t" + money.format(r.getInt(2)));
total += r.getInt(2);
System.out.println ("\tTotal: " + money.format(total));
//-----Close Connections
c.close();
catch(SQLException err)
System.out.println (err);Well I changed some thing and it seems as if I'm so close but I keep getting this error. The wierd thing is it doesn't always break there. Sometimes it breaks at 14 transactions, sometimes 85, all kinds of numbers. I can't figure that out. Thanks for all the help, i appreciate it.
The balance of accounts prior to money transfers is:
Account Balance
1 $10,000.00
2 $10,000.00
3 $10,000.00
4 $10,000.00
5 $10,000.00
6 $10,000.00
7 $10,000.00
8 $10,000.00
9 $10,000.00
10 $10,000.00
Total $100,000.00
TranID From Balance to Balance
1 8 9000 6 11000
2 3 9000 9 11000
3 7 9000 8 10000
4 10 9000 9 12000
5 1 9000 9 13000
6 4 9000 8 11000
7 8 10000 6 12000
8 5 9000 9 14000
9 7 8000 2 11000
10 3 8000 9 15000
11 9 14000 2 12000
12 8 9000 10 10000
13 4 8000 3 9000
14 8 8000 10 11000
15 3 8000 2 13000
16 10 10000 9 15000
17 5 8000 7 9000
18 9 14000 1 10000
19 3 7000 5 9000
20 9 13000 3 8000
21 3 7000 8 9000
22 8 8000 6 13000
23 7 8000 2 14000
24 3 6000 4 9000
25 1 9000 5 10000
26 8 7000 1 10000
27 4 8000 5 11000
java.sql.SQLException: No data found
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:6287)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataInteger(JdbcOdbc.java:3211)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataInteger(JdbcOdbcResultSet.java:5434)
at sun.jdbc.odbc.JdbcOdbcResultSet.getInt(JdbcOdbcResultSet.java:571)
at Transfer.main(Transfer.java:76)
My altered code:
import java.sql.*;
import java.util.*;
import java.io.*;
import java.text.NumberFormat;
public class Transfer
public static void main(String[] args)
throws ClassNotFoundException, SQLException, IOException
String file = "Report.dat", file2 = "Log.dat", sql = "";
int sum = 0, trans = 1, accountWithdraw = 0, accountDeposit = 0, total = 0;
//-----Load database driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//-----File Writers
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
FileWriter fw2 = new FileWriter (file2);
BufferedWriter bw2 = new BufferedWriter (fw2);
PrintWriter outFile2 = new PrintWriter (bw2);
NumberFormat money = NumberFormat.getCurrencyInstance();
try
//-----Create Database Connection object.
Connection c = DriverManager.getConnection("jdbc:odbc:Banking");
//-----Create Statement object.
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
s.execute("CREATE TABLE MyBank " + "(AccountNum Number, Balance Number)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(1, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(2, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(3, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(4, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(5, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(6, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(7, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(8, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(9, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(10, 10000)");
String selection = "SELECT AccountNum, Balance FROM MyBank";
ResultSet r = s.executeQuery(selection);
System.out.println ("The balance of accounts prior to money transfers is:");
System.out.println ("\tAccount\t Balance");
while(r.next())
System.out.println("\t" + r.getInt(1) + "\t" + money.format(r.getInt(2)));
sum += r.getInt(2);
System.out.println("\tTotal\t" + money.format(sum));
System.out.println ("\nTranID\tFrom\tBalance\tto\tBalance");
r = s.executeQuery(selection);
r.first();
for (int i=0; i <= 1000; i++)
r.first();
while(r.next())
accountWithdraw = (int) ((Math.random() * 10) + 1);
accountDeposit = (int) ((Math.random() * 10) + 1);
while ( (accountWithdraw == r.getInt(1)) || (accountWithdraw == accountDeposit) )
accountWithdraw = (int) ((Math.random() * 10) + 1);
accountDeposit = (int) ((Math.random() * 10) + 1);
r.absolute(accountWithdraw);
s.executeUpdate("UPDATE MyBank SET Balance = " + (r.getInt(2) - 1000) + " WHERE AccountNum = " + accountWithdraw);
r = s.executeQuery(selection);
r.absolute(accountWithdraw);
System.out.print (trans + "\t" + accountWithdraw + "\t" + r.getInt(2) + "\t" + accountDeposit + "\t");
r.absolute(accountDeposit);
s.executeUpdate("UPDATE MyBank SET Balance = " + (r.getInt(2) + 1000) + " WHERE AccountNum = " + accountDeposit);
r = s.executeQuery(selection);
r.absolute(accountDeposit);
System.out.println (r.getInt(2));
r.first();
trans++;
r.first();
System.out.println ("\nThe balance of accounts after money transfers is:");
System.out.println ("\tAccount\t Balance");
while (r.next())
System.out.println("\t" + r.getInt(1) + "\t" + money.format(r.getInt(2)));
total += r.getInt(2);
System.out.println ("\tTotal: " + money.format(total));
//-----Close Connections
c.close();
catch(SQLException err)
err.printStackTrace(System.out);
} -
System IP address and Java+Swings
Hi!
I m designing a Network Application in Java. While desiging Front End using swings, i want if the System IP is changed the application should know that. I m sure my code is logically correct and calls
try {
this.systemIP = null;
this.systemIP = InetAddress.getLocalHost().getHostAddress();
catch (Exception ex)
System.out.println (ex.getMessage());
}but its the fault of JVM, i think, it keeps Local System IP unchanged until the application is closed and reload..
What should i do in this scenario...plz guide me!
Regards>
but its the fault of JVM, i think, it keeps Local
System IP unchanged until the application is closed
and reload..
That would be my guess.
What should i do in this scenario...plz guide me!You already answered the question. You restart the application.
You could probably do something using JNI, but whether that works depends on what you are doing with the IP in your java code (although there are some obscure command line options/properties that might make it work.) -
Question about database and java
Suppose i have a form with a bunch of textboxes etc.
What is the best way to send the data from the
result set to the form objects.
Thanks in advance
Maggiehi,
first you use the array of buttons then in a loop
you should adopt the logic
for(i=0;i<=10;i++)
myButton.setTrxt(RecordSet[i]);
where condition depends on the no of buttons.
zafir -
How Connect to oracle database with java
i have trouble with my program
i use oracle 8i to my database and java for interface
this mycode :
import java.sql.*;
class TestThinApp {
public static void main (String args[])
throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
// or you can use:
// DriverManager.registerDriver(
// new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@dssw2k01:1521:orcl","scott","tiger");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(
"select 'Hello Thin driver tester '||USER||'!' result from dual");
while(rset.next())
System.out.println(rset.getString(1));
rset.close();
stmt.close();
conn.close();
i have trouble , becouse i can connect my database with java (JDK)
if any one can help me pls?
arifPLEASE .... Ask in an Oracle Java forum.
And read the documentaiton. There is a whole document devoted to doing that. http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/toc.htm has examples.
PLEASE ... do not ask product questions in a forum which clearly has a title saying it is devoted to assisting with download problems. -
I m using ms access as database and i want to create a login page in java
hye frnz... plz help me m new to java
m using ms access as database and try to create a login page where user type username and pw
i had enter valid user entries in database i checked connectivity is working i want as user login the main window must open after checking username and pw field to database but
now there is an error class not found exception sun:jdbc...... error
plz help me i had stuck frm 4 days */
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Login extends JFrame
//Component Declarations
JLabel jlb1,jlb2;
JTextField jtf1;
JPasswordField jpf1;
JButton jb1,jb2;
//Constructor
Login()
//frame settings
setTitle("Login Dialog");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension d= Toolkit.getDefaultToolkit().getScreenSize();
setBounds(d.width/2-175,d.height/2-100,350,200);
gbc.insets=new Insets(7,7,7,7);
//adding components
jlb1=new JLabel("User ID");
gbc.gridx=0;
gbc.gridy=0;
add(jlb1,gbc);
jlb2=new JLabel("Password");
gbc.gridx=0;
gbc.gridy=1;
add(jlb2,gbc);
jtf1=new JTextField(10);
gbc.gridx=1;
gbc.gridy=0;
add(jtf1,gbc);
jpf1=new JPasswordField(10);
gbc.gridx=1;
gbc.gridy=1;
add(jpf1,gbc);
jb1=new JButton("Login");
gbc.gridx=0;
gbc.gridy=2;
add(jb1,gbc);
jb1.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
Connection conn=null;
Statement stmt=null;
boolean found=false;
try
Class.forName("sun.jdbc.driver.JdbcOdbcDriver");
String dataSourceName = "Inventory";
String dbURL = "jdbc:odbc:" + dataSourceName;
conn=DriverManager.getConnection(dbURL, "","");
stmt=conn.createStatement();
ResultSet rst=stmt.executeQuery("Select * from User");
System.out.println(jtf1.getText()+"/t"+jpf1.getPassword());
while(rst.next())
System.out.println( rst.getString(1) +"/t"+ rst.getString(2));
if(jtf1.getText().equals(rst.getString(1).trim()) && new String(jpf1.getPassword()).equals(rst.getString(2).trim()))
found=true;
rst.close();
dispose();
MainWindow mw= new MainWindow(); /*created min window object created to be opend after login but not working*/
break;
rst.close();
stmt.close();
conn.close();
catch(ClassNotFoundException e){System.out.print(e);}
catch(Exception e){System.out.print(e);}
if(found==false) /*this portion is executing and dialog box appears invalid name and pw with class not found exception sun:jdbc.......on console */
JOptionPane.showMessageDialog(null,"Invalid username or password",
"Error Message",JOptionPane.ERROR_MESSAGE);
jb2=new JButton("Clear");
gbc.gridx=1;
gbc.gridy=2;
add(jb2,gbc);
jb2.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
jtf1.setText("");
jpf1.setText("");
jtf1.requestFocus();
setSize(350,200);
setVisible(true);
jtf1.requestFocus();
public static void main(String args[])
Login l=new Login();
}http://forums.oracle.com/forums/ann.jspa?annID=599
Oh, and by the way, your keyboard seems to be broken as your words are not getting spelled correctly. -
Problem with java swing button and loop
Problem with java swing button and loop
I�m using VAJ 4.0. and I�m doing normal GUI application. I have next problem.
I have in the same class two jswing buttons named start (ivjGStart) and stop (ivjGStop) and private static int field named Status where initial value is 0. This buttons should work something like this:
When I click on start button it must do next:
Start button must set disenabled and Stop button must set enabled and selected. Field status is set to 1, because this is a condition in next procedure in some loop. And then procedure named IzvajajNeprekinjeno() is invoked.
And when I click on stop button it must do next:
Start button must set enabled and selected and Stop button must set disenabled.
Field status is set to 0.
This works everything fine without loop �do .. while� inside the procedure IzvajajNeprekinjeno(). But when used this loop the start button all the time stay (like) pressed. And this means that a can�t stop my loop.
There is java code, so you can get better picture:
/** start button */
public void gStart_ActionEvents() {
try {
ivjGStart.setEnabled(false);
ivjGStop.setEnabled(true);
ivjGStop.setSelected(true);
getJTextPane1().setText("Program is running ...");
Status = 1;
} catch (Exception e) {}
/** stop button */
public void gStop_ActionEvents() {
try {
ivjGStart.setEnabled(true);
ivjGStart.setSelected(true);
ivjGStop.setEnabled(false);
getJTextPane1().setText("Program is NOT running ...");
Status = 0;
} catch (Exception e) {
/** procedure IzvajajNeprekinjeno() */
public void IzvajajNeprekinjeno() { //RunLoop
try {
int zamik = 2000; //delay
do {
Thread.sleep(zamik);
PreberiDat(); //procedure
} while (Status == 1);
} catch (Exception e) {
So, I'm asking what I have to do, that start button will not all the time stay pressed? Or some other aspect of solving this problem.
Any help will be appreciated.
Best regards,
TomiThis is a multi thread problem. When you start the gui, it is running in one thread. Lets call that GUI_Thread so we know what we are talking about.
Since java is task-based this will happen if you do like this:
1. Button "Start" is pressed. Thread running: GUI_Thread
2. Event gStart_ActionEvents() called. Thread running: GUI_Thread
3. Method IzvajajNeprekinjeno() called. Thread running: GUI_Thread
4. Sleep in method IzvajajNeprekinjeno() on thread GUI_Thread
5. Call PreberiDat(). Thread running: GUI_Thread
6. Check status. If == 1, go tho 4. Thread running: GUI_Thread.
Since the method IzvajajNeprekinjeno() (what does that mean?) and the GUI is running in the same thread and the event that the Start button has thrown isn't done yet, the program will go on in the IzvajajNeprekinjeno() method forever and never let you press the Stop-button.
What you have to do is do put either the GUI in a thread of its own or start a new thread that will do the task of the IzvajajNeprekinjeno() method.
http://java.sun.com/docs/books/tutorial/uiswing/index.html
This tutorial explains how to build a multi threaded gui.
/Lime -
Java Swing/AWT and FX is so old school! Give me HTML and CSS for GUI!
Dear Java,
I am a seasoned programmer and I feel it's time JAVA implements a GUI system where it uses HTML and CSS for the GUI. For the love of god just look at the interfaces you can make using HTML and CSS alone. I am a big fan of Java Swing and the recent GUI designer for FX is quite cool. But they are just not as simple as HTML and CSS. And JavaFX has some interesting requirements for the graphics.
I know it is possible to use JavaFX and implement the WebView/WebDriver and make it load a HTML page, etc... but why go through all the trouble?
Just imagine... if you make Java where it has powerful back-end to do what it does best and the HTML/CSS powered GUI on the front-end. It will make the lives of many developers much much easier.
I am not sure whether a Swing designed GUI will be faster than a HTML designed GUI... but if you look at a traditional browser and how fast it renders HTML/CSS, I am sure if Java had a native Form where it uses HTML and CSS to render the GUI, Java will make the dreams of many programmers a reality.
Make it happen!!!!Check this i solve problem just now using this
https://wiki.archlinux.org/index.php/Ja … ow_Manager -
Viewing and printing a PDF file from Java Swing Application
Hello,
I need to view and print PDF files from Java Swing Application.How do I do that?I appreciate your help.
Thank you
Sumana SomareddyIf you have a link to the URL pointing to the PDF file, you can allow the browser to open it. Then use the print function of the browser to print the PDF document.
Regards,
Tak.
Maybe you are looking for
-
I seem to have music files in various places on my laptop, on my husbands computer and our main imac. What we want to do is put all music on imac so when each of us logs on we have the same files availabe in itunes, but we logon seperately so we can
-
No data in view in SQL Developer
When trying to run the following code in SQL Developer the return values from the statement are all NULL. SELECT DECODE(paaf.assignment_type, 'E', hr_general.decode_lookup('EMP_CAT', paaf.employment_category), 'C',
-
In desperate need of a Pattern Maker!!!
Photoshop CS6 no longer has the Pattern Maker nor supports the plugin that was available in CS5. Does anyone know of a software or 3rd party plugin that will create patterns from high res photo files? I've searched in Google, like crazy, but alas hav
-
How to make it mandatory to enter a value in a collection?
Is it possible in Wave 7 CLM - Contract Management to make it mandatory for a collection to have at least one record? We have created a custom collection and placed it on the Supplier tab of agreements and we would now like to make it mandatory for a
-
How can i separate 4 devises into individual accounts?
I have 1 x iPhone 4, 2 x iPhone 4S and 1 x iTouch 4th Gen all on one iTunes, iCloud and the same Apple iD. How can i separate them into having their own individual accounts??? Please help we are all recieving each others txt messages and contacts lis