Using one Applet to open another - java

I created a login applet that that I want to open another main applet once the user logins but I cant seems to get it to work right. I tried making an object of themain applet and then invoking it but that didnt work so then I tried creating another pane for the new applet and setting it inside of the login applet but that didnt work. Can someone tell me what im doing wrong?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.applet.Applet;
public class login extends Applet implements ActionListener{
FundRaiserApplet secondApplet;
JLabel uname = new JLabel("Username");
JLabel pname = new JLabel("Password");
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
JButton login = new JButton("Login");
static final String USER = "identityone";
static final String PASS = "test";
JLabel status = new JLabel("");
JPanel fundraiserPanel;
public void init(){
setSize(250,200);
add(uname);
add(username);
add(pname);
add(password);
add(login);
add(status);
login.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == login){
//status.setText("Password or Username is incorrect");
String user = username.getText();
String pass = password.getText();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/Credentials;user=test;password=test");
Statement stmt = conn.createStatement();
Statement credR = conn.createStatement();
String credentialSet = "INSERT INTO Credentials" +"( username, password)" + " VALUES('" + USER +"' , '" + PASS +"' )";
stmt.executeUpdate(credentialSet);
ResultSet ret = credR.executeQuery("SELECT username , password FROM Credentials");
while (ret.next()) {
if(user.equals(ret.getString("username")) && pass.equals(ret.getString("password"))) {
//didnt work
FundRaiserApplet runme = new FundRaiserApplet();
runme.init();
JPanel container = new JPanel();
container.setLayout(new GridLayout(1,0));
container.add(secondApplet);
add(container);
secondApplet.init();
secondApplet.start();
secondApplet.setVisible(true);
status.setText("Logged in");
// this.dispose();
//FundRaiserApplet.init();
}else{
status.setText("Wrong Username or Password");
}
}
ret.close();
} catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
}
}
//MAIN CLASS BELOW////////////////////
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.applet.Applet;
public class FundRaiserApplet extends Applet {
//database creation
// static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//static final String DB_URL = "jdbc:derby://localhost/";
//end database creation
ArrayList<String> resultsHold = new ArrayList<>();
private JLabel DonorNamelabel;
private JLabel AmountLabel;
private JLabel charityName;
private JLabel emptycell;
static final String USER = "identityone";
static final String PASS = "test";
private JTextField donorNameTexfield;
private JTextField Amounttextfield;
private JTextField singletextfield;
private JTextArea resultsscreen;
public JButton seeAll;
public JButton myExitButton;
public JButton Enter;
public JButton ClearButton;
JPanel centerPanel;
JPanel buttonPanel;
JPanel textfieldPanel;
JPanel myresultsPanel;
JPanel results1Panel;
//JPanel container = new JPanel();
public void init() {
setSize(400, 325);
DonorInfo donor = new DonorInfo();
String[] charityselections = { "Wounded Warrior Project","American Red Cross", "Doctors Without Borders","American Cancer Society","PETA"};
final JComboBox<String> chairtycombo = new JComboBox<>(charityselections);
chairtycombo.setVisible(true);
//creating text fields, labels and buttons
emptycell = new JLabel("");
DonorNamelabel = new JLabel("Donor Name",10);
AmountLabel = new JLabel("Pledge Amount",10);
charityName = new JLabel ("Charity Name",10);
donorNameTexfield = new JTextField(8);
Amounttextfield = new JTextField(8);
singletextfield = new JTextField(35);
resultsscreen = new JTextArea(7, 35);
final JScrollPane myScroll = new JScrollPane(resultsscreen);
myExitButton = new JButton("Exit");
myExitButton.setSize(new Dimension(10, 10));
Enter = new JButton("Enter Info");
Enter.setSize(new Dimension(10, 10));
ClearButton= new JButton("Clear");
ClearButton.setSize(new Dimension(10, 10));
seeAll = new JButton("See All Results");
seeAll.setSize(new Dimension(10, 10));
seeAll.setMargin(new Insets(2, 0, 2, 0));
//adding panels
results1Panel = new JPanel();
centerPanel = new JPanel();
buttonPanel = new JPanel();
textfieldPanel = new JPanel();
myresultsPanel = new JPanel();
//adding labels
centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 67, 0));
centerPanel.add(DonorNamelabel);
centerPanel.add(AmountLabel);
centerPanel.add(charityName);
// adding text fields
textfieldPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 30, 3));
textfieldPanel.add(donorNameTexfield);
textfieldPanel.add(Amounttextfield);
textfieldPanel.add(chairtycombo);
//adding the buttons to the panel
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));
buttonPanel.add(seeAll);
buttonPanel.add(myExitButton);
buttonPanel.add(Enter);
buttonPanel.add(ClearButton);
myresultsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
myresultsPanel.add(emptycell);
myresultsPanel.add(myScroll);
myresultsPanel.add(emptycell);
myresultsPanel.add(emptycell);
results1Panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 2));
results1Panel.add(singletextfield);
add(centerPanel, BorderLayout.NORTH);
add(textfieldPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
add(results1Panel, BorderLayout.NORTH);
add(myresultsPanel, BorderLayout.SOUTH);
//clear button action event listener
ClearButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
donorNameTexfield.setText("");
Amounttextfield.setText("");
singletextfield.setText("");
resultsscreen.setText("");
resultsHold.clear();
}
});
//end clear listener
Enter.addActionListener(new ActionListener() {
int counter=1;
#Override
public void actionPerformed(ActionEvent e)
{
singletextfield.setText("");
double amountc = Double.parseDouble(Amounttextfield.getText());
String charityselection = (String) chairtycombo.getSelectedItem();
donor.setName(donorNameTexfield.getText());
donor.setCharityname(charityselection);
donor.setAmount(amountc);
String name = donor.getName();
Double amount = donor.getAmount();
String charity = donor.getCharityName();
String text ="Donor Name is:" +name +"\n"+"Pledge Amount: $" + amount + "\n"+"Charity Name: "+charity+"\n"+"-----------------------------------------------";
//Ading the text variable into array
resultsHold.add(text);
//displaying results in textarea
singletextfield.setText("Donor Name is:" +name +" Pledge Amount: $" + amount + "..." + "Charity Name: "+charity);
try
{
// Create a connection to the database.
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/Fundraiser;user=test;password=test");
Statement stmt = conn.createStatement();
String sqlStatement = "INSERT INTO Fundraiser" +"( NAME, PLEDGE_AMOUNT,CHARITY)" + " VALUES('" + name +"' , " + amount +" , '" + charity +"' )";
stmt.executeUpdate(sqlStatement);
System.out.println("Records Updated.");
// Close the connection.
conn.close();
System.out.println("Connection closed.");
}
catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
// resetting text fields
donorNameTexfield.setText("");
Amounttextfield.setText("");
counter++;
}
});
//event listeners
myExitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
//exit program
System.exit(0);
}
});
seeAll.addActionListener((ActionEvent e) -> {
try{
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/Fundraiser;user=test;password=test");
Statement stmt = conn.createStatement();
String sqlStatement = "SELECT * FROM Fundraiser";
ResultSet result = stmt.executeQuery(sqlStatement);
while (result.next())
{
resultsscreen.append("Pledge Name: " + result.getString("NAME") + "\n"+
"Amount Given: "+result.getDouble("PLEDGE_AMOUNT") +"\n"+
"Donor Charity: " + result.getString("CHARITY")+"\n"+ "........................."+ "\n");
}
// Close the connection.
conn.close();
} catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
//resultsscreen.append(text.toString());
});
}
public static void main(String[] args) {
//database initialization
Connection conn = null;
Connection conn2 = null;
Statement stmt = null;
Statement start = null;
try{
//downloaded driver "mysql-connector-java-5.1.18-bin.jar" and added into project library
//downloaded "derbyclient.jar" and added to library
Class.forName("com.mysql.jdbc.Driver").newInstance ();
//connection time!
System.out.println("Connecting to database...");
//if a folder already exist in "C:\Users\User\.netbeans-derby" called "Fundraiser" then delete it or it will throw an exception
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/Fundraiser;create=true;user=test;password=test");
conn2 = DriverManager.getConnection("jdbc:derby://localhost:1527/Credentials;create=true;user=test;password=test");
//Create database
System.out.println("Fundraiser Database Created!");
stmt = conn.createStatement();
start = conn2.createStatement();
try{
String sql1 = "DROP TABLE Fundraiser";
String dropcreds = "DROP TABLE Credentials";
stmt.executeUpdate(sql1);
System.out.println("Fundraiser Table Deleted...");
start.executeUpdate(dropcreds);
System.out.println("Credentials Table Deleted...");
}catch(Exception e){System.out.println("No Table to Delete...");}
String sql = "CREATE TABLE Fundraiser" +
"(NAME VARCHAR(255), " +
" PLEDGE_AMOUNT DOUBLE, " +
" CHARITY VARCHAR(255) )";
String sql2 = "CREATE TABLE Credentials" +
"(username VARCHAR(255), " +
" password VARCHAR(255) )";
stmt.executeUpdate(sql);
System.out.println("Fundraiser Table created successfully...");
start.executeUpdate(sql2);
System.out.println("Credential Table Created successfully...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException my2){
System.out.println(my2);
}
try{
if(conn!=null)
conn.close();
}catch(SQLException my){
my.printStackTrace();
}
}//end try
FundRaiserApplet applet = new FundRaiserApplet();
applet.init();
JFrame frame = new JFrame("Identity One");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( applet );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
applet.start();
//login.main(args);
}
public void ShowWindow() {
FundRaiserApplet applet = new FundRaiserApplet();
applet.init();
JFrame frame = new JFrame("My Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( applet );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
applet.start();
}
}

