Data not displayed in jtable - java

Hi I am trying to retrieve data from the database and display in the jtable but I am unable to do it. The code is given below. Can anyone please help me.
//Dialog Creation for Finding Data
jdlgFind=new JDialog(frame,"FIND DATA",true);
jdlgFind.setFont(new Font("Times New Roman", Font.PLAIN, 12));
jdlgFind.setSize(650,500);
findpanel=new JPanel();
findpanel.setBackground(new Color(144, 238, 144));
jdlgFind.setContentPane(findpanel);
findpanel.setLayout(new FlowLayout());
findpanel.setFont(new Font("Times New Roman", Font.PLAIN, 12));
txtGetMobileno=new JTextField(15);
txtGetLandlineno=new JTextField(15);
txtGetPlaceofBirth=new JTextField(15);
JTable jtblFindDate=new JTable(tbldata,columnhead);
jspFindPanel=new JScrollPane(jtblFindDate);
jtblFindDate.setRowSelectionAllowed(true);
jtblFindDate.setFont(new Font("Times New Roman", Font.PLAIN, 11));
jtblFindDate.setPreferredSize(new Dimension(600, 500));
findpanel.add(new JLabel("Mobile No. please : ")).setFont(new Font("Times New Roman", Font.BOLD, 12));
findpanel.add(txtGetMobileno).setFont(new Font("Times New Roman", Font.PLAIN, 12));
findpanel.add(new JLabel("Landline No. please : ")).setFont(new Font("Times New Roman", Font.BOLD, 12));
findpanel.add(txtGetLandlineno).setFont(new Font("Times New Roman", Font.PLAIN, 12));
findpanel.add(new JLabel("Place Of Birth please : ")).setFont(new Font("Times New Roman", Font.BOLD, 12));
findpanel.add(txtGetPlaceofBirth).setFont(new Font("Times New Roman", Font.PLAIN, 12));
findpanel.add(jspFindPanel);
txtGetMobileno.setDocument(new TextFieldLimit(11));
txtGetMobileno.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
findMobileno=null;
findMobileno=txtGetMobileno.getText();
txtGetLandlineno.setEditable(false);
txtGetPlaceofBirth.setEditable(false);
if(findMobileno.length()!=0)
{
try
{
dbcon=new DB_Connection();
PreparedStatement pstmt=dbcon.DB_Connection("//F://eclipse_Luna_64_Development_Workspace//Project JAVA//LIC_AGENCY_TRACKER//DATABASE//LIC_DATA_TRACKER.accdb").prepareStatement("select Inquiry_Master_Data.Inquiry_Master_Name as [Inquirer Name],Inquiry_Master_Data.Inquiry_Master_Mobile_Number as [Inquirer Mobile No],Inquiry_Master_Data.Inquiry_Master_Landline_Number as [Inquirer Landline No],"
+ "Inquiry_Master_Data.Inquiry_Master_Place_Of_Work as [Inquirer Work Place] from Inquiry_Master_Data where Inquiry_Master_Data.Inquiry_Master_Mobile_Number='"+findMobileno+"'");
ResultSet rset=pstmt.executeQuery();
ResultSetMetaData rsetmetadata=rset.getMetaData();
int col=rsetmetadata.getColumnCount();
columnhead=new Vector(col);
columnhead.add("Inquirer Name");
columnhead.add("Inquirer Mobile No");
columnhead.add("Inquirer Landline No");
columnhead.add("Inquirer Work Place");
tbldata=new Vector();
row=new Vector();
while(rset.next())
{
row=new Vector(col);
for(int i=1;i<=col;i++)
{
row.add(rset.getString(i));
}
tbldata.add(row);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Data not found.");
txtGetMobileno.setText("");
txtGetLandlineno.setEditable(true);
txtGetPlaceofBirth.setEditable(true);
txtGetMobileno.requestFocus();
}
}
else
{
txtGetLandlineno.requestFocus();
}
}
});
I am using MS Access. I have used Prepared Statement to retrieve the data but it is not displaying the data.
Regards
Sandeep

