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...)
Related
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.
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);
i am making java app for my minor project.i am entering correct data but it not allowing to login.i am confused why the code in not working.
there are 2 fields in my database(username and pass ).i am entering correct data but it allowing me to login
`
public class login extends JFrame implements ActionListener{
JButton jb1;
JTextField tf3,tf1,tf2;
ResultSet rs;
String s2,s1,s3;
String a;
Connection con;
login(){
Container c =getContentPane();
c.setLayout(null);
c.setBackground(Color.orange);
jb1=new JButton("submit");
jb1.addActionListener(this);
jb1.setBounds(180,370,100,50);
JLabel jl1=new JLabel("username");
jl1.setBounds(10,60,100,50);
JLabel jl2=new JLabel("password");
jl2.setBounds(10,110,100,50);
JLabel jl3=new JLabel("user or emp");
jl3.setBounds(10,160,100,50);
tf1= new JTextField();
tf1.setBounds(110,70,200,40);
tf2= new JTextField();
tf2.setBounds(110,120,200,40);
tf3=new JTextField();tf3.setBounds(110,180,200,40);
tf1.setText("username");
tf2.setText("password");
c.add(tf1);c.add(tf2);c.add(tf3);
c.add(jl1);c.add(jl2);c.add(jl3);
c.add(jb1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==jb1){
s1 = tf1.getText();
s2 = tf2.getText();
s3 = tf3.getText();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "scott", "hr");
PreparedStatement ps = con.prepareStatement("select * from login ");
rs = ps.executeQuery();
while(rs.next()) {
String username = rs.getString("username");
String pass = rs.getString("pass");
if ((s1.equals(username)) && (s2.equals(pass))) {
if (s3.equals("Admin")) {
dispose();
home f=new home();
f.setSize(500,500);
f.setTitle("Bank Management System");
f.setVisible(true);
} else if (s3.equals("user")) {
dispose();
} else {
dispose();
}
} else {
JOptionPane.showMessageDialog(null, "User name and password do" + " not match!","ALERT!",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
catch(Exception ex)
{
System.out.println( ex);
}
}
}
public static void main(String[] args) {
login af =new login();
af.setSize(500,500);
af.setTitle("login");
af.setVisible(true);
}
}
`
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 need to generate sequential number between 0-9 and want to display it in the JTextfield combined with the value from JCombobox(i.e.element of jcombobox+count)
as a string after pressing the JButton
When I select the first value from combobox and press the JButton the count should start from 0 and again when the second element from the combobox is selected the count should again start from 0 for second element and this should be the case for all other element of combobox.
For example-- when element 1 is selected and button is pressed the combined output should be 10,11,12,13... but,if in between this element 2 is selected
the output displayed in textfield should again start from 0 i.e.20,21,22...
and for element 3 the count should again start from 0 i.e. 30,31,32...
The combined output should be displayed in textfield
import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class Test extends JFrame implements ActionListener {
JButton b1, b2;
JComboBox jc;
String name;
JTextField t1;
Connection con, conn;
Statement st;
PreparedStatement pst;
ResultSet rs, rs1;
Test() {
setLayout(null);
JLabel l1 = new JLabel("USER SELECTION :");
l1.setBounds(100, 100, 150, 60);
add(l1);
jc = new JComboBox();
jc.setBounds(230, 114, 120, 30);
jc.addItem("SELECT");
jc.addActionListener(this);
add(jc);
JButton b1 = new JButton("GENERATE PART NO. :");
b1.setBounds(70, 340, 170, 30);
b1.addActionListener(this);
add(b1);
t1 = new JTextField(10);
t1.setBounds(270, 340, 200, 30);
add(t1);
JButton b2 = new JButton("BACK");
b2.setBounds(190, 420, 120, 30);
b2.addActionListener(this);
add(b2);
setSize(500, 500);
setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select Userdata from user1";
rs = st.executeQuery(s);
while (rs.next()) {
String name = rs.getString("Userdata");
jc.addItem(rs.getString("Userdata"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR");
}
finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("GENERATE PART NO. :")) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select value from user1 where Userdata='" + jc.getSelectedItem() + "'";
rs = st.executeQuery(s);
t1.getText();
if (rs.next()) {
String add1 = rs.getString("value");
t1.setEditable(false);
t1.setText("B" + add1);// B is the default value here which
// is also concatenated
}
}
catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
if (str.equals("BACK") == true) {
new categ();
setVisible(false);
}
}
public static void main(String[] args) throws IOException {
Test td = new Test();
}
}