I am learning JDBC, completely new to it. I know MySQL very well. I have a search form in my applet (tab 2), where I search for food. And when I click search, I want it to search for the exact food from the Database and return the table contents of that particular row alone. But I am not getting any result. Only an empty frame opens. But when I put the query as "SELECT * FROM table", I am getting the complete table. But I want only one row, the one that is searched for. Can anyone please tell me where I am going wrong? Here's my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.DriverManager;
import java.util.Vector;
import javax.swing.*;
import com.mysql.jdbc.*;
public class Tryout extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
final Vector columnNames = new Vector();
final Vector data = new Vector();
private JTabbedPane tabbedPane = new JTabbedPane();
private JPanel inputpanel;
private JPanel searchpanel;
public String s;
public Tryout() {
inputpanel = createPage1();
searchpanel = createPage2();
tabbedPane.addTab("Input Form", inputpanel);
tabbedPane.addTab("Search Form", searchpanel);
this.add(tabbedPane, BorderLayout.CENTER);
}
public JPanel createPage1() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Some code
return panel;
}
public JPanel createPage2() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 0.5;
c.weighty = 0.5;
JLabel region = new JLabel("Enter Region");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 0;
c.gridy = 0;
panel.add(region, c);
JTextField field = new JTextField(20);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 1;
c.gridy = 0;
panel.add(field, c);
JButton search = new JButton("SEARCH");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 2;
c.gridy = 0;
panel.add(search, c);
s = field.getText();
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
try{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/delikat", "root", "");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT * FROM delicious WHERE name = ?");
statement.setString(1,s);
ResultSet rs= (ResultSet) statement.executeQuery();
ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
statement.close();
}
catch(Exception e) {}
JFrame tab=new JFrame();
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
tab.add( scrollPane );
tab.setVisible(true);
tab.setSize(300,100);
}
});
return panel;
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Tryout ex = new Tryout();
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex.setSize(500,500);
ex.setVisible(true);
}
});
}
}
Here is my table:
Also, I am trying to display the table in the panel itself below the search form but it gives error when I add
panel.add(scrollpane);
How do I rectify this problem too?
Thanks
What Sudhanshu means is:
PreparedStatement statement = con.preparedStatement("SELECT * FROM delicious WHERE name = ?");
statement.setString(1,s);
ResultSet rs= (ResultSet) statement.executeQuery();
Enclose name is quotes if its of type string (varchar). Better use PreparedStatement in such cases.
Basic debugging. Did you display the value of "s" that is being used in the PreparedStatement?
s = field.getText();
From what I can see, this statement is executed when you build the GUI which means nothing because the user hasn't even entered any text into this text field.
That statement needs to be executed when you actually invoke the SQL.
Related
i'm junho who is stuying JAVA, SQL.
Now i'm struggling with this below problem.
firstly, when i tried to put 20020202 in this field, it occurred error about unexpected datatype. However, i don't know how to change number to 'Date'
Secondly, i don't know how to make JTable method to input into this below part.
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
because if i dont put the below code,
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table1 = new JTable(model);
table1.setColumnSelectionAllowed(true);
table1.setCellSelectionEnabled(true);
JScrollPane scrollPane = new JScrollPane(table1);
scrollPane.setBounds(10, 53, 600, 200);
addGrid(gbl,gbc,scrollPane,0,4,2,3,0,0);
the table doesn't show up.
So, i m wondering how to fix this problem.
my writing skill for english is not good. So, it is not going to be enough info for you.
i wish someone gives advice for me.
this is whole code that i wrote.
i hope it will help you to understand what i am struggling with.
thank you so much.
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class DbPanel extends JPanel{
public DbPanel() {
Vector columnNames = new Vector();
Vector data = new Vector();
JPanel panel = new JPanel(); //
JPanel panel2 =new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
setLayout(gbl);
//DB 관리
/* String url = "jdbc:oracle:thin:#localhost:1521:xe";
String user = "madang";
String password = "madang";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url, user, password);
String sql = "select * from STOCK_INFO order by DATE_STOCK";
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
statement.close();
} catch (Exception e) {
System.out.println(e);
}*/
//DB 끝
JLabel label = new JLabel("start_date");
addGrid(gbl,gbc,label,0,0,1,1,0,0);
JTextField textfield = new JTextField(8);
addGrid(gbl,gbc,textfield,0,1,1,1,0,0);
JLabel label2 = new JLabel("end_date");
addGrid(gbl,gbc,label2, 2,0,1,1,0,0);
JTextField textfield2 = new JTextField(8);
addGrid(gbl,gbc,textfield2, 2,1,1,1,0,0);
JButton btn = new JButton("search");
addGrid(gbl, gbc, btn, 2, 4, 1, 3, 0, 0);
JLabel lblNewLabel = new JLabel("Stock_database");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
/* lblNewLabel.setBounds(10, 11, 927, 31);*/
addGrid(gbl,gbc,lblNewLabel,0,3,4,1,1,0);
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table1 = new JTable(model);
table1.setColumnSelectionAllowed(true);
table1.setCellSelectionEnabled(true);
JScrollPane scrollPane = new JScrollPane(table1);
scrollPane.setBounds(10, 53, 600, 200);
addGrid(gbl,gbc,scrollPane,0,4,2,3,0,0);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String url = "jdbc:oracle:thin:#localhost:1521:xe";
String user = "madang";
String password = "madang";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url, user, password);
String sql = "select * from stock_info between"+textfield.getText()+"and"+textfield2.getText();
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
statement.close();
} catch (Exception e1) {
System.out.println(e1);
}
}
});
/* TableColumn column;
for (int i = 0; i < table1.getColumnCount(); i++) {
column = table1.getColumnModel().getColumn(i);
column.setMaxWidth(250);
}*/
}
private void addGrid(GridBagLayout gbl, GridBagConstraints gbc, Component c, int gridx, int gridy, int gridwidth, int gridheight, int weightx, int weighty) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbl.setConstraints(c, gbc);
add(c);
}
}
firstly, when i tried to put 20020202 in this field, it occurred error about unexpected datatype. However, i don't know how to change number to 'Date'
Parse the String date into year, month and day values. Then you can create a Calendar
object:
Calendar date = new Calendar(...);
Once you have the Calendar object you can create your SQLDate using:
Date sqlDate = new Date( date.getTimeInMillis() );
Note you should use the java.sql.Date class, not the java.util.Date class.
the table doesn't show up.
The table doesn't show up because the columns are empty when the model is created. You need to create the model once you have the valid data.
So the code should be something like:
//DefaultTableModel model = new DefaultTableModel(data, columnNames);
//JTable table1 = new JTable(model);
JTable table1 = new JTable(); // create empty table to add to scroll pane
Then after you get the data from the ResultSet you can create the model and assign it to the table:
resultSet.close();
statement.close();
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table1.setModel( model );
I connect my dosen.java with my Test5.java, I trying to make panel for Teacher to insert our score. but I make it simple like if teacher want to insert score he just need to find the the class and the subject come out from mapel combobox and insert the grade on the textfield in the bottom. when I put combobox in there I got error like raw type combobox and then my jtable got problem too.
UPDATE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.table.*;
import java.util.*;
import javax.swing.DefaultComboBoxModel;
public class dosen{
JPanel panel_dosen, panel_combo, panel_input;
JTable table;
JLabel label_input,label_input2;
JTextField tf_input,tf_input2;
JButton Insert;
JComboBox<String> classs, mapel; //first Problem
ResultSet rs;
JScrollPane scroll;
Connection conn = null;
Statement stmt = null;
String sql;
public dosen(){
table();
dataInsert();
panel_dosen = new JPanel();
panel_dosen.setLayout(new BorderLayout());
panel_dosen.add(panel_combo, BorderLayout.NORTH);
panel_dosen.add(scroll, BorderLayout.CENTER);
panel_dosen.add(panel_input, BorderLayout.SOUTH);
}
public void panelCombo(){ //combobox panel
panel_combo = new JPanel();
DefaultComboBoxModel classes = new DefaultComboBoxModel(new String[]{"Information System", "Hospitality", "Law", "Management", "Accounting"});
classs = new JComboBox(classes);
mapel = new JComboBox();
classs.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
if ("Information System".equals(classs.getSelectedItem())){
DefaultComboBoxModel ISsub = new DefaultComboBoxModel(new String[]{"Statistic and Probability", "Operating System", "Management Information System", "Inggris-2", "Object Oriented Programming"});
mapel.setModel(ISsub);
} else {
DefaultComboBoxModel Hossub = new DefaultComboBoxModel(new String[]{"Statistic and Probability", "Operating System", "Management Information System", "Inggris-2", "Object Oriented Programming1"});
mapel.setModel(Hossub);
}
}
});
classs.setSelectedIndex(0);
mapel.setSelectedIndex(0);
panel_combo.add(classs);
panel_combo.add(mapel);
}
public void table(){//i dont put panel on table because i dont think it needed
table = new JTable();
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
DefaultTableModel model = new DefaultTableModel();
String[] columnNames= {"NIM","Grade","Class"};
model.setColumnIdentifiers(columnNames);
table.setModel(model);
String Classes = "";
String Grade = "";
String NIM = "";
String url = "jdbc:mysql://localhost/kampus";
String username = "root";
String password = "abc";
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
sql = "select NIM, Grade, Class from nilai where Mapel = '"+ mapel.getSelectedItem() +"' AND Major = '" + classs.getSelectedItem() +"'";
PreparedStatement ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
NIM = rs.getString("NIM");
Classes = rs.getString("Kelas");
Grade = rs.getString("Nilai");
model.addRow(new Object[]{NIM, Grade, Classes});
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void dataInsert(){
panel_input = new JPanel();
panel_input.setLayout(new GridBagLayout());
label_input = new JLabel("NIM : ");
label_input2 = new JLabel("Nilai : ");
tf_input = new JTextField(15);
tf_input2 = new JTextField(15);
Insert = new JButton("Insert");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.LINE_START;
panel_input.add(label_input, gbc);
gbc.gridy++;
panel_input.add(label_input2, gbc);
gbc.gridy = 0;
gbc.gridx++;
gbc.anchor = GridBagConstraints.LINE_END;
panel_input.add(tf_input, gbc);
gbc.gridy++;
panel_input.add(tf_input2, gbc);
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel_input.add(Insert, gbc);
}
}
problem
dosen.java:31: warning: [rawtypes] found raw type: DefaultComboBoxModel
DefaultComboBoxModel classes = new DefaultComboBoxModel(new String[]{"Information System", "Hospitality", "Law", "Management", "Accounting"});
^
missing type arguments for generic class DefaultComboBoxModel<E>
where E is a type-variable:
E extends Object declared in class DefaultComboBoxModel
String Class = ""; Change this variable's name. Because of this line
Class.forName("com.mysql.jdbc.Driver");
forName method calling from a String instance. Bu there is not a method named forName in String.
I am new to java and I am trying to build a simple project that connects
to database then display it on JTable with MouseClick event. When i click in the row to transfer its content to JTextFields but it returns NullPointerException in line 225. Here's the full code of my project:
package Dbase;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
#SuppressWarnings("serial")
public class MainForm extends JFrame {
Connection con;
Statement stmt;
ResultSet rs;
PreparedStatement pstmt;
#SuppressWarnings("rawtypes")
Vector columnNames = new Vector();
#SuppressWarnings("rawtypes")
Vector data = new Vector();
//JTable table;
private JPanel gui;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainForm frame = new MainForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
setLookAndFeel();
setSize(800,500);
gui = new JPanel();
gui.setLayout(new BorderLayout(5, 5));
setContentPane(gui);
DBConnect();
initComponents();
tbData();
}
public void DBConnect(){
try{
String host = "jdbc:mysql://localhost:3306/birthdb";
String uName = "admin";
String uPass = "46m1n";
// connection to mysql database
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM childinfo";
rs = stmt.executeQuery(sql);
}
catch(SQLException er){
JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
}
}
private void initComponents(){
//child's information
JLabel lblfirstName = new JLabel("FirstName", JLabel.RIGHT);
JLabel lbllastName = new JLabel("LastName", JLabel.RIGHT);
JLabel lblmiddleName = new JLabel("MiddleName", JLabel.RIGHT);
JLabel lblbirthDate = new JLabel("BirthDate",JLabel.RIGHT);
JLabel lblgender = new JLabel("Gender",JLabel.RIGHT);
JLabel lblbirthType = new JLabel("BirthType", JLabel.RIGHT);
JLabel lblmultiBirth = new JLabel("If Multiple Birth, Child Was", JLabel.RIGHT);
JLabel lblbirthOrder = new JLabel("BirthOrder", JLabel.RIGHT);
JLabel lblbirthWeight = new JLabel("BirthWeight",JLabel.RIGHT);
JLabel lblregistry = new JLabel("Registry",JLabel.RIGHT);
JTextField txtfirstName = new JTextField();
JTextField txtlastName = new JTextField();
JTextField txtmiddleName = new JTextField();
JTextField txtbirthDate = new JTextField();
JTextField txtgender = new JTextField();
JTextField txtbirthType = new JTextField();
JTextField txtmultiBirth = new JTextField();
JTextField txtbirthOrder = new JTextField();
JTextField txtbirthWeight = new JTextField();
JTextField txtregistry = new JTextField();
JButton newData = new JButton("New");
JButton updateData = new JButton("Update");
JButton deleteData = new JButton("Delete");
JButton printData = new JButton("Print");
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//trial menu
menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menuBar.add(menu);
//trial menu item
menuItem = new JMenuItem("Quit");
menuItem.setMnemonic(KeyEvent.VK_Q);
menu.add(menuItem);
//trial row panel
JPanel row = new JPanel(new GridLayout(6,4,5,10));
row.add(lblregistry);
txtregistry.setEditable(false);
row.add(txtregistry);
row.add(lblfirstName);
txtfirstName.setEditable(false);
row.add(txtfirstName);
row.add(lbllastName);
txtlastName.setEditable(false);
row.add(txtlastName);
row.add(lblmiddleName);
txtmiddleName.setEditable(false);
row.add(txtmiddleName);
row.add(lblgender);
txtgender.setEditable(false);
row.add(txtgender);
row.add(lblbirthDate);
txtbirthDate.setEditable(false);
row.add(txtbirthDate);
row.add(lblbirthType);
txtbirthType.setEditable(false);
row.add(txtbirthType);
row.add(lblmultiBirth);
txtmultiBirth.setEditable(false);
row.add(txtmultiBirth);
row.add(lblbirthOrder);
txtbirthOrder.setEditable(false);
row.add(txtbirthOrder);
row.add(lblbirthWeight);
txtbirthWeight.setEditable(false);
row.add(txtbirthWeight);
gui.add(row, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new BorderLayout(3,3));
gui.add(buttonPanel,BorderLayout.WEST);
JPanel btn = new JPanel(new GridLayout(6,1,5,5));
btn.add(newData);
btn.add(updateData);
btn.add(deleteData);
btn.add(printData);
buttonPanel.add(btn);
}
#SuppressWarnings("unchecked")
private void tbData(){
try{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT ChildID, FirstName, LastName, MiddleName FROM childinfo";
rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for(int i = 1; i <= columns; ++i){
columnNames.add(md.getColumnName(i));
}
while(rs.next()){
#SuppressWarnings("rawtypes")
Vector row = new Vector(columns);
for(int i = 1; i<= columns; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
stmt.close();
}
catch(SQLException e){
JOptionPane.showMessageDialog(MainForm.this, e.getMessage());
}
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table = new JTable(model){
#SuppressWarnings({ "rawtypes" })
public Class getColumnClass(int column){
for(int row = 0; row < getRowCount(); row++){
Object o = getValueAt(row,column);
if(o != null){
return o.getClass();
}
}
return Object.class;
}
};
table.setRowSelectionAllowed(true);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
int row = table.getSelectedRow();
try{
String dataClick = (table.getModel().getValueAt(row, 0).toString());
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM childinfo WHERE ChildID='"+dataClick+"'";
rs = stmt.executeQuery(sql);
if(rs.next()){
txtregistry.setText(Integer.toString(rs.getInt("ChildID"))); *this is where i get the error*
txtfirstName.setText(rs.getString("FirstName"));
txtlastName.setText(rs.getString("LastName"));
txtmiddleName.setText(rs.getString("MiddleName"));
txtgender.setText(rs.getString("Gender"));
txtbirthDate.setText(rs.getString("BirthDate"));
txtbirthType.setText(rs.getString("BirthType"));
txtmultiBirth.setText(rs.getString("IfMultiBirth"));
txtbirthOrder.setText(Integer.toString(rs.getInt("BirthOrder")));
txtbirthWeight.setText(Integer.toString(rs.getInt("BirthWeight")));
}
}
catch(SQLException er){
JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
gui.add(scrollPane, BorderLayout.CENTER);
}
private void setLookAndFeel(){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception ee){
}
}
JTextField txtfirstName;
JTextField txtlastName;
JTextField txtmiddleName;
JTextField txtbirthDate;
JTextField txtgender;
JTextField txtbirthType;
JTextField txtmultiBirth;
JTextField txtbirthOrder;
JTextField txtbirthWeight;
JTextField txtregistry;
JTable table;
Kindly help me to fix the problem.
You're shadowing all the variable names for the components used in your class. E.g. Replace
JTextField txtfirstName = new JTextField();
with
txtfirstName = new JTextField();
This was working fine before, but I set the project down for a while and when I decided to take it up again, the panels do not show up in the frame. I have tried many different possible resolutions and spent days trying to fix it with nothing working. Does anyone see what might be causing the frame to display empty?
// imports
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class login extends JFrame {
// create variables
JFrame login = new JFrame();
private JTextField userTF;
private JPasswordField passwordField;
private JLabel userL;
private JLabel passL;
private JLabel updateOne;
private JLabel updateTwo;
private JLabel error;
private JLabel welcome;
private JButton submit;
String password = "";
String username = "";
JPanel panel1 = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel(new GridBagLayout());
JPanel panel3 = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// constructor
public login(){
// set and add all GUI components
welcome = new JLabel("PLA LOGIN");
c.gridx = 0;
c.gridy = 0;
panel1.add(welcome, c);
userL = new JLabel("Username: ");
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.WEST;
panel2.add(userL, c);
userTF = new JTextField(15);
userTF.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray));
userTF.setOpaque(false);
c.gridx = 0;
c.gridy = 2;
panel2.add(userTF, c);
passL = new JLabel("Password: ");
c.gridx = 0;
c.gridy = 3;
panel2.add(passL, c);
passwordField = new JPasswordField(15);
passwordField.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray));
passwordField.setOpaque(false);
c.gridx = 0;
c.gridy = 4;
panel2.add(passwordField, c);
submit = new JButton("Sign In");
c.gridx = 0;
c.gridy = 5;
c.insets = new Insets(10, 0, 0, 0); // add top padding
c.ipadx = 93;
panel2.add(submit, c);
updateOne = new JLabel("MySQL JDBC Driver Registered!");
c.gridx = 0;
c.gridy = 4;
panel3.add(updateOne,c );
updateOne.setVisible(false);
updateTwo = new JLabel("You are now connected to your database.");
c.gridx = 1;
c.gridy = 4;
panel3.add(updateTwo);
updateTwo.setVisible(false);
login.add(panel1);
login.add(panel2);
login.add(panel3);
// call text handler constructor to complete correct actions depending on user action
TextHandler handler = new TextHandler();
userTF.addActionListener(handler);
passwordField.addActionListener(handler);
submit.addActionListener(handler);
}
// inner class TextHandler
private class TextHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
// check if user hit to submit with userTF, passwordField, or submit button
if(e.getSource() == userTF){
username = e.getActionCommand();
} else if(e.getSource() == passwordField){
password = e.getActionCommand();
} else if(e.getSource() == submit){
// try to access mysql driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException s) {
error = new JLabel("Where is your MySQL JDBC Driver?"); // if driver not found output label
s.printStackTrace();
c.gridx = 0;
c.gridy = 3;
add(error, c);
return;
} // end try
updateOne.setVisible(true); // make label visible
Connection connection = null;
// try to login to mysql database
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost/PLA", username, password); // fetch username and password
} catch (SQLException s) {
error = new JLabel("Connection Failed! Check output console"); // error if login failed
s.printStackTrace();
c.gridx = 0;
c.gridy = 3;
add(error, c);
return;
} // end try
// if login was successful output label
if (connection != null) {
updateTwo.setVisible(true);
} else {
error = new JLabel("Failed to make connection!"); // if login failed, output label
c.gridx = 0;
c.gridy = 3;
add(error, c);
} // end if
} // end submit else if
} // end action performed
} // end private class text handler } // end class login
I'm not sure if this is you intention, but it's weird to me...
First, you declare a class that extends from JFrame...
public class login extends JFrame {
Then you declare a instance variable of the same class...
JFrame login = new JFrame();
You than add all your components to this instance...
login.add(panel1);
login.add(panel2);
login.add(panel3);
Now, I can't see how you are using this, but I imagine you are doing something like...
login login = new login()
login.setVisible(true);
Which basically, doesn't show anything...
Instead. Rather than extending from JFrame, I would extend from JPanel and drop the login instance variable.
Create a instance of login and then add it to a JFrame instance that you have created...
I also recommend that you take a look at Code Conventions for the Java Programming Language
I'm working on this application and I just can't get the GUI to display properly. I'm using FlowLayout, and everything just looks all jumbled (any other layout looks even worse). If there were just some way to add a horizontal rule between sections, that would work, but nothing I tried works.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class ConnectToDB implements ActionListener {
public static void main(String[] args){
//GUI STUFF
//constants
final int windowX = 640; //pixels
final int windowY = 655; //pixels
final int fieldX = 20; //characters
final FlowLayout LAYOUT_STYLE = new FlowLayout();
//window
JFrame window = new JFrame("Mike's MySQL GUI Client");
//Connection Details
JLabel enterInfo = new JLabel("Enter Connection Details: ");
JLabel driver = new JLabel("Database Driver: ");
JTextField driverText = new JTextField(fieldX);
JLabel dburl = new JLabel("Database URL: ");
JTextField dburlText = new JTextField(fieldX);
JLabel dbuser = new JLabel("Username: ");
JTextField dbuserText = new JTextField(fieldX);
JLabel dbpass = new JLabel("Password: ");
JTextField dbpassText = new JTextField(fieldX);
//Enter a SQL Command
JLabel enterSQL = new JLabel("Enter a SQL Command:");
JTextArea enterSQLText = new JTextArea(10, 30);
//Connection Status and Command Buttons
JLabel connectionStatus = new JLabel ("No Connection Now");
JButton connectButton = new JButton("Connect");
JButton executeButton = new JButton("Execute SQL Command");
JButton clearCommandButton = new JButton("Clear Command");
//SQL Execution Result
JLabel executionResult = new JLabel("SQL Execution Result:");
JButton clearResultsButton = new JButton("Clear Results");
JTextArea executionResultText = new JTextArea(20, 50);
//Configure GUI
window.setSize(windowX, windowY);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
driverText.setEditable(false);
dburlText.setEditable(false);
dbuserText.setEditable(false);
dbpassText.setEditable(false);
executionResultText.setEditable(false);
//Register Event Listeners
connectButton.addActionListener(null);
executeButton.addActionListener(null);
clearCommandButton.addActionListener(null);
clearResultsButton.addActionListener(null);
//Construct Container
Container c = window.getContentPane();
c.setLayout(LAYOUT_STYLE);
c.add(enterInfo);
c.add(driver);
c.add(driverText);
c.add(dburl);
c.add(dburlText);
c.add(dbuser);
c.add(dbuserText);
c.add(dbpass);
c.add(dbpassText);
c.add(connectionStatus);
c.add(connectButton);
c.add(enterSQL);
c.add(enterSQLText);
c.add(executeButton);
c.add(clearCommandButton);
c.add(new JSeparator(SwingConstants.VERTICAL));
c.add(executionResult);
c.add(clearResultsButton);
c.add(executionResultText);
window.setVisible(true);//END GUI STUFF
//DB Connection details
System.out.println("Attempting to connect to database...");
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "project3";
String DBdriver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "OMGnpw=-0";
driverText.setText(DBdriver);
dburlText.setText(url);
dbuserText.setText(userName);
dbpassText.setText(password);
try
{
//Connect to DB and notify user
Class.forName(DBdriver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
/*>>>>>>Do everything you need to do while connected to DB<<<<<<*/
//HOW TO EXECUTE A STATEMENT AND PRINT IT
//Create a statement
Statement statement = conn.createStatement();
//Execute a statement
ResultSet resultSet = statement.executeQuery("SELECT * FROM riders");
//Process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
System.out.printf("%20s\t", metaData.getColumnName(i));
}
System.out.println();
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
System.out.printf("%20s\t", resultSet.getObject(i));
}
System.out.println();
}
/*>>>>>>Finish DB activities<<<<<<*/
//Disconnect from DB
conn.close();
System.out.printf("Disconnected from database");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e){
System.out.println("Button Works!");
}
}
I may need to use a different layout, but FlowLayout is the only one I'm familiar with. Can anyone suggest an easy fix?
Try a box layout. And add some panels to it. Make the panels flow layout and put a pair of label and textfield in each panel
|-----container with box layout-----|
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]sqltextfields]
panel[[flow]buttons]
|-----------------------------------|
and near the bottom put your sql textfields and buttons
http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
So, we a little playing around you can achieve this...
This uses a combination of card layout, border layout, grid bag layout and flow layout
Connection Pane...
Query Pane
public class TestLayout11 {
public static void main(String[] args) {
new TestLayout11();
}
public TestLayout11() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SQLPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class SQLPane extends JPanel {
private ConnectionPane connectionPane;
private QueryPane queryPane;
public SQLPane() {
setLayout(new CardLayout(8, 8));
connectionPane = new ConnectionPane();
connectionPane.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Perform login...
((CardLayout) getLayout()).show(SQLPane.this, "query");
}
});
queryPane = new QueryPane();
add(connectionPane, "connection");
add(queryPane, "query");
((CardLayout) getLayout()).show(this, "connection");
}
}
public static class ConnectionPane extends JPanel {
protected static final int FIELD_CHARACTER_WIDTH = 20; //characters
private JButton connectButton;
private JTextField driverText;
private JTextField dburlText;
private JTextField dbuserText;
private JTextField dbpassText;
public ConnectionPane() {
JLabel enterInfo = new JLabel("Enter Connection Details: ");
JLabel driver = new JLabel("Database Driver: ");
driverText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dburl = new JLabel("Database URL: ");
dburlText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dbuser = new JLabel("Username: ");
dbuserText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dbpass = new JLabel("Password: ");
dbpassText = new JTextField(FIELD_CHARACTER_WIDTH);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = 2;
gbc.insets = new Insets(2, 2, 2, 2);
add(enterInfo, gbc);
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = 1;
gbc.gridy++;
add(driver, gbc);
gbc.gridy++;
add(dburl, gbc);
gbc.gridy++;
add(dbuser, gbc);
gbc.gridy++;
add(dbpass, gbc);
gbc.gridx++;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.WEST;
add(driverText, gbc);
gbc.gridy++;
add(dburlText, gbc);
gbc.gridy++;
add(dbuserText, gbc);
gbc.gridy++;
add(dbpassText, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 2;
connectButton = new JButton("Connect");
add(connectButton, gbc);
}
public void addActionListener(ActionListener listener) {
connectButton.addActionListener(listener);
}
public void removeActionListener(ActionListener listener) {
connectButton.removeActionListener(listener);
}
}
public static class QueryPane extends JPanel {
private JTextArea enterSQLText;
public QueryPane() {
JLabel enterSQL = new JLabel("Enter a SQL Command:");
enterSQLText = new JTextArea(10, 30);
JButton clearResultsButton = new JButton("Clear Results");
JButton executeButton = new JButton("Execute SQL Command");
setLayout(new BorderLayout());
add(enterSQL, BorderLayout.NORTH);
add(new JScrollPane(enterSQLText));
JPanel buttons = new JPanel();
buttons.add(executeButton);
buttons.add(clearResultsButton);
add(buttons, BorderLayout.SOUTH);
executeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute query...
String text = enterSQLText.getText();
enterSQLText.setText("I've being executed....");
}
});
clearResultsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
enterSQLText.setText(null);
}
});
}
}
}