JTable jtblFindDate=new JTable(tbldata,columnhead);
What is that statement supposed to do? Do you actually have valid data in both of those variables? If not then the table will be created with no rows or columns.
columnhead=new Vector(col);
columnhead.add("Inquirer Name");
columnhead.add("Inquirer Mobile No");
columnhead.add("Inquirer Landline No");
columnhead.add("Inquirer Work Place");
That code doesn't do anything because you don't then use the columnHead to create a new TableModel.
tbldata.add(row);
That may add data to the Vector, but again you don't use the Vector to create a TableModel
Check out the TableFromDatabaseExample code found in Table From Database for generic code to load a JTable from a database.

Hi I have solved the issue. I have changed the code. Below is the modification part, I have used the following codes: -
dbcon=new DB_Connection();
PreparedStatement pstmt=dbcon.DB_Connection("//F://eclipse_Luna_64_Development_Workspace//Project JAVA//LIC_AGENCY_TRACKER//DATABASE//LIC_DATA_TRACKER.accdb").prepareStatement("select Inquiry_Master_Data.Inquiry_Master_Name as [Inquirer Name],Inquiry_Master_Data.Inquiry_Master_Mobile_Number as [Inquirer Mobile No],Inquiry_Master_Data.Inquiry_Master_Landline_Number as [Inquirer Landline No],"
+ "Inquiry_Master_Data.Inquiry_Master_Place_Of_Work as [Inquirer Work Place] from Inquiry_Master_Data where Inquiry_Master_Data.Inquiry_Master_Place_Of_Work='"+findPlaceofBirth+"'");
ResultSet rset=pstmt.executeQuery();
jtblFindData.setModel(DbUtils.resultSetToTableModel(rset));
For this I have used rs2xml.jar file.
Regards
Sandeep

Related

JTabbedPane, addChangeListener() only queries database on the last tab

Ok, so I am stuck with these loops. I have a tabbedPane and I add tabs to it, via data from database which I get with the line con.getKat() - (list of strings that represent categories). Then every tab should contain a JTable with contents from my database with all the records that contain the category(String) from the selected tab. The problem is that every tab triggers the ChangeListener() (which i check with System.out.println(kategorija)) but only the last tab displays data (no matter how i add or remove tabs it's always the last tab). Might be something silly here but any help appreciated.
ArrayList<String> ls = con.getKat();
for(String s : ls){
pane = new JScrollPane();
tabbedPane.addTab(s, null, pane, null);
}
tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
kategorija = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
System.out.println(kategorija);
ArrayList<Ceni> artikli = con.getHuroCeni(kategorija);
dtm.setRowCount(0);
for(Ceni c : artikli){
dtm.addRow(new Object[]{c.sifra, c.name, String.valueOf(c.cena1), c.tarifa});
table = new JTable();
table.setFont(new Font("Times New Roman", Font.PLAIN, 16));
table.setBorder(new BevelBorder(BevelBorder.LOWERED, new Color(128, 128, 128), null, null, null));
pane.setViewportView(table);
table.setModel(dtm);
}
}
});

How to change the font of a string in gui and then change it back again to normal

