Iwould like to create a form using java eclipse. The problem is i cannot obtain the total added JLabel and JTextField.this is my code:
class gestiontache extends JFrame{
JFrame f;
JPanel p1, p2, p3;
JTabbedPane tp;
JLabel l1, l2, l3,l4,l5;
JComboBox tf3categor;
JComboBox tf4Affiliation;
JComboBox tf5montant;
JTextField tf1, tf2;
JScrollPane sp1;
JButton savebtn, resetbtn, editbtn;
private static String FILE = "c:/temp/DocumentPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
gestiontache() {
f = new JFrame("Form");
GridLayout lay1= new GridLayout(12, 2);
GridLayout lay2= new GridLayout(5, 2);
p1 = new JPanel(lay1);
p2 = new JPanel(lay2);
lay1.setHgap(5); //Cinq pixels d'espace entre les colonnes (H comme Horizontal)
lay1.setVgap(5); //Cinq pixels d'espace entre les lignes (V comme Vertical)
lay2.setHgap(5);
lay2.setVgap(5);
tp = new JTabbedPane();
l1 = new JLabel("Nom");
l2 = new JLabel("Prénom");
l3 = new JLabel("Catégorie");
l4 = new JLabel("Affiliation");
l5 = new JLabel("Montant à payer");
tf1 = new JTextField(12);
tf2 = new JTextField(12);
tf3categor = new JComboBox( new String[] { "Medecin", "Technicien", "Pharmacien","Autre" });
tf4Affiliation =new JComboBox( new String[] { "K", "T", "Sf","Gab","Toze","Med","Tat","Na","B","G","Si","Ga","Ke","Kr" });
tf5montant = new JComboBox( new String[] { "15 Dinars", "30 Dinars"});
savebtn = new JButton(" Ajouter ");
resetbtn = new JButton(" Annuler");
editbtn = new JButton(" Imprimer");
p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
p1.add(l3);
p1.add(tf3categor);
p1.add(l4);
p1.add(tf4Affiliation);
p1.add(l5);
p1.add(tf5montant);
p1.add(savebtn);
p1.add(resetbtn);
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
p2.add(editbtn);
resetbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
clear();
}
});
savebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String nom, prenom,categorie, affiliation, montant;
nom = tf1.getText();
prenom = tf2.getText();
categorie=(String) tf3categor.getSelectedItem();
affiliation=(String) tf4Affiliation.getSelectedItem();
montant=(String) tf5montant.getSelectedItem();
String url = "jdbc:mysql://localhost:3306/seminaire";
String userid = "root";
String password = "";
try {
Connection connection = DriverManager.getConnection(url,
userid, password);
Statement st = connection.createStatement();
if (nom != "" && prenom != ""&& categorie!= ""&& affiliation!= ""&& montant!= "") {
st.executeUpdate("insert into participant values('" + nom
+ "','" + prenom + "','" + categorie + "','"+affiliation+"','"+montant+"')");
JOptionPane.showMessageDialog(null,"Données insérées avec succès");
clear();
} else {
JOptionPane.showMessageDialog(null, "merci de saisir vos données");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
editbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String nom, prenom,categorie, affiliation, montant;
nom = tf1.getText();
prenom = tf2.getText();
String url = "jdbc:mysql://localhost:3306/seminaire";
String userid = "root";
String password = "";
try {
Connection connection = DriverManager.getConnection(url,
userid, password);
Statement st = connection.createStatement();
if (nom != "" && prenom != "") {
ResultSet rs= st.executeQuery("SELECT * FROM participant
WHERE nom=nom && prenom=prenom");
while (rs.next())
{
String nm = rs.getString("nom");
String prnm = rs.getString("prenom");
String cat = rs.getString("categorie");
String afl=rs.getString("affiliation");
String mnt=rs.getString("montant");
// print the results
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
//open
document.open();
Paragraph p = new Paragraph();
p.add("Reçu");
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
Paragraph p2 = new Paragraph();
p2.add(nm); //no alignment
document.add(p2);
Font f = new Font();
f.setStyle(Font.BOLD);
f.setSize(8);
document.add(new Paragraph("This is my paragraph 3", f));
//close
document.close();
System.out.println("Done");
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else {
JOptionPane.showMessageDialog(null, "merci de saisir vos données");
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}});
}
void dis() {
f.getContentPane().add(tp);
tp.addTab("Ajouter participant", p1);
tp.addTab("Imprimer attestation", p2);
f.setSize(500, 400);
f.setVisible(true);
f.setResizable(true);
}
void clear()
{
tf1.setText("");
tf2.setText("");
tf3categor.setSelectedItem("");
tf4Affiliation.setSelectedItem("");
tf5montant.setSelectedItem("");
}
public static void main(String z[]) {
gestiontache data = new gestiontache();
data.dis();
}
}
`
The problem here is the JLabel and JTextField(nom, prenom)don't appear in the form in order to insert or select from database. Have any idea how can i correct it please. Thank you
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
These above fields are added in both p1(Tab1) and p2(Tab2) Panels.
Thats why its not showing.
You must create seperate controls for both p1 and p2 panels. Don't reuse same controls in two panels.
For example:
l7 = new JLabel("Normal");
p2.add(l7);
Related
I have two classes, one has an ArrayList called "clanovi" which is populated by data from SQL database and I want to display that data in the "clanComboBox" in another class. I have been trying for two days but I can't figure it out.
Class with the list:
String cnnString;
String user;
String password;
public ArrayList<String> clanovi = new ArrayList<String>();
public ArrayList<String> getList(){
return clanovi;
}
public void Connect(String cnnString, String user, String password){
this.cnnString = cnnString;
this.user = user;
this.password = password;
ResultSet res = null;
try {
Connection connection = DriverManager.getConnection(cnnString, user, password);
System.out.println("Connection successful");
Statement stm = connection.createStatement();
String sql = "select Ime, Prezime from Clanovi";
res = stm.executeQuery(sql);
while(res.next()) {
clanovi.add(res.getString("Ime") + " " + res.getString("Prezime"));
}
System.out.println(clanovi);
} catch (SQLException e) {
System.out.println("An unexpected error occurred.");
e.printStackTrace();
}
}
The GUI class with the combobox:
public class PosuditiFilmFrame implements ActionListener{
SQLConnection con = new SQLConnection();
JFrame posuditiFilmFrame = new JFrame();
JButton posuditiFilmButton = new JButton();
JComboBox clanoviComboBox = new JComboBox();
JComboBox filmoviComboBox = new JComboBox();
JLabel clanLabel = new JLabel("Clan:");
JLabel filmLabel = new JLabel("Film:");
ArrayList<String> cBox = con.getList();
PosuditiFilmFrame(){
posuditiFilmButton = new JButton();
posuditiFilmButton.setBounds(200, 270, 200, 50);
posuditiFilmButton.addActionListener(this);;
posuditiFilmButton.setText("Posuditi Film");
posuditiFilmButton.setFocusable(false);
clanLabel.setBounds(50, 50, 70, 50);
clanLabel.setFont(new Font("Arial", Font.PLAIN, 25));
filmLabel.setBounds(50, 125, 70, 50);
filmLabel.setFont(new Font("Arial", Font.PLAIN, 25));
clanoviComboBox.setBounds(150, 50, 300, 50);
filmoviComboBox.setBounds(150, 125, 300, 50);
posuditiFilmFrame.setTitle("Posuditi Film");
posuditiFilmFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
posuditiFilmFrame.setLayout(null);
posuditiFilmFrame.setSize(600, 400);
posuditiFilmFrame.setVisible(true);
posuditiFilmFrame.add(posuditiFilmButton);
posuditiFilmFrame.add(clanoviComboBox);
posuditiFilmFrame.add(filmoviComboBox);
posuditiFilmFrame.add(clanLabel);
posuditiFilmFrame.add(filmLabel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==posuditiFilmButton) {
JOptionPane.showMessageDialog(null, "Film je posuden");
}
}
Of course, I also want the data to be displayed in that combobox
I am implementing a search interface in eclipse with the help of mysql. My search interface yields the results I want, but I want to be able to have the "video_url" column clickable and bring up a hyperlink. Is there a way to do this for a single column? Right now the Jtable is "editable", so the user can click on it, but no changes are made to it. The link can be copied and then pasted later, but I'm really trying to have the link be opened from the interface.
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VIdeo_search_test window = new VIdeo_search_test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public VIdeo_search_test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 17));
frame.setBounds(400, 400, 1050, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblVideoSearch = new JLabel("Video Search");
lblVideoSearch.setFont(new Font("Tahoma", Font.PLAIN, 19));
lblVideoSearch.setBounds(241, 11, 230, 27);
frame.getContentPane().add(lblVideoSearch);
JButton btnSearchCity = new JButton("Search City");
btnSearchCity.setBounds(216, 80, 165, 25);
btnSearchCity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from video where video_city = '" +txtCity.getText()+"'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
frame.getContentPane().add(btnSearchCity);
JButton btnSearchTag = new JButton("Search Tag");
btnSearchTag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from video where video_tags LIKE '"+txtTag.getText()+"%'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table_1.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
btnSearchTag.setBounds(216, 303, 165, 25);
frame.getContentPane().add(btnSearchTag);
txtCity = new JTextField();
txtCity.setBounds(216, 49, 165, 20);
frame.getContentPane().add(txtCity);
txtCity.setColumns(10);
table = new JTable();
table.setBounds(10, 116, 867, 135);
frame.getContentPane().add(table);
txtTag = new JTextField();
txtTag.setColumns(10);
txtTag.setBounds(216, 272, 165, 20);
frame.getContentPane().add(txtTag);
table_1 = new JTable();
table_1.setBounds(10, 341, 601, 135);
frame.getContentPane().add(table_1);
JButton btnViewVideo = new JButton("View Video");
btnViewVideo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
registered_video_interface info = new registered_video_interface();
registered_video_interface.main(null); }
});
btnViewVideo.setBounds(251, 509, 89, 23);
frame.getContentPane().add(btnViewVideo);
}
}
I have a Jframe with two panels and i am trying to change the panels/views using jmenu items.
The first panel adds data to a database. User can then switch to the view panel by clicking the JMenuBarItem.
The Second panel fetches data from the database and displays the results in a JTable.
Everything works fine but when i switch back and forth to the second panel it adds another panel instead of removing it/replacing it. See linked images below to better understand
First Panel
Second Panel
Second Panel after switching back and forth
package employeerecords3;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.*;
public class EmployeeRecords3 extends JFrame {
JLabel empnolb, empnamelb, empdptlb, basicsallb, hseallowancelb;
JTextField empnotf, empnametf, empdpttf, basicsaltf, hseallowancetf;
JButton submitbtn, cancelbtn;
String host = "jdbc:mysql://localhost:3306/employee";
String username = "root";
String password = "";
EmployeeRecords3() {
setTitle("Employee Records");
final JPanel addpanel = new JPanel();
final JPanel viewpanel = new JPanel();
setTitle("Employee Records");
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem add = new JMenuItem("Add Employee");
JMenuItem view = new JMenuItem("View Employees");
file.add(add);
file.add(view);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (viewpanel.isShowing()) {
remove(viewpanel);
add(addpanel);
}
revalidate();
repaint();
}
});
view.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
java.util.List<String[]> datalist = new ArrayList<>();
String[] columnNames = {"Emp ID", "Emp Name", "Department", "Basic Pay", "House Allowance", "Payee", "NHIF", "NSSF", "Pension", "NetPay"};
try {
String query = "SELECT * FROM payroll";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(host, username, password);
Statement st = con.prepareStatement(query);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
String[] results = {rs.getString(1), rs.getString(2), rs.getString(3), Double.toString(rs.getDouble(4)), Double.toString(rs.getDouble(5)), Double.toString(rs.getDouble(6)), Double.toString(rs.getDouble(7)), Double.toString(rs.getDouble(8)), Double.toString(rs.getDouble(9)), Double.toString(rs.getDouble(10))};
datalist.add(results);
}
con.close();
String[][] data = new String[datalist.size()][];
data = datalist.toArray(data);
JTable table = new JTable(data, columnNames);
JScrollPane sp = new JScrollPane(table);
viewpanel.add(sp);
} catch (Exception ex) {
ex.printStackTrace();
}
if (addpanel.isShowing()) {
remove(addpanel);
add(viewpanel);
} else if (viewpanel.isShowing()) {
remove(viewpanel);
add(viewpanel);
}
revalidate();
repaint();
}
});
empnolb = new JLabel("Emp No");
empnamelb = new JLabel("Name");
empdptlb = new JLabel("Department");
basicsallb = new JLabel("Basic Pay");
hseallowancelb = new JLabel("House Allowance");
empnotf = new JTextField();
empnametf = new JTextField();
empdpttf = new JTextField();
basicsaltf = new JTextField();
hseallowancetf = new JTextField();
submitbtn = new JButton("Submit");
cancelbtn = new JButton("Cancel");
Submit submithandler = new Submit();
submitbtn.addActionListener(submithandler);
Cancel cancelhandler = new Cancel();
cancelbtn.addActionListener(cancelhandler);
addpanel.add(empnolb);
addpanel.add(empnotf);
addpanel.add(empnamelb);
addpanel.add(empnametf);
addpanel.add(empdptlb);
addpanel.add(empdpttf);
addpanel.add(basicsallb);
addpanel.add(basicsaltf);
addpanel.add(hseallowancelb);
addpanel.add(hseallowancetf);
addpanel.add(submitbtn);
addpanel.add(cancelbtn);
addpanel.setLayout(new GridLayout(6, 2));
viewpanel.setLayout(new GridLayout(1, 1));
add(addpanel);
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class Submit implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String empNo, empName, department;
double grossPay, basicPay, hseAllowance, payee, nhif, nssf, pension, netPay;
empNo = empnotf.getText();
empName = empnametf.getText();
department = empdpttf.getText();
basicPay = Double.parseDouble(basicsaltf.getText());
hseAllowance = Double.parseDouble(hseallowancetf.getText());
grossPay = basicPay + hseAllowance;
payee = 0.3 * grossPay;
if (grossPay > 100000) {
nhif = 1200;
} else {
nhif = 320;
}
nssf = 200;
pension = 0.05 * basicPay;
netPay = grossPay - (payee - nhif - nssf - pension);
String query = "INSERT INTO payroll(EmpID,EmpName,Department,BasicPay,HouseAllowance,Payee,NHIF,NSSF,Pension,NetPay) VALUES('" + empNo + "','" + empName + "','" + department + "','" + basicPay + "','" + hseAllowance + "','" + payee + "','" + nhif + "','" + nssf + "','" + pension + "','" + netPay + "')";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(host, username, password);
Statement st = con.prepareStatement(query);
int count = st.executeUpdate(query);
boolean action = (count > 0);
if (action) {
empnotf.setText(null);
empnametf.setText(null);
empdpttf.setText(null);
basicsaltf.setText(null);
hseallowancetf.setText(null);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class Cancel implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
EmployeeRecords3 er = new EmployeeRecords3();
}
}
The mistake you made is that you create a new JTable every time you open the viewpanel. You not only create a new one, you add it to your view-JPanel. This is why you get the weird behaviour.
This code snippet fixes your problem. I just added the removeAll() method call to the add-JPanel ActionListener. When the add-JPanel is opened, the old JTable is removed from the view-JPanel. I had to comment out your database interactions.
// ...
// ...
// ...
add.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (viewpanel.isShowing())
{
remove(viewpanel);
/*
* I basically just added this one line.
* Since you want to make a fresh query after
* you come back to the viewpanel, we can delete
* all the elements (which is only the JTable).
*/
viewpanel.removeAll();
add(addpanel);
}
revalidate();
repaint();
}
});
view.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
java.util.List<String[]> datalist = new ArrayList<>();
String[] columnNames = {"Emp ID", "Emp Name", "Department",
"Basic Pay", "House Allowance", "Payee", "NHIF", "NSSF",
"Pension", "NetPay"};
try
{
// String query = "SELECT * FROM payroll";
// Class.forName("com.mysql.jdbc.Driver");
// Connection con = DriverManager.getConnection(host, username,
// password);
// Statement st = con.prepareStatement(query);
// ResultSet rs = st.executeQuery(query);
String[] results = {"a", "b", "c", "d", "e", "f", "g", "h",
"i", "j"};
datalist.add(results);
// con.close();
String[][] data = new String[datalist.size()][];
data = datalist.toArray(data);
JTable table = new JTable(data, columnNames);
JScrollPane sp = new JScrollPane(table);
viewpanel.add(sp);
}
catch (Exception ex)
{
ex.printStackTrace();
}
if (addpanel.isShowing())
{
remove(addpanel);
add(viewpanel);
}
else if (viewpanel.isShowing())
{
remove(viewpanel);
add(viewpanel);
}
revalidate();
repaint();
}
});
// ...
// ...
// ...
The solution on top is not the only one of course. I don't know where you wanna go with this UI, but you can just remove the contents of the table and refill them as soon as you open the view-JPanel again.
Another solution would be to remove the JTable specifically (but in this case you probably need to have it as a field, because you create the table in a block that you can't reference from your add.addActionListener-Block)
The third solution would be to add a boolean flag, that checks if the table has been loaded and only create a new JTable, if it hasn't.
I'm struggeling the whole day with a stupid problem. I insert with executeupdate a row in my database. I tried it with fireTableDataChanged, setModel and every hint i could find here.
But nothing changes. The data is inserted and only if i reopen my app i can see my insert.
I hope this class is enough to solve my problem. Otherwise i could paste my executeupdate statement or my mainclass.
I really hope you can help me.
Table
public TabelleErfasst()
{
super(new GridLayout(1, 0));
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(950, 300));
table.setFillsViewportHeight(true);
DefaultTableModel model = new DefaultTableModel();
model.setRowCount(0);
table.setModel(model);
Object[] columnsName = new Object[7];
columnsName[0] = "Vorname";
columnsName[1] = "Nachname";
columnsName[2] = "Straße";
columnsName[3] = "Stadt";
columnsName[4] = "Hat abgestimmt für";
columnsName[5] = "ID";
columnsName[6] = "Sterne";
model.setColumnIdentifiers(columnsName);
Object[] rowData = new Object[8];
ArrayList<Stimmzettel> stimmzettel = ErfasstDatabase.getStimmzettel();
for (int i = 0; i < stimmzettel.size(); i++) {
rowData[0] = stimmzettel.get(i).getVorName();
rowData[1] = stimmzettel.get(i).getNachName();
rowData[2] = stimmzettel.get(i).getStrasse();
rowData[3] = stimmzettel.get(i).getStadt();
rowData[4] = stimmzettel.get(i).getAbgestimmtFuer();
rowData[5] = stimmzettel.get(i).getProjektId();
rowData[6] = stimmzettel.get(i).getSterne();
model.addRow(rowData);
}
// Ändere Spaltenbreite, wenn i == 1 -> breiter
TableColumn column = null;
for (int i = 0; i < 7; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 1) {
column.setPreferredWidth(150); //
} else if (i == 4) {
column.setPreferredWidth(200);
} else if (i == 5) {
column.setPreferredWidth(45);
} else if (i == 6) {
column.setPreferredWidth(45);
} else {
column.setPreferredWidth(150);
}
}
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Statement
public class DBProjektController {
public void insert(String f1, String f2, String f3, String f4, String f5, String f6, String f7) {
if (f1.isEmpty()) {
System.out.println("The ID cannot be null!");
} else {
try {
Connection con;
con = DriverManager.getConnection("jdbc:ucanaccess://C:/Projekt/DB/erfasst.accdb");
Statement statement = con.createStatement();
statement.executeUpdate("INSERT INTO ERFASST(VORNAME, NAME, STRASSE, ORT, ABGESTIMMT_PROJEKT, PROJEKTID, STERNE) VALUES('" + f1 + "','" + f2 + "','" + f3 + "','" + f4 + "','" + f5 + "','" + f6 + "','" + f7 + "')");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Snippet from my MainClass (I deleteted some parts that doesn't really concern my problem)
public class Gui extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
// Frame
JFrame frame = new JFrame();
// Erstelle JTabbedPane
JTabbedPane jtp = new JTabbedPane();
// Panel
JPanel panel = new JPanel();
public Gui() {
frame.getContentPane().add(jtp);
JPanel pAbstimmung = new JPanel(null);
TabelleErfasst tabelleErfasst = new TabelleErfasst();
tabelleErfasst.setSize(950, 350);
tabelleErfasst.setLocation(35, 80);
JButton bSterneExport = new JButton("Sterne exportieren");
bSterneExport.setSize(300, 60);
bSterneExport.setLocation(682, 480);
JButton bEintragNeu = new JButton("Ausgewählten Eintrag löschen");
bEintragNeu.setSize(300, 60);
bEintragNeu.setLocation(358, 480);
JButton bEintragLoeschen = new JButton("Alle Einträge löschen");
bEintragLoeschen.setSize(300, 60);
bEintragLoeschen.setLocation(35, 480);
JLabel lZettelSession = new JLabel("Alle eingetragenen Stimmzettel der aktuellen Session");
// Inhalte zu Abstimmungsergebnis
pAbstimmung.add(tabelleErfasst);
pAbstimmung.add(bEintragLoeschen);
pAbstimmung.add(bEintragNeu);
pAbstimmung.add(bSterneExport);
pAbstimmung.add(lZettelSession);
jtp.addTab("Abstimmungsergebnis", pAbstimmung);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bStimmeKontrolle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
new DBProjektController().insert(erfasstVorname.getText(), erfasstNachname.getText(),
erfasstStrasse.getText(), erfasstStadt.getText(), projektAuswahl.getText(),
erfasstId.getText(), sterneGruppe.getSelection().getActionCommand());
}
}).start();
TabelleErfasst tabelleErfasst = new TabelleErfasst();
jtp.setSelectedIndex(3);
}
});
// Titel des Fensters
frame.setTitle("AfVF");
// Gr��e des Fensters
frame.setResizable(false);
frame.pack();
frame.setSize(1024, 650);
frame.setVisible(true);
}
}
I have the following code which compiles fine but when it runs then it throws the exception that java.lang.ArrarIndexOutOfBoundsException:11, please if you could help what is wrong it would be a great help.
The code is:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Pro implements ActionListener
{
JTextField t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13;
JButton b1,b2;
public Pro()
{
JFrame f = new JFrame();
JLabel l1 = new JLabel("SNo.");
JLabel l2 = new JLabel("OPANo");
JLabel l3 = new JLabel("CollegeName");
JLabel l4 = new JLabel("ProjectName");
JLabel l5 = new JLabel("SanctionNoDate");
JLabel l6 = new JLabel("TotalOutlayInLakhs)");
JLabel l7 = new JLabel("ProjectDuration");
JLabel l8 = new JLabel("AmountReleased");
JLabel l9 = new JLabel("BalanceToBeReleased");
JLabel l10 = new JLabel("PRSGsHeld");
JLabel l11 = new JLabel("NextPRSGDue");
JLabel l12 = new JLabel("CompletionMonth");
JLabel l13 = new JLabel("Status");
t1 = new JTextField(20);
t1.setEnabled(false);
t2 = new JTextField(20);
t3 = new JTextField(20);
t4 = new JTextField(20);
t5 = new JTextField(20);
t6 = new JTextField(20);
t7 = new JTextField(20);
t8 = new JTextField(20);
t9 = new JTextField(20);
t10 = new JTextField(20);
t11 = new JTextField(20);
t12 = new JTextField(20);
t13 = new JTextField(20);
b1 = new JButton("Reset");
b2 = new JButton("Insert");
b1.addActionListener(this);
b2.addActionListener(this);
JPanel p1 = new JPanel();
p1.add(l1);p1.add(t1);
p1.add(l2);p1.add(t2);
p1.add(l3);p1.add(t3);
p1.add(l4);p1.add(t4);
p1.add(l5);p1.add(t5);
p1.add(l6);p1.add(t6);
p1.add(l7);p1.add(t7);
p1.add(l8);p1.add(t8);
p1.add(l9);p1.add(t9);
p1.add(l10);p1.add(t10);
p1.add(l11);p1.add(t11);
p1.add(l12);p1.add(t12);
p1.add(l13);p1.add(t13);
p1.add(b1);p1.add(b2);
p1.setLayout(new GridLayout(14,2));
f.add(p1);
f.pack();
f.setResizable(false);
f.setVisible(true);
}
public int getMaxSNO()
{
int sno=0;
String path ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=doit.mdb";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(path);
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("SELECT max(Sno) from project");
if(rs.next())
{
sno=rs.getInt(1);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e.toString());
}
return sno;
}
public boolean isAlpha(String str)
{
boolean result = false;
for(int i=0;i!=str.length();i++)
{
int ch = str.charAt(i);
if((ch>=65 && ch<=91) || (ch>=97 && ch<=122))
{
result = true;
}
else
{
result = false;
break;
}
}
return result;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
t5.setText("");
t6.setText("");
t7.setText("");
t8.setText("");
t9.setText("");
t10.setText("");
t11.setText("");
t12.setText("");
t13.setText("");
}
else if(e.getSource()==b2)
{
String name = t3.getText();
boolean b1 = isAlpha(name);
if(b1)
{
try
{
String path ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=doit.mdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(path);
PreparedStatement ps = con.prepareStatement("INSERT into project(OPANo, CollegeName, ProjectName, SanctionNoDate, TotalOutlayInLakhs, ProjectDuration, AmountReleased, BalanceToBeReleased, PRSGsHeld, NextPRSGDue, CompletionMonth, Status) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
ps.setInt(1,Integer.parseInt(t2.getText()));
ps.setString(2, t3.getText());
ps.setString(3, t4.getText());
ps.setString(4, t5.getText());
ps.setString(5, t6.getText());
ps.setString(6, t7.getText());
ps.setString(7, t8.getText());
ps.setString(8, t9.getText());
ps.setString(9, t10.getText());
ps.setString(10, t11.getText());
ps.setString(11, t12.getText());
ps.setString(12, t13.getText());
int rows = ps.executeUpdate();
if(rows>0)
{
con.close();
int sno=getMaxSNO();
t1.setText(String.valueOf(sno));
JOptionPane.showMessageDialog(null, "Data Inserted");
}
else
{
JOptionPane.showMessageDialog(null, "Failed");
}
con.close();
}
catch(Exception ae)
{
JOptionPane.showMessageDialog(null, ae.toString());
}
}
else
{
JOptionPane.showMessageDialog(null, "Invalid Name");
}
}
}
public static void main(String args[])
{
Pro obj = new Pro();
}
}
I suspect this is the problem:
// Reformatted
PreparedStatement ps = con.prepareStatement(
"INSERT into project(OPANo, CollegeName, ProjectName, SanctionNoDate, " +
"TotalOutlayInLakhs, ProjectDuration, AmountReleased, " +
"BalanceToBeReleased, PRSGsHeld, NextPRSGDue, CompletionMonth, Status) " +
"VALUES(?,?,?,?,?,?,?,?,?,?,?)");
Count the question marks, then count the number of values you're trying to specify...
(Then note that you're calling ps.setString(12, t13.getText()) - confirming that you really meant there to be 12 parameters, not 11...)