You can try to use javascript to open the second applet in the web page.

Related

How to Show text retrieved from database on JButton, JTextArea in Java?

I am trying to build a quiz app and I managed to build the database. I created a GUI using the card layout to switch between panels and I tried to retrieve the questions and options from from the database to a JtextArea with no success. My question is how do I get the visual components (jtext area,jbutton to display the content from the database) I want them to automatically set the text according with the question number.
this is my code
package quizzGUI;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.List;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JRadioButton;
import javax.swing.JTextPane;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.management.Query;
import javax.swing.ButtonGroup;
public class quizzMain {
private JFrame frame;
private JPanel Menu;
private JPanel Playing;
private JPanel Score;
private final ButtonGroup buttonGroup = new ButtonGroup();
public JTextPane textPane;
public JButton btnA;
public JRadioButton rdbtnB;
public JRadioButton rdbtnC;
public JRadioButton rdbtnD;
public JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
quizzMain window = new quizzMain();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
Connection connection = null;
public quizzMain() {
initialize();
connection = sqlConnection.dbConnector();
}
private void initialize() {
Connection connection = sqlConnection.dbConnector();
Statement stmt=null;
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel Menu = new JPanel();
frame.getContentPane().add(Menu, "name_668313932787145");
Menu.setLayout(null);
Menu.setVisible(true);
final JPanel Playing = new JPanel();
Playing.setBackground(Color.CYAN);
frame.getContentPane().add(Playing, "name_668321772390383");
Playing.setLayout(null);
Playing.setVisible(false);
final JPanel Score = new JPanel();
frame.getContentPane().add(Score, "name_668324579994343");
Score.setLayout(null);
Score.setVisible(false);
JLabel lblNewLabel = new JLabel("C QUIZZ");
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD | Font.ITALIC, 14));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(123, 47, 169, 40);
Menu.add(lblNewLabel);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Integer i=0;
Playing.setVisible(true);
Menu.setVisible(false);
try{
String query = ("SELECT * FROM Question ");
PreparedStatement pst=connection.prepareStatement(query);
ResultSet rs=pst.executeQuery();
do {
btnA.setText(rs.getString("ANSWERA"));
}while(rs.next());
}catch(Exception e ){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
});
btnStart.setFont(new Font("Tahoma", Font.BOLD, 12));
btnStart.setBounds(167, 176, 89, 23);
Menu.add(btnStart);
JButton btnFinish = new JButton("Finish");
btnFinish.setBounds(335, 227, 89, 23);
Playing.add(btnFinish);
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Score.setVisible(true);
Playing.setVisible(false);
}
});
JButton btnNextQuestion = new JButton("Next");
btnNextQuestion.setBounds(10, 227, 89, 23);
Playing.add(btnNextQuestion);
JTextArea textArea = new JTextArea();
textArea.setBounds(20, 11, 387, 41);
Playing.add(textArea);
JButton btnA = new JButton("New button");
btnA.setBounds(20, 84, 381, 41);
Playing.add(btnA);
JTextArea txtrScore = new JTextArea();
txtrScore.setBounds(87, 74, 244, 43);
txtrScore.setText("Score:");
Score.add(txtrScore);
}
}
Since you didn't mention your code, its difficult to give you a short precise example. I would recommend you to go through this tutorial which retrieves information (name and number) and display it in JTextArea.
Extracting the key points from the tutorial below:
Database connection establishment and fetching information
String url = "jdbc:mysql://localhost:3306/";
String db = "databasename";
String driver = "com.mysql.jdbc.Driver";
String user = "xxxx";
String pass = "xxxx";
Connection con = null;
PreparedStatement pstatement = null;
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db , user, pass);
pstatement = con.prepareStatement("SELECT name, phonenumber FROM tablename");
con = DriverManager.getConnection(url + db, user, pass);
ResultSet rs = pstatement.executeQuery();
while(rs.next()){
String name = rs.getString(1);
int phonenumber = rs.getInt(2);
}
Set text in JTextArea
Then use setText method of JTextArea to set the text. For example, recordTextArea.setText(name + " " + phonenumber);.