Hello fellow programmers across the world I am currently having a problem with one of my frames in my GUI. I have managed to change the font of my messeges to itallic and the color to grey and i have set my textfield to editable(true). The problem is that when I delete the string in gray and italic and try to write something useful in the textfield, rather that plain font and a color of black for the string it always comes out italic and gray. Is there any way that a string in a text message can change font and color and then then next string you write to have the normal font and black color? Would appreciate any sugggestions at this point. Here is my code:
void makeSecondFrame(){
frame2 = new JFrame("Step one!Vertification!");
Container contentPane2 = frame2.getContentPane();
JLabel label2 = new JLabel("Welcome to step 1 of our algorithm, Verification!" + "To varify yourself of owning an account please enter the following:");
JLabel label3 = new JLabel("First Name:");
JLabel label4 = new JLabel("Middle Name:");
JLabel label5 = new JLabel("Surname:");
JLabel label6 = new JLabel("Account Number:");
JLabel label7 = new JLabel ("Registration Number:");
firstName = new TextField("Enter your name here");
firstName.setForeground(Color.gray);
firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
firstName.setEditable(true);
middleName = new TextField("Enter your middle name here");
middleName.setForeground(Color.gray);
middleName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
middleName.setEditable(true);
surname = new TextField("Enter your surname here");
surname.setForeground(Color.gray);
surname.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
surname.setEditable(true);
accountNumber = new TextField("Enter your main account number");
accountNumber.setForeground(Color.gray);
accountNumber.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
accountNumber.setEditable(true);
registrationNumber = new TextField("Enter your registration number");
registrationNumber.setForeground(Color.gray);
registrationNumber.setFont(new java.awt.Font("Arail", Font.ITALIC, 12));
registrationNumber.setEditable(true);
JPanel p2 = new JPanel(new GridLayout(1,1));
p2.add(label2);
contentPane2.add(p2, BorderLayout.NORTH);
JPanel p3 = new JPanel(new GridLayout(10,1));
p3.add(label3);
p3.add(firstName);
p3.add(label4);
p3.add(middleName);
p3.add(label5);
p3.add(surname);
p3.add(label7);
p3.add(registrationNumber);
p3.add(label6);
p3.add(accountNumber);
contentPane2.add(p3, BorderLayout.WEST);
JButton next = new JButton("Next!");
next.addActionListener(this);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(this);
JPanel p4 = new JPanel(new GridLayout(1,1));
p4.add(next);
p4.add(cancel);
contentPane2.add(p4, BorderLayout.SOUTH);
frame2.pack();
frame2.setVisible(true);
}
You need to act on an appropriate action on the JTextField. The best I can think of is the FocusListener.focusGained():
firstName = new TextField("Enter your name here");
firstName.setForeground(Color.gray);
firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
firstName.setEditable(true);
firstName.addFocuListener(new FocusAdapter(){
#Overwrite
public void focusGained(FocusEvent e){
firstName.setText("");// remove help message, will also remove previously entered text!
firstName.setFont(new JTextField().getFont()); // reset to default
}
}
Well that did remove the helper message – Христо Петков
as I mentioned...
and I want to keep it – Христо Петков
Then you might want to use the other method in the FocusListener interface too:
#Overwrite
public void focusLost(FocusEvent e){
if(userDidNotEnterTextIn(firstName){ // hopefully you know how to find out...
firstName.setText("Enter your name here");
// do formatting again
}
}

Add a JScrollPane to avoid distortion of components

I am trying to make a variable size interface. However, currently, if the size of all components is greater than the dimension of the window, then those begin to
distort ! Therefore, I would like to add a JScrollPane to be displayed when the window size is no longer sufficient, in order to avoid this distortion.
I just started by adding a JScrollPane (as shown on the code bellow), but it does not seem to work, and I am not sure what to change now.
JScrollPane myScrollPane = new JScrollPane();
myWindow.getContentPane().add(myScrollPane, BorderLayout.CENTER);
EDIT 1: here is a simple example of what I have tried:
static void one(String[] ari, JLabel sess_nb, Box boxy, long[] res){
int p;
int length = ari.length;
Border cadre = BorderFactory.createLineBorder(Color.black);
Font police = new Font("Monospaced 13", Font.BOLD, 18);
Font police1 = new Font("Monospaced 13", Font.BOLD, 15);
Font font = new Font("Monospaced 13", Font.ITALIC, 13);
for (p=0;p<length;p++){
Box boxz = Box.createVerticalBox();
JLabel Rate = new JLabel("Rating Group "+r);
JLabel rg_reser = new JLabel();
JLabel switsh = new JLabel("1");
JLabel reser = new JLabel(); //in this label the resrvation for each update and each rating group will be stocked
JLabel consump = new JLabel(); //in this label will be stocked the consumption
//----------------------------------------------------
//choice of MB or kB
JComboBox combo = new JComboBox();
combo.addItem("Megabytes");
combo.addItem("Bytes");
combo.addItem("kilobytes");
combo.addItem("Gigabytes");
JLabel upload = new JLabel("Upload consumption:");
JTextField upload_entry = new JTextField("7.5");
JLabel download = new JLabel("Download consumption:");
JTextField download_entry = new JTextField("7.5");
JTextField total_entry = new JTextField();
JLabel total = new JLabel("Total consumption:");
JButton rg = new JButton("Next");
JLabel update = new JLabel("Result here");
boxz.add(Rate);
boxz.add(total);
boxz.add(total_entry);
boxz.add(upload);
boxz.add(upload_entry);
boxz.add(download);
boxz.add(download_entry);
boxz.add(combo);
boxz.add(rg);
boxz.add(update);
boxy.add(boxz);
scrollPane1.add(boxy);
}
EDIT 2: here is a new test code, but it also does not work:
public Fenetre(){
this.setTitle("Data Simulator");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
String hello = "hello";
int number = 69;
JPanel content = new JPanel();
content.setBackground(Color.LIGHT_GRAY);
//Box imad = Box.createHorizontalBox();
JTextArea textArea = new JTextArea(10, 10);
JLabel imad = new JLabel();
imad.setText(hello + " your favorite number is " + number + "\nRight?");
JScrollPane scrollPane = new JScrollPane();
setPreferredSize(new Dimension(450, 110));
scrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setEnabled(true);
scrollPane.setWheelScrollingEnabled(true);
scrollPane.setViewportView(textArea);
scrollPane.setViewportView(imad);
add(scrollPane, BorderLayout.CENTER);
//---------------------------------------------
//On ajoute le conteneur
content.add(imad);
content.add(textArea);
content.add(scrollPane);
this.setContentPane(content);
this.setVisible(true);
this.setResizable(false);
}
A small white scare appears (I think it is the scroll bar or scroll panel?) and the components in the window exceeds the windows size but nothing happens when I try to scroll (using the mouse or by clinking on the white scare). I don't know what is wrong.
Don't use scrollPanel.add(boxy) - you need to add boxy to the scrollPanel's viewport, not to the scrollPanel itself. Use scrollPanel.setViewportView(boxy) instead, or better yet create the ScrollPanel AFTER you create boxy and use the constructor that takes a Component argument.

Entering various values in mysql from various JCheckboxes in JAVA

I have the following 4 JChecboxes in my form. If the user clicks all the four, or any choices of JCheckboxes how do I save the values from the checboxes in mysql database in one sigle column? When I click my Add button, it should stored all the values from the selected checkboxes Please help.. Thanks
My codes :
foreign = new JCheckBox("Foreign");
foreign.setFont(new Font("Tahoma", Font.BOLD, 12));
foreign.setForeground(new Color(240, 255, 240));
foreign.setBounds(16, 25, 97, 23);
foreign.setOpaque(false);
panel.add(foreign);
travelling = new JCheckBox("Travelling");
travelling.setFont(new Font("Tahoma", Font.BOLD, 12));
travelling.setForeground(new Color(240, 255, 240));
travelling.setBounds(150, 26, 97, 23);
travelling.setOpaque(false);
panel.add(travelling);
danger = new JCheckBox("Danger Pay");
danger.setFont(new Font("Tahoma", Font.BOLD, 12));
danger.setForeground(new Color(240, 255, 240));
danger.setBounds(16, 68, 97, 23);
danger.setOpaque(false);
panel.add(danger);
medical = new JCheckBox("Medical Scheme");
medical.setFont(new Font("Tahoma", Font.BOLD, 12));
medical.setForeground(new Color(240, 255, 240));
medical.setBounds(150, 69, 121, 23);
medical.setOpaque(false);
panel.add(medical);
add = new JButton("Add");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int id1 = Integer.parseInt(id.getText());
String fn = fname.getText();
String ln = lname.getText();
String po = pos.getText();
String sa = sal.getText();
String all = "";
if(foreign.isSelected() && travelling.isSelected() && danger.isSelected() && medical.isSelected()){
all = "Foreign, Travelling, Danger, Medical";
}else if(foreign.isSelected() && travelling.isSelected() && danger.isSelected()){
all = "Foreign, Travelling, Danger";
}else if(foreign.isSelected() && travelling.isSelected()){
all = "Foreign, Travelling";
}else if()
}
});
You could save the data in a separate table. What I mean by this is that suppose you are storing the data in a table temp which is having 2 columns - id and selection. Now my suggestion is that you create 2 tables one for id and the other for selection. the selection table will have 2 columns id and selection. the id column is to be a foreign key to the id table's id column.
Now when the user having id say 01 selects "Foreign" & "Travelling", then you make 2 entries in the selection table that are 01 - Foreign and 01 - Travelling
Now when the user having id say 02 selects all the options then you are to make 4 entries in the selection table against the id of the user:
02-Foreign,
02-Travelling,
02-Danger,
02-Medical
This way you could save each selection separately.
After getting you comment
After your comment I could only suggest that you create 4 columns of boolean type in the table and store the state of each checkBox in each column.

