I have this code in Java Swings which creates 2 frames.The first frame contains 4 text fields(roll no,name,class,section) leaving the text fields blank I click on the search button in the 1st frame,another frame opens with all my table records in the database.Once I select a record(or the row) all the details of it appear in the 1st frame,i.e roll no,class,name and section get populated.
Right now I am using the search button to go to the next frame.What should I do so that the action is performed once I click on the roll no. text field instead of the search button?
This is the code:
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.Vector;
import java.awt.event.*;
public class barcoder1 implements ActionListener{
JFrame frame,frame1;
JTextField textbox,textbox1,textbox2,textbox3,textbox4,textbox5,textbox6,textbox7,textbox8;
JLabel label,label1,label2,label3,label4,label5,label6,label7,label8;
JButton button;
JPanel panel;
static JTable table;
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String userName = "root";
String password = "root";
String[] columnNames = {"Roll No", "Name", "Class", "Section"};
public void createUI()
{
frame = new JFrame("Database Search Result");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
textbox = new JTextField();
textbox.setBounds(120,30,150,20);
label=new JLabel("Roll No.");
label.setBounds(10, 30, 100, 20);
textbox1 = new JTextField();
textbox1.setBounds(120,50,150,20);
label1=new JLabel("Name");
label1.setBounds(10, 50, 100, 20);
textbox2 = new JTextField();
textbox2.setBounds(120,70,150,20);
label2=new JLabel("Class");
label2.setBounds(10, 70, 100, 20);
textbox3 = new JTextField();
textbox3.setBounds(120,90,150,20);
label3=new JLabel("Section");
label3.setBounds(10, 90, 100, 20);
button = new JButton("search");
button.setBounds(120,230,150,20);
button.addActionListener(this);
frame.add(textbox);
frame.add(label);
frame.add(textbox1);
frame.add(label1);
frame.add(textbox2);
frame.add(label2);
frame.add(textbox3);
frame.add(label3);
frame.add(button);
frame.setVisible(true);
frame.setSize(500, 400);
}
public void actionPerformed(ActionEvent ae)
{
button = (JButton)ae.getSource();
System.out.println("Showing Table Data.......");
showTableData();
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
//frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
final JTable table = new JTable(model);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
System.out.println("Selecte table row = " + row);
if (row != -1) {
int modelRow = table.convertRowIndexToModel(row);
System.out.println("Selecte model row = " + row);
Vector data = (Vector) ((DefaultTableModel) table.getModel()).getDataVector().get(modelRow);
textbox.setText(data.get(0).toString());
textbox1.setText(data.get(1).toString());
textbox2.setText(data.get(2).toString());
textbox3.setText(data.get(3).toString());
}
}
});
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
if (table.getSelectedRow() != -1) {
SwingUtilities.getWindowAncestor(table).dispose();
}
}
}
});
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
String textvalue = textbox.getText();
String roll= "";
String name= "";
String cl = "";
String sec = "";
try
{
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, userName, password);
//String sql = "select * from student where rollno = "+textvalue;
String sql="select * from student";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i =0;
while(rs.next())
{
roll = rs.getString("rollno");
name = rs.getString("name");
cl = rs.getString("class");
sec = rs.getString("section");
model.addRow(new Object[]{roll, name, cl, sec});
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400,300);
}
public static void main(String args[])
{
barcoder1 sr = new barcoder1();
sr.createUI();
}
}
Related
I'm trying to add rows to my table whenever the user selects yes when they are asked to add the product to the cart or not with the help of JOptionPane Confirm Dialog. My code is as follows:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Home {
final static int WINDOW_WIDTH = 500;
final static int WINDOW_HEIGHT = 200;
JFrame window;
public Home() {
window = new JFrame();
window.setTitle("Home");
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel title = new JLabel("Please select a book for more information", JLabel.CENTER);
title.setHorizontalTextPosition(JLabel.CENTER);
Font plainFont = new Font("Serif", 0, 24);
title.setFont(plainFont);
title.setBounds(180, 230, 97, 29);
//====================================================================//
String [] bookStrings = {"[Select a book]", "The Host", "Ruby", "Divergent", "The Secret Garden", "Hunger Games"};
JComboBox bookList = new JComboBox(bookStrings);
//====================================================================//
JLabel bookinfo = new JLabel();
//====================================================================//
JButton search = new JButton("Search");
search.setHorizontalTextPosition(JButton.CENTER);
JButton cart = new JButton("Show Cart");
search.setHorizontalTextPosition(JButton.CENTER);
JButton exit = new JButton("Exit");
search.setHorizontalTextPosition(JButton.CENTER);
JTable cartTable;
String[] columns = {"Book Name","Author", "Quantity", "Price"};
String [][] data = {};
cartTable = new JTable(data, columns);
cartTable.setPreferredScrollableViewportSize(new Dimension(450, 63));
cartTable.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane(cartTable);
//====================================================================//
search.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (bookList.getSelectedIndex() == 1) {
int reply = JOptionPane.showConfirmDialog(null,
"<html>Title: The Host <br> Author: Stephenie Meyer <br> Price: 110 AED <br> " +
"\n Synopsis: The Host is a romance novel by Stephenie Meyer. The book is about Earth, " +
"\n in a post apocalyptic time, being invaded by a parasitic alien race, known as \"Souls\", and " +
"\n follows one Soul's predicament when the consciousness of her human host refuses to co-operate " +
"\n with the takeover of her body."
+ "\n \n Would you like to add this to cart?", "Book Details", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION){
String [][] data = {{"The Host", "Stephenie Meyer", "2", "110"}};
DefaultTableModel model = (DefaultTableModel)(cartTable.getModel());
model.addRow(data);
}
else {
JOptionPane.showMessageDialog(null, "GOODBYE");
}
}
});
cart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Cart();
window.setVisible(false);
}
});
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//====================================================================//
JPanel panel;
panel = new JPanel();
panel.add(title);
panel.add(bookList);
panel.add(search);
panel.add(bookinfo);
panel.add(cart);
panel.add(exit);
panel.add(jps);
window.add(panel);
window.setVisible(true);
}
}
However I'm getting this error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JTable$1 cannot be cast to javax.swing.table.DefaultTableModel
Can someone help me with where I'm going wrong? Thank You.
cartTable = new JTable(data, columns);
uses an anonymous AbstractTableModel if I remember correctly.
Use instead:
cartTable = new JTable(new DefaultTableModel(data, columns));
DefaultTableModel fires miscellaneous change events and handles dynamic data.
being new to programming, i'm having a slight issue resizing the text fields I've added to the JPanel. While I could go the route of creating individual panels with their own text field, I though it would be better to add all the components into one panel. Part of my overall idea is to have my add button reference the panel, containing the text fields, to add more text fields on the tracker for users to fill out, and while I can get the fields to display when I implement the setBounds method on my panel object, i'm having tough time figuring out how resize them in the panel itself. And if you have any other advice on my overall structure, I welcome it.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class UI {
JFrame frame;
JLabel Title,Name, CheckOut, CheckIn, Email;
JTextField NameField,CheckOutField, CheckInField, EmailField;
JButton Add, Delete;
JPanel buttons, textfields, primary;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UI window = new UI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public UI(){
design();
}
private void design(){
frame = new JFrame("Form 48 Tracker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 750, 400);
frame.getContentPane().setLayout(null);
Title = new JLabel();
Title.setText("Form 48 Tracker");
Title.setFont(new Font("Calibri", Font.PLAIN, 28));
Title.setBounds(233, 11, 200, 75);
frame.getContentPane().add(Title);
Title.setForeground(Color.BLACK);
Name = new JLabel();
Name.setText("Name");
Name.setFont(new Font("Calibri", Font.PLAIN, 15));
Name.setBounds(50, 80, 128, 20);
frame.getContentPane().add(Name);
Name.setForeground(Color.BLACK);
CheckOut = new JLabel();
CheckOut.setText("Check Out Date");
CheckOut.setFont(new Font("Calibri", Font.PLAIN, 15));
CheckOut.setBounds(200, 80, 128, 20);
frame.getContentPane().add(CheckOut);
CheckOut.setForeground(Color.BLACK);
CheckIn = new JLabel();
CheckIn.setText("Check In Date");
CheckIn.setFont(new Font("Calibri", Font.PLAIN, 15));
CheckIn.setBounds(350, 80, 128, 20);
frame.getContentPane().add(CheckIn);
CheckIn.setForeground(Color.BLACK);
Email = new JLabel();
Email.setText("Email");
Email.setFont(new Font("Calibri", Font.PLAIN, 15));
Email.setBounds(500, 80, 128, 20);
frame.getContentPane().add(Email);
Email.setForeground(Color.BLACK);
Add = new JButton("Add");
buttons = new JPanel();
buttons.add(Add);
buttons.setBounds(200, 270, 157, 50); //x , y , width , height//
frame.getContentPane().add(buttons);
Add.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
Delete = new JButton("Delete");
buttons = new JPanel();
buttons.add(Delete);
buttons.setBounds(605, 101, 128, 50);
frame.getContentPane().add(buttons);
primary = new JPanel();
NameField = new JTextField();
CheckOutField = new JTextField();
CheckInField = new JTextField();
EmailField = new JTextField();
primary.add(NameField);
primary.add(CheckOutField);
primary.add(CheckInField);
primary.add(EmailField);
primary.setBounds(50, 110, 128, 20);
frame.getContentPane().add(primary);
}
}
Let's concentrate on the code that's causing the problem, and only that code. I've created a minimal example program, one that has enough code to compile and run, and that demonstrates the problem, but that has no unnecessary code:
import javax.swing.*;
public class UiFoo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null); // **** no!! ****
JPanel primary = new JPanel();
JTextField NameField = new JTextField();
JTextField CheckOutField = new JTextField();
JTextField CheckInField = new JTextField();
JTextField EmailField = new JTextField();
primary.add(NameField);
primary.add(CheckOutField);
primary.add(CheckInField);
primary.add(EmailField);
primary.setBounds(50, 110, 128, 20);
frame.getContentPane().add(primary);
frame.setSize(600, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
So, if you run this code, you'll see 4 very small JTextFields. Why are they so small? Because you've not set the columns property for the JTextFields, and so they default to columns size 0 and show up like so:
So it's better if you can give the JTextField a columns property so that they have some width, e.g., make this change:
JPanel primary = new JPanel();
int columns = 8;
JTextField NameField = new JTextField(columns);
JTextField CheckOutField = new JTextField(columns);
JTextField CheckInField = new JTextField(columns);
JTextField EmailField = new JTextField();
But this just shows one JTextField, and cuts off the bottom as well:
Why? Because you're artificially constraining the size of the containing JPanel, primary via:
primary.setBounds(50, 110, 128, 20);
This containing JPanel is only 128 pixels wide by 20 pixels high, meaning that it won't even display one JTextField well.
One solution is to use a mix of layout managers and JPanels as well as a JScrollPane to allow for a grid of JPanels to be added, something like so (try it out!):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class UiFoo2 extends JPanel {
JPanel singleColumnPanel = new JPanel(new GridLayout(0, 1, 2, 2));
public UiFoo2() {
JButton addButton = new JButton("Add");
addButton.addActionListener(e -> {
JPanel rowPanel = new JPanel(new GridLayout(1, 4, 2, 2));
for (int i = 0; i < 4; i++) {
rowPanel.add(new JTextField(8));
}
singleColumnPanel.add(rowPanel);
singleColumnPanel.revalidate();
singleColumnPanel.repaint();
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
JPanel labelPanel = new JPanel(new GridLayout(1, 4, 2, 2));
labelPanel.add(new JLabel("Name", SwingConstants.CENTER));
labelPanel.add(new JLabel("Check Out Date", SwingConstants.CENTER));
labelPanel.add(new JLabel("Check In Date", SwingConstants.CENTER));
labelPanel.add(new JLabel("Email", SwingConstants.CENTER));
singleColumnPanel.add(labelPanel);
JPanel containerPanel = new JPanel(new BorderLayout(5, 5));
containerPanel.add(singleColumnPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(containerPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new Dimension(650, 400));
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
UiFoo2 mainPanel = new UiFoo2();
JFrame frame = new JFrame("UiFoo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
This will create a row JPanel that holds four JTextFields that get added to the JScrollPane when the add JButton is pressed, and looks like so:
but we still can do better. Why not instead create a class to hold a row of data, something like so:
import java.util.Date;
public class Form48Customer {
private String name;
private Date checkIn;
private Date checkOut;
private String Email;
public Form48Customer(String name, Date checkIn, Date checkOut, String email) {
this.name = name;
this.checkIn = checkIn;
this.checkOut = checkOut;
Email = email;
}
public Date getCheckIn() {
return checkIn;
}
public void setCheckIn(Date checkIn) {
this.checkIn = checkIn;
}
public Date getCheckOut() {
return checkOut;
}
public void setCheckOut(Date checkOut) {
this.checkOut = checkOut;
}
public String getName() {
return name;
}
public String getEmail() {
return Email;
}
// should override hashCode and equals here
}
and then create a JTable complete with custom model to display objects of this type, and then display them in the GUI. This is much cleaner, more flexible, and extendable. Something like so:
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.table.*;
#SuppressWarnings("serial")
public class Form48TrackerPanel extends JPanel {
public static final String TITLE = "Form 48 Tracker";
private static final String DATE_FORMAT_TXT = "MM/dd/yyyy";
private Form48TableModel model = new Form48TableModel();
private JTable table = new JTable(model);
private JButton addButton = new JButton("Add");
private JButton deleteButton = new JButton("Delete");
private JButton exitButton = new JButton("Exit");
public Form48TrackerPanel() {
final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_TXT);
TableCellRenderer dateRenderer = new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if( value instanceof Date) {
value = dateFormat.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
};
table.getColumnModel().getColumn(1).setCellRenderer(dateRenderer);
table.getColumnModel().getColumn(2).setCellRenderer(dateRenderer);
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 28f));
addButton.addActionListener(new AddListener());
addButton.setMnemonic(KeyEvent.VK_A);
deleteButton.addActionListener(new DeleteListener());
deleteButton.setMnemonic(KeyEvent.VK_D);
exitButton.addActionListener(new ExitListener());
exitButton.setMnemonic(KeyEvent.VK_X);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(exitButton);
setPreferredSize(new Dimension(800, 500));
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BorderLayout(ebGap, ebGap));
add(titleLabel, BorderLayout.PAGE_START);
add(new JScrollPane(table), BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
model.addRow(new Form48Customer("John Smith", new Date(), new Date(), "JSmith#Yahoo.com"));
model.addRow(new Form48Customer("Fred Flinstone", new Date(), new Date(), "FFlinstone#GMail.com"));
}
private class AddListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
AddForm48Panel addFormPanel = new AddForm48Panel();
int result = JOptionPane.showConfirmDialog(Form48TrackerPanel.this,
addFormPanel, "Add Customer", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
Form48Customer customer = addFormPanel.getForm48Customer();
model.addRow(customer);
}
}
}
private class DeleteListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO *** finish this code ***
}
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(Form48TrackerPanel.this);
win.dispose();
}
}
private static void createAndShowGui() {
Form48TrackerPanel mainPanel = new Form48TrackerPanel();
JFrame frame = new JFrame(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class AddForm48Panel extends JPanel {
private static final int TFIELD_COLS = 10;
private static final String DATE_FORMAT_TXT = "MM/dd/yyyy";
private static final Format DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_TXT);
private static final Insets INSETS = new Insets(5, 5, 5, 5);
private JTextField nameField = new JTextField(TFIELD_COLS);
private JFormattedTextField checkOutDateField = new JFormattedTextField(DATE_FORMAT);
private JFormattedTextField checkInDateField = new JFormattedTextField(DATE_FORMAT);
private JTextField emailField = new JTextField(TFIELD_COLS);
private JComponent[] fields = {nameField, checkOutDateField, checkInDateField, emailField};
private String[] labels = {"Name", "Check Out Date", "Check In Date", "Email"};
public AddForm48Panel() {
InputVerifier verifier = new DateFieldVerifier();
checkInDateField.setInputVerifier(verifier);
checkOutDateField.setInputVerifier(verifier);
setLayout(new GridBagLayout());
for (int i = 0; i < fields.length; i++) {
add(new JLabel(labels[i] + ":"), createGbc(0, i));
add(fields[i], createGbc(1, i));
}
}
public String getName() {
return nameField.getText();
}
public String getEmail() {
return emailField.getText();
}
public Date getCheckOut() {
return (Date) checkOutDateField.getValue();
}
public Date getCheckIn() {
return (Date) checkInDateField.getValue();
}
public Form48Customer getForm48Customer() {
String name = getName();
Date checkOut = getCheckOut();
Date checkIn = getCheckIn();
String email = getEmail();
return new Form48Customer(name, checkIn, checkOut, email);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = INSETS;
gbc.anchor = x == 0 ? GridBagConstraints.WEST :GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private class DateFieldVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
if (input instanceof JFormattedTextField) {
JFormattedTextField ftf = (JFormattedTextField)input;
AbstractFormatter formatter = ftf.getFormatter();
if (formatter != null) {
String text = ftf.getText();
try {
formatter.stringToValue(text);
return true;
} catch (ParseException pe) {
return false;
}
}
}
return true;
}
#Override
public boolean shouldYieldFocus(JComponent input) {
boolean verify = verify(input);
if (!verify) {
String message = "Enter a valid date, e.g.: 01/05/2017";
String title = "Invalid Date Format";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(input, message, title, type);
}
return verify;
}
}
}
#SuppressWarnings("serial")
class Form48TableModel extends DefaultTableModel {
private static final String[] COL_NAMES = {"Name", "Check Out Date", "Check In Date", "Email"};
public Form48TableModel() {
super(COL_NAMES, 0);
}
public void addRow(Form48Customer customer) {
Object[] rowData = {
customer.getName(),
customer.getCheckOut(),
customer.getCheckIn(),
customer.getEmail()
};
addRow(rowData);
}
public Form48Customer getRow(int row) {
String name = (String) getValueAt(row, 0);
Date checkIn = (Date) getValueAt(row, 1);
Date checkOut = (Date) getValueAt(row, 2);
String email = (String) getValueAt(row, 3);
return new Form48Customer(name, checkIn, checkOut, email);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 1:
return Date.class;
case 2:
return Date.class;
default:
break;
}
return super.getColumnClass(columnIndex);
}
}
Which would look like:
I work on my projekt where i need to copy one row from JTable into another JTable, the second JTable should be only one-row table. I created mouselistener to first JTable where on doubleclick it should copy row and insert it into another JTable but it doesn't work correctly, any ideas how to solve it? i Get the data from database in first table. with code:
public void cputable() {
try {
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test","postgres","postgres");
stat = conn.createStatement();
result = stat.executeQuery("SELECT name,bus_speed,socket,cores,chipset,price*1.3 FROM CPU");
cputable.setModel(DbUtils.resultSetToTableModel(result));
result.close();
stat.close();
}
catch (Exception e){
e.printStackTrace();
}
}
and here is the code which i try to copy row:
cputable.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable cputable =(JTable) me.getSource();
int row = cputable.getSelectedRow();
int col = cputable.getColumnCount();
if (me.getClickCount() == 2) {
cputablebottom.repaint();
for(int i = 0; i < col; i++) {
DefaultTableModel model = (DefaultTableModel) cputable.getModel();
List<String>list = new ArrayList<String>();
list.add( cputable.getValueAt(row, i).toString());
model.addRow(list.toArray());
cputablebottom.setModel(model);
}
Result before and after:
EDIT:
I remake a bit in the code and now it copy the whole list instead of only one row.
cputable.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable cputable =(JTable) me.getSource();
int row = cputable.getSelectedRow();
int col = cputable.getColumnCount();
if (me.getClickCount() == 2) {
cputablebottom.repaint();
DefaultTableModel model1 = (DefaultTableModel) cputable.getModel();
List<String>list = new ArrayList<String>();
model1.addRow(list.toArray());
for(int i = 0; i < col; i++) {
list.add( cputable.getValueAt(row, i).toString());
cputablebottom.setModel(model1);
System.out.println(model1);
System.out.println(list);
}
cputablebottom.setModel(model1);
I've not tried this, but...
DefaultTableModel model1 = (DefaultTableModel) cputable.getModel();
Vector data = model1.getDataVector();
Object rowObj = data.get(row);
Vector newData = new Vector(1);
newData.add(rowObj);
DefaultTableModel model2 = (DefaultTableModel) cputablebottom.getModel();
model2.setRowCount(0);
model2.addRow(newData);
This should preserve the column information of the second table.
Alternatively, you could create a new DefaultTableModel, but you'd have to reconfigure the column information each time
What I suggest you do is have a read of the JavaDocs for DefaultTableModel
Tested example
I don't use DefaultTableModel often, preferring to put an actual object in each row, which I can then define how it is displayed, which would make it generally simpler, but, if a DefaultTableModel is all you have...
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable top;
private JTable bottom;
public TestPane() {
setLayout(new GridLayout(2, 0));
String[][] rowData = new String[10][10];
for (int row = 0; row < 10; row++) {
String[] data = new String[10];
for (int col = 0; col < 10; col++) {
data[col] = row + "x" + col;
}
rowData[row] = data;
}
String[] names = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
DefaultTableModel model = new DefaultTableModel(rowData, names);
top = new JTable(model);
add(new JScrollPane(top));
DefaultTableModel emptyModel = new DefaultTableModel(new String[10][10], names);
bottom = new JTable(emptyModel);
add(new JScrollPane(bottom));
top.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
int row = top.rowAtPoint(e.getPoint());
if (row > -1) {
DefaultTableModel topModel = ((DefaultTableModel)top.getModel());
DefaultTableModel bottomModel = ((DefaultTableModel)bottom.getModel());
bottomModel.setRowCount(1);
for (int col = 0; col < topModel.getColumnCount(); col++) {
bottomModel.setValueAt(topModel.getValueAt(row, col), 0, col);
}
}
}
}
});
}
}
}
1.Code of 1st class where we are making our table-->
Sell.java
public class Sell extends JFrame {
public static void main(String args[]) {
new Sell();
}
JTextField tf1, tf2, tf3;
JButton b1, b2, b3;
JTable t1;
String s1;
public Sell() {
setBounds(450, 200, 600, 300);
setTitle("Sell");
Container con = getContentPane();
con.setBackground(Color.WHITE);
setLayout(null); // FlowLayout,GridLayout By default it is FlowLayout.
setVisible(true);
setResizable(false); // It allows to resize application size.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tf1 = new JTextField();
tf2 = new JTextField();
tf3 = new JTextField();
b1 = new JButton("Select");
b2 = new JButton("Add");
b3 = new JButton("Invoice");
t1 = new JTable(0, 2);
DefaultTableModel model = (DefaultTableModel) t1.getModel();
model.addRow(new Object[] { "Product", "Price" });
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
add(b3);
add(t1);
tf1.setBounds(50, 50, 50, 20);
tf2.setBounds(25, 100, 100, 20);
tf3.setBounds(150, 100, 100, 20);
b1.setBounds(150, 45, 75, 30);
b2.setBounds(100, 195, 75, 30);
b3.setBounds(200, 195, 75, 30);
t1.setBounds(350, 50, 225, 200);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
s1 = tf1.getText();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/vanisb",
"root", "spirit");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from product where ID='" + s1 + "';");
while (rs.next()) {
tf2.setText(rs.getString("product_name"));
tf3.setText(rs.getString("price"));
}
conn.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(b1, ex);
}
}
});
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addRow(new Object[] { tf2.getText(), tf3.getText() });
}
});
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Invoice(model);
}
});
}
}
2.Code of 2nd class where we have to fetch the last table data-->
Invoice.java
public class Invoice extends JFrame {
public static void main(String[] args) {
}
JLabel l1, l2;
JTextField tf1, tf2;
JTable t2;
JButton b1;
public Invoice(DefaultTableModel model) {
setBounds(450, 200, 600, 300);
setTitle("Invoice");
Container con = getContentPane();
con.setBackground(Color.WHITE);
setLayout(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1 = new JLabel("Name : ");
l2 = new JLabel("Phone No. : ");
tf1 = new JTextField();
tf2 = new JTextField();
b1 = new JButton("Add Customer");
t2 = new JTable(model);
add(l1);
add(l2);
add(tf1);
add(tf2);
add(b1);
add(t2);
l1.setBounds(50, 50, 100, 20);
l2.setBounds(50, 100, 100, 20);
tf1.setBounds(150, 50, 100, 20);
tf2.setBounds(150, 100, 100, 20);
b1.setBounds(100, 175, 150, 30);
t2.setBounds(300, 50, 275, 200);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
}
}
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();
Im making a desktop application in java and i need some help ,
Im using sql database to store all my information on the users , e.g UserName , Password , full name .
i have 2 frames , The first one is the login frame where the admin enters his username and password and if it matches with the details on sql database then it will take him to the next frame which is the admin panel , now i want that the admins full name should show on the top left corner of the second frame(which is the admin panel) in the NorthPanel,
this is my codes for both frames , please help
How do i take the name of the admin that logged in from the sql database and show it in the admin panel?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.*;
import java.sql.*;
import java.awt.*;
import javax.swing.*
public class Login extends JFrame implements ActionListener, KeyListener, FocusListener, WindowListener
{
JPanel UserPanel,NorthPanel;
JLabel UserId,UserPassword;
JLabel LblFrgtPass;
JTextField TxtUser;
JPasswordField TxtUserPass;
JButton BtnLogin;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean flag=false;
public Login()
{
add(GetUserPanel(), BorderLayout.CENTER);
add(GetNorthPanel(), BorderLayout.NORTH);
addWindowListener(this);
}
public boolean GetConnection()
{
flag=false;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:Project");
stmt=con.createStatement();
flag=true;
}catch(Exception ex)
{
ex.printStackTrace();
flag=false;
}
return flag;
}
public boolean CloseConnection()
{
flag=false;
try
{
if(con!=null)
{
con.close();
flag=true;
}
}catch(Exception ex)
{
flag=false;
}
return flag;
}
public ResultSet GetRecords(String sql)
{
rs=null;
try
{
rs=stmt.executeQuery(sql);
}catch(Exception ex)
{
rs=null;
}
return rs;
}
JPanel GetNorthPanel()
{
NorthPanel = new JPanel();
NorthPanel.setLayout(new FlowLayout());
ImageIcon titleIcon = new ImageIcon("titleicon.png");
JLabel title = new JLabel(titleIcon);
NorthPanel.add(title);
NorthPanel.setBackground(Color.white);
return NorthPanel;
}
JLabel GetLblForgetPassword()
{
LblFrgtPass = new JLabel("Forgot Password ? ");
return LblFrgtPass;
}
JPanel GetUserPanel()
{
UserPanel=new JPanel();
UserPanel.setLayout(new GridBagLayout());
UserPanel.setBackground(Color.WHITE);
GridBagConstraints GbcUserId = new GridBagConstraints();
GbcUserId.gridx=1;
GbcUserId.gridy=3;
GbcUserId.fill=GridBagConstraints.BOTH;
GbcUserId.insets = new Insets(10, 70, 0, 0);
UserPanel.add(GetUserId(),GbcUserId);
GridBagConstraints GbcTxtUser = new GridBagConstraints();
GbcTxtUser.gridx=2;
GbcTxtUser.gridy=3;
GbcTxtUser.insets = new Insets(10, 40, 0, 0);
UserPanel.add(GetTxtUser(),GbcTxtUser);
GridBagConstraints GbcUserPassword = new GridBagConstraints();
GbcUserPassword.gridx=1;
GbcUserPassword.gridy=4;
GbcUserPassword.fill=GridBagConstraints.BOTH;
GbcUserPassword.insets = new Insets(10, 70, 0, 0);
UserPanel.add(GetUserPassword(),GbcUserPassword);
GridBagConstraints GbcTxtUserPass = new GridBagConstraints();
GbcTxtUserPass.gridx=2;
GbcTxtUserPass.gridy=4;
GbcTxtUserPass.insets = new Insets(10, 40, 0, 0);
UserPanel.add(GetTxtUserPass(),GbcTxtUserPass);
GridBagConstraints GbcBtnLogin = new GridBagConstraints();
GbcBtnLogin.gridx=2;
GbcBtnLogin.gridy=5;
GbcBtnLogin.insets = new Insets(50, 50, 20, 20);
UserPanel.add(GetBtnLogin(),GbcBtnLogin);
GridBagConstraints GbcLblFrgtPass = new GridBagConstraints();
GbcLblFrgtPass.gridx=3;
GbcLblFrgtPass.gridy=5;
GbcLblFrgtPass.insets = new Insets(50, 0, 20, 20);
UserPanel.add(GetLblFrgtPass(),GbcLblFrgtPass);
return UserPanel;
}
JLabel GetUserId()
{
UserId = new JLabel("User Id : ");
UserId.setFont(new Font("Bookman Old Style", Font.PLAIN, 14));
return UserId;
}
JTextField GetTxtUser()
{
TxtUser = new JTextField(10);
TxtUser.addKeyListener(this);
TxtUser.addFocusListener(this);
return TxtUser;
}
JLabel GetUserPassword()
{
UserPassword = new JLabel("Password : ");
UserPassword.setFont(new Font("Bookman Old Style", Font.PLAIN, 14));
return UserPassword;
}
JPasswordField GetTxtUserPass()
{
TxtUserPass = new JPasswordField(10);
TxtUserPass.addKeyListener(this);
TxtUserPass.addFocusListener(this);
return TxtUserPass;
}
JLabel GetLblFrgtPass()
{
LblFrgtPass = new JLabel("Forgot Passord ?");
return LblFrgtPass;
}
JButton GetBtnLogin()
{
BtnLogin = new JButton(" LogIn ");
//Project1 p = new Project1();
BtnLogin.addActionListener(this);
BtnLogin.setFont(new Font("Bookman Old Style", Font.PLAIN, 14));
BtnLogin.registerKeyboardAction(BtnLogin.getActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED);
BtnLogin.registerKeyboardAction(BtnLogin.getActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED);
return BtnLogin;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==BtnLogin)
{
String User_Id = TxtUser.getText().trim();
String User_Pass = TxtUserPass.getText().trim();
String sql = "Select * from users where UserId = '"+User_Id+"' and Password= '"+User_Pass+"'";
if(GetConnection()==true)
{
try
{
rs =GetRecords(sql);
int count = 0;
String usertype="";
while(rs.next())
{
count = count + 1;
usertype=rs.getString(3);
}
if(count ==1)
{
if(usertype.equalsIgnoreCase("student"))
{
JOptionPane.showMessageDialog(null, "Student Frame");
}
else if(usertype.equalsIgnoreCase("teacher"))
{
JOptionPane.showMessageDialog(null, "Teacher Frame");
}
else if(usertype.equalsIgnoreCase("admin"))
{
Admin frame=new Admin();
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
dispose();
}
else
{
JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
catch(Exception ex)
{
//ex.printStackTrace();
System.err.println("ERROR2");
}
}
else
{
System.out.println("Not Connected");
}
}
}
public void keyTyped(KeyEvent ex)
{
//ASCII :American Standard Code for Information Interchange
}
public void keyPressed(KeyEvent ex)
{
System.out.println(ex.getKeyCode());
if(ex.getKeyCode()==10 && ex.getSource()==TxtUser)
{
TxtUserPass.requestFocus();
}
else if(ex.getKeyCode()==10 && ex.getSource()==TxtUserPass)
{
BtnLogin.requestFocus();
}
else if(ex.getKeyCode()==10 && ex.getSource()==BtnLogin)
{
JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
public void keyReleased(KeyEvent ex)
{
if(ex.getKeyCode()==10 && ex.getSource()==TxtUserPass)
{
// JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
public void focusGained(FocusEvent ex)
{
if(ex.getSource()==TxtUser)
{
TxtUser.setBackground(Color.white);
}
else if(ex.getSource()==TxtUserPass)
{
TxtUserPass.setBackground(Color.white);
}
}
public void focusLost(FocusEvent ex)
{
if(ex.getSource()==TxtUser)
{
TxtUser.setBackground(Color.white);
}
else if(ex.getSource()==TxtUserPass)
{
TxtUserPass.setBackground(Color.white);
}
}
public void windowActivated(WindowEvent ex)
{
}
public void windowDeactivated(WindowEvent ex)
{
}
public void windowIconified(WindowEvent ex)
{
}
public void windowDeiconified(WindowEvent ex)
{
}
public void windowClosing(WindowEvent ex)
{
//JOptionPane.showMessageDialog(null,"GoodBye","Exit LogIn",JOptionPane.PLAIN_MESSAGE);
}
public void windowClosed(WindowEvent ex)
{
}
public void windowOpened(WindowEvent ex)
{
}
public static void main(String[] args)
{
Login Frame = new Login();
Frame.setResizable(false);
Frame.setSize(600,400);
Frame.setLocationRelativeTo(null);
Frame.setVisible(true);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The code below is the second frame
import java.awt.*;
import javax.swing.*;
import java.sql.*;
public class Admin extends Login {
JFrame frame = new JFrame("Admin");
JPanel panel;
JPanel nPanel;
JLabel logOut;
JLabel UserName;
JButton btn1;
JButton btn2;
JButton btn3;
JButton btn4;
JButton btn5;
JButton btn6;
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
boolean flag = false;
//****************MAIN CONSTRUCTOR******************************************
public Admin(){
add(GetNPanel(), BorderLayout.NORTH);
add(GetCPanel(), BorderLayout.CENTER);
}
//****************SQL CONNECTION********************************************
public boolean GetConnection(){
flag = false;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Project");
//System.out.println("Connected");
stmt = con.createStatement();
flag=true;
}
catch(Exception ex){
ex.printStackTrace();
flag = false;
}
return flag;
}
//****************CENTER PANEL**********************************************
JPanel GetCPanel(){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//gbc.insets = new Insets(1, 1, 1, 1); //cell padding
gbc.fill = GridBagConstraints.BOTH; //fill cell area
gbc.weightx = 1; // fill horizontal cell area
gbc.weighty = 1; //fill vertical cell area
//btn1
btn1 = new JButton(new ImageIcon("teacher.png"));
btn1.setToolTipText("Add / Edit / Remove Teachers");
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(btn1, gbc);
//btn2
btn2 = new JButton(new ImageIcon("student.png"));
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(btn2, gbc);
//btn3
btn3 = new JButton(new ImageIcon("notice.png"));
gbc.gridx = 2;
gbc.gridy = 0;
panel.add(btn3, gbc);
//btn4
btn4 = new JButton(new ImageIcon("complaints.png"));
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(btn4, gbc);
//btn5
btn5 = new JButton(new ImageIcon("messages.png"));
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(btn5, gbc);
//btn6
btn6 = new JButton(new ImageIcon("password.png"));
gbc.gridx = 2;
gbc.gridy = 1;
panel.add(btn6, gbc);
return panel;
}
JPanel GetNPanel()
{
nPanel = new JPanel();
return nPanel;
}
//****************NORTH PANEL***********************************************
public static void main(String[] args)
{
new Admin();
Admin frame = new Admin();
//FRAME
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
}
You are extending your AdminPanel Frame from Login frame. What you can do is create an instance variable in your Login frame and store the value of Full Name of user to it if the login is successful.
As the AdminPanel inherits Login Frame, so it will automatically get the value of Full name of user. Then you can take any JLabel in your AdminPanel in the left corner and set text the value of instance variable there.
I would have a setName method that takes a string variable and then set the text of the label.
Public void setName(String name){
Label.setText(name)
}
Then I would call the method upon the login being successful.