SQLite database not displaying on button click

Evening all,
So I've been working on creating a local database using SQLite. (As a plugin that is part of Firefox). It uses three classes:
databaseConnection
Login
Display
and two tables (which come under the database MyFilms) called:
Users
MyFilms
databaseConnection is used to simply just connect to my SQLite database MyFilms, which it does fine.
The second class, Login, access my Users table from my database so it can access the logins and proceed to my GUI called Display.
Display will load the following GUI, which consists of a button, which when clicked is supposed to load the data from my database table MyFilms into a JTable:
However, when I click the button, nothing loads... it even looks like the JTable is not there, but when I check my code it defiantly is!
The code where I think the problem might lie is:
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
Any idea why the database is not showing here? Please find the code to each class below:
databaseConnection:
import java.sql.*;
import javax.swing.*;
public class databaseConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Joe\\workspace\\MyFilms.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!");
return conn;
}
catch(Exception anException)
{
JOptionPane.showMessageDialog(null, anException);
return null;
}
}
}
Login:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frmTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frmTest.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField textFieldUN;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
connection = databaseConnection.dbConnector();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frmTest = new JFrame();
frmTest.setTitle("Database Login");
frmTest.setBounds(100, 100, 345, 184);
frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTest.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(34, 37, 64, 14);
frmTest.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Password:");
lblNewLabel_1.setBounds(34, 66, 64, 14);
frmTest.getContentPane().add(lblNewLabel_1);
textFieldUN = new JTextField();
textFieldUN.setBounds(126, 34, 151, 20);
frmTest.getContentPane().add(textFieldUN);
textFieldUN.setColumns(10);
JButton btnLogin = new JButton("Login");
frmTest.getRootPane().setDefaultButton(btnLogin);
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = "Select * from Users where username=? and password=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textFieldUN.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()){
count = count +1;
}
if (count == 1){
frmTest.dispose();
Display GUI = new Display();
GUI.setVisible(true);
}
else if (count > 1){
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}
else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct - Please try again..");
}
rs.close();
pst.close();
}
catch (Exception anException){
JOptionPane.showMessageDialog(null, anException);
}
}
});
btnLogin.setBounds(126, 111, 89, 23);
frmTest.getContentPane().add(btnLogin);
passwordField = new JPasswordField();
passwordField.setBounds(126, 64, 151, 17);
frmTest.getContentPane().add(passwordField);
}
}
Display:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class Display extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
btnLoadData.setBounds(596, 11, 89, 23);
contentPane.add(btnLoadData);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(684, 45, -675, 349);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
Any help would be greatly appreciated! Cheers..
However, when I run it in Eclipse I receive no errors at all. It runs fine, just does not display the database in the JTable.
Could you please replace your Display.java with the following:
Display.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
public class Display extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception anException) {
anException.printStackTrace();
}
}
});
// btnLoadData.setBounds(596, 11, 89, 23);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(btnLoadData, BorderLayout.EAST);
contentPane.add(buttonPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
// scrollPane.setBounds(684, 45, -675, 349);
table = new JTable();
scrollPane.setViewportView(table);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
}
and see the results?
Few changes have been made to your code. They are:
1) You first added scrollPane to the contentPane then you added table to scrollPane. I changed the order.
2) You used absolute layout. I changed that with BorderLayout.
The result displayed on my system is:
Hope this helps!