Multiple choice test GUI with serialization of Q&A

I'm working on a project for school in Java programming. I need to design a GUI that will take in questions and answers and store them in a file. It should be able to contain an unlimited number of questions. We have covered binary I/O.
How do I write the input they give to a file? How would I go about having them add multiple questions from this GUI?
package multiplechoice;
import java.awt.*;
import javax.swing.*;
public class MultipleChoice extends JFrame {
public MultipleChoice() {
/*
* Setting Layout
*/
setLayout(new GridLayout(10,10));
/*
* First Question
*/
add(new JLabel("What is the category of the question?: "));
JTextField category = new JTextField();
add(category);
add(new JLabel("Please enter the question you wish to ask: "));
JTextField question = new JTextField();
add(question);
add(new JLabel("Please enter the correct answer: "));
JTextField correctAnswer = new JTextField();
add(correctAnswer);
add(new JLabel("Please enter a reccomended answer to display: "));
JTextField reccomendedAnswer = new JTextField();
add(reccomendedAnswer);
add(new JLabel("Please enter a choice for multiple choice option "
+ "A"));
JTextField A = new JTextField();
add(A);
add(new JLabel("Please enter a choice for multiple choice option "
+ "B"));
JTextField B = new JTextField();
add(B);
add(new JLabel("Please enter a choice for multiple choice option "
+ "C"));
JTextField C = new JTextField();
add(C);
add(new JLabel("Please enter a choice for multiple choice option "
+ "D"));
JTextField D = new JTextField();
add(D);
add(new JButton("Compile Questions"));
add(new JButton("Next Question"));
}
public static void main(String[] args) {
/*
* Creating JFrame to contain questions
*/
FinalProject frame = new FinalProject();
// FileOutputStream output = new FileOutputStream("Questions.dat");
JPanel panel = new JPanel();
// button.setLayout();
// frame.add(panel);
panel.setSize(100,100);
// button.setPreferredSize(new Dimension(100,100));
frame.setTitle("FinalProject");
frame.setSize(600, 400);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
First:
There are basically two ways to write to a file in java.
ObjectOutputStream(FileOutputStream("blah")) API
PrintWriter("blah") API
Second:
Three or more; use a for.
This is what comes to mind for me when reading JTextField A = new JTextField(); and JTextField B = new JTextField();

Categories

Resources