Filter JTable using a JcomboBox

Im trying to filter my Jtabke using my Jcomboox but i cant do it and in the :
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting
it only says how to filter using search txt field or sort using headers but not how to use a JComboBox change event to filter a JTable is there a simple code to do this??
EDITED
GOT iT WORKING
This is my Code:
public class Sql extends JFrame{
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"fecha","clave_pdv","pdv","turno","clave_platillo","platillo","precio","total sin iva"});
public TableRowSorter<DefaultTableModel> sorter;
Connection conn = null;
Connection conn1 = null;
Statement st = null;
Statement st1 = null;
ResultSet rs = null;
ResultSet rs1 = null;
//Create list of values
private final JComboBox comboBox = new JComboBox();
private final JComboBox comboBox_1 = new JComboBox();
private JTextField textField;
public Sql(){
table.setAutoCreateRowSorter(true);
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
st = conn.createStatement();
rs= st.executeQuery("SELECT DISTINCT Nombre_Pdv FROM VENTA_PLATILLOS");
while(rs.next()){
comboBox.addItem(rs.getString(1));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn1 = DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
st1 = conn.createStatement();
rs1 = st1.executeQuery("SELECT DISTINCT Nombre_Turno FROM VENTA_PLATILLOS");
while(rs1.next()){
comboBox_1.addItem(rs1.getString(1));
}
}
catch(Exception e){
e.printStackTrace();
}
getContentPane().setLayout(null);
table.setModel(model);
table.setBounds(50, 50, 50, 50);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(139, 88, 535, 227);
getContentPane().add(scrollPane);
comboBox.setBounds(404, 11, 130, 31);
getContentPane().add(comboBox);
comboBox_1.setBounds(544, 11, 130, 31);
getContentPane().add(comboBox_1);
textField = new JTextField();
textField.setBounds(24, 16, 86, 20);
getContentPane().add(textField);
textField.setColumns(10);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 2);
sorter.setRowFilter(rf);
}
});
comboBox_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox_1.getSelectedItem().toString(), 3);
sorter.setRowFilter(rf);
}
});
sorter = new TableRowSorter<DefaultTableModel>(model);
table.setRowSorter(sorter);
//Populate table
sqlConection bd = new sqlConection();
List<Value> values = bd.selectAll();
for(Value v : values){
model.addRow(new Object[]{v.fecha,v.clave_pdv,v.pdv,v.turno,v.clave_platillo,v.platillo,v.precio,v.total});
}
}
Try this, using a TableRowSorter, fill the table with some numbers and filter it ...
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class TableFilter extends JFrame {
private JTable table;
private DefaultTableModel model;
private TableRowSorter<DefaultTableModel> sorter;
public TableFilter() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
pack();
setVisible(true);
}
public static void main(String args[]) {
new TableFilter();
}
private void initComponents() {
JPanel panel = new JPanel();
final JComboBox<String> comboBox = new JComboBox<>(new String[]{"","1","2","3"});
JButton button = new JButton("filter");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 0);
sorter.setRowFilter(rf);
}
});
panel.add(comboBox);
panel.add(button);
table = new JTable(model = new DefaultTableModel(3,3));
sorter = new TableRowSorter<DefaultTableModel>(model);
table.setRowSorter(sorter);
add(panel,BorderLayout.SOUTH);
add(new JScrollPane(table));
}
}
Fill the table with some numbers
filter it

How to insert image to existing JFrame

Am trying to create login page for my application and i did it well but i couldn't able to add a image to my JFrame, here is my code for login page....
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.*;
public class log extends JFrame {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://sqldatabase.com/databasename";
// Database credentials
static final String USER = "usernamr";
static final String PASS = "pass";
public static void main(String[] args) throws IOException {
log frameTabel = new log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JLabel label = new JLabel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
log() throws IOException{
super("Login Autentification");
setSize(500,500);
setLocation(300,280);
panel.setLayout (null);
//ImageIcon image = new ImageIcon("image.jpeg");
//JLabel hangman = new JLabel(new ImageIcon(urlOfImageFile));
//panel.add(image, BorderLayout.NORTH);
//Image image = ImageIO.read(new File("F:\\IModubytes\\Images\\1.jpg"));
//JLabel picLabel = new JLabel(new ImageIcon(image));
//panel.add(picLabel);
//panel.repaint();
txuser.setBounds(300,100,150,20);
pass.setBounds(300,135,150,20);
blogin.setBounds(380,170,80,20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin(){
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String puname = txuser.getText();
String ppaswd = pass.getText();
String sql = "SELECT * FROM EmpDetails WHERE id="+puname;
System.out.println(puname);
ResultSet rs = stmt.executeQuery(sql);
String pw = null;
while(rs.next()) {
pw = rs.getString("pass");
}
rs.close();
//if(puname.equals("test") && ppaswd.equals(pw)) {
if(ppaswd.equals(pw)) {
newFrame regFace =new newFrame();
regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Can anyone please help me how to add image in this....
You already have the code to load the image and add the label to your frame.
So the next step is to add your components to the label and then add the label to the content pane, instead of adding the components to the panel and adding the panel to the content pane.
Also, don't use a null layout!!! Swing was designed to be used with layout mangers. Read the section from the Swing tutorial on Layout Managers for more information and working examples.

Connecting Java To SQL [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I don't know much about SQL, but I'm fine with Java, I just wanted to know how I can retrieve a variable from my SQL database: 'EasyDirectory'. Like:
String test = con.getQuery(query1).get(username);
Obviously that doesn't work but I would like a snippet of code that does that. Heres all of my code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory {
public static void main(String args[]) throws IOException, SQLException {
Connection con = null;
try {
// Load the JDBC driver
String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);
// Create a connection to the database
String serverName = "www.freesql.org";
String mydatabase = "EasyDirectory";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
String username = "*********";
String password = "*********";
con = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}
final JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
final JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(200, 30));
searchprogress.setPreferredSize(new Dimension(280, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
final List<String> housetypes = new ArrayList<String>();
String line = "";
BufferedReader br = new BufferedReader(new FileReader("Index.txt"));
while (line != null) {
line = br.readLine();
housetypes.add(line);
String seperation = br.readLine();
}
/* Finish Buffered Reader */
/* Start Content Code */
final JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchfield.setEnabled(true);
done.setVisible(false);
searchbutton.setVisible(true);
searchprogress.setValue(0);
}
});
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchprogress.setValue(100);
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
done.setVisible(true);
searchbutton.setVisible(false);
for (String housetype : housetypes) {
if (searchquery.equals(housetype)) {
String housepath = housetype + "/" + housetype + ".txt";
System.out.println(housepath);
try {
BufferedReader housebr = new BufferedReader(new FileReader(housepath));
String housename_query = housebr.readLine();
String housenumber_query = housebr.readLine();
String housestreet_query = housebr.readLine();
String houselocality_query = housebr.readLine();
String housepostal_query = housebr.readLine();
System.out.println(housepostal_query);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.setResizable(false);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(false);
/* Start Login Window */
int passtimes = 3;
final JFrame login = new JFrame("Login");
JPanel login_panel = new JPanel();
JLabel userlabel = new JLabel("Username: ");
JLabel passlabel = new JLabel(" Password: ");
JButton loginuser = new JButton("Login");
JButton cancel = new JButton("Cancel");
final JTextField user_field = new JTextField();
user_field.setPreferredSize(new Dimension(100,30));
final JPasswordField pass_field = new JPasswordField();
pass_field.setPreferredSize(new Dimension(100,30));
ImageIcon icon = new ImageIcon("Images/Logo.png");
ImageIcon space = new ImageIcon("Images/Spacing.png");
JLabel logo = new JLabel();
JLabel spacing = new JLabel();
logo.setIcon(icon);
login.setPreferredSize(new Dimension(200,212));
login_panel.add(logo);
login_panel.add(userlabel);
login_panel.add(user_field);
login_panel.add(passlabel);
login_panel.add(pass_field);
login_panel.add(spacing);
login_panel.add(loginuser);
login_panel.add(cancel);
login.add(login_panel);
login.pack();
login.setVisible(true);
login.setLocationRelativeTo(null);
loginuser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String user_input = user_field.getText();
String pass_input = pass_field.getText();
String username = "Tom";
String password = "******";
if(user_input.equals(username)){
if(pass_input.equals(password)){
user_field.setEnabled(false);
pass_field.setEnabled(false);
frame.setVisible(true);
login.setVisible(false);
}
else{//If Password AND Username is incorrect
JOptionPane.showMessageDialog(panel, "Password and/or Username Is Incorrect.", "Failed Login", JOptionPane.ERROR_MESSAGE);
}
}
else{ //If Username is incorrect
JOptionPane.showMessageDialog(panel, "Password and/or Username Is Incorrect.", "Failed Login", JOptionPane.ERROR_MESSAGE);
}
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
}
}
Thanks, Helping is greatly appreciated!
By reading the API of Connection (here: http://docs.oracle.com/javase/6/docs/api/java/sql/Connection.html) I would assume that it would have to be something like:
final Statement statement = con.createStatement();
final ResultSet result = statement.executeQuery(query1);
//do stuff with the resultset
//result.getString(something), see http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html
On a side-note. I don't really like the fact that you have put both the GUI and the database logic in the same class. You really should separate concerns, by applying the MVC pattern or something similar. For instance, you could create one class for the GUI, one class for to the connection the database, and one class for starting the application and tying the two others together.

Categories