event mouseclicked in java not working to populate text field - java

I am making a gui with netbeans. I right clicked a JTable to add event listener for mouse clicked. I added my code to the new method. For the life of me when I click the JTable I get no errors.
Any ideas on what I am doing wrong or how to fix it? if you need to see more of my code let me know. everything besides the connection to the DB is ran out of the driver class.
I moved my program to eclipse to make this easier for me to trouble shoot.
private void tableDisplayMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tableDisplay.getSelectedRow();
String tableClick = (tableDisplay.getModel().getValueAt(row, 1).toString());
String sql = " select * from contact where id = ' " + tableClick + " ' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()) {
System.out.println("hey dude this method is being called.");
String add2 = rs.getString("Business_Name");
fieldBN.setText(add2);
String add3 = rs.getString("First_Name");
fieldFN.setText(add3);
String add4 = rs.getString("Last_Name");
fieldLN.setText(add4);
String add5 = rs.getString("Phone");
fieldP.setText(add5);
String add6 = rs.getString("Email");
fieldE.setText(add6);
String add7 = rs.getString("Address_Line_1");
fieldA.setText(add7);
String add8 = rs.getString("Address_Line_2");
aLine2.setText(add8);
String add9 = rs.getString("Website");
fieldW.setText(add9);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Here is the onclick method
Here is my even listener
public Driver() {
gui();
conn = DbConnect.ConnectDb();
UpdateTable();
tableDisplay.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableDisplayMouseClicked(evt);
}
});
}
Here is the whole Driver Class:
import java.awt.BorderLayout;
public class Driver {
private JFrame f;
private JPanel p;
private JTextField fieldBN;
private JTextField fieldFN;
private JTextField fieldLN;
private JTextField fieldP;
private JTextField fieldE;
private JTextField fieldA;
private JTextField aLine2;
private JTextField fieldW;
private JLabel labelBN;
private JLabel labelFN;
private JLabel labelLN;
private JLabel labelP;
private JLabel labelE;
private JLabel labelA;
private JLabel labelW;
private JComboBox relationship;
private JButton buttonS;
private JTable tableDisplay;
String[] relationshipValues = { "Business", "Friend", "Family", "Professional" };
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
// Constructor:
public Driver() {
gui();
conn = DbConnect.ConnectDb();
UpdateTable();
tableDisplay.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableDisplayMouseClicked(evt);
}
});
}
public void gui() {
f = new JFrame("Contact Book");
GridBagConstraints c = new GridBagConstraints();
p = new JPanel(new GridBagLayout());
f.getContentPane().add(p, BorderLayout.NORTH);
c.gridx = 0;
c.gridy = 0;
labelBN = new JLabel ("Business Name:");
p.add(labelBN, c);
c.gridx = 1;
c.gridy = 0;
fieldBN = new JTextField(10);
p.add(fieldBN, c);
c.gridx = 0;
c.gridy = 1;
labelFN= new JLabel ("First Name:");
p.add(labelFN, c);
c.gridx = 1;
c.gridy = 1;
fieldFN = new JTextField (10);
p.add(fieldFN, c);
c.gridx = 0;
c.gridy = 2;
labelLN= new JLabel ("Last Name:");
p.add(labelLN, c);
c.gridx = 1;
c.gridy = 2;
fieldLN = new JTextField (10);
p.add(fieldLN, c);
c.gridx = 0;
c.gridy = 3;
labelP = new JLabel ("Phone Number:");
p.add(labelP, c);
c.gridx = 1;
c.gridy = 3;
fieldP = new JTextField (10);
p.add(fieldP, c);
c.gridx = 0;
c.gridy = 4;
labelE = new JLabel ("Email:");
p.add(labelE, c);
c.gridx = 1;
c.gridy = 4;
fieldE = new JTextField (10);
p.add(fieldE, c);
c.gridx = 0;
c.gridy = 5;
labelA = new JLabel ("Address:");
p.add(labelA, c);
c.gridx = 1;
c.gridy = 5;
fieldA = new JTextField (10);
p.add(fieldA, c);
c.gridx = 1;
c.gridy = 6;
aLine2 = new JTextField (10);
p.add(aLine2, c);
c.gridx = 0;
c.gridy = 7;
labelW = new JLabel ("Website:");
p.add(labelW, c);
c.gridx = 1;
c.gridy = 7;
fieldW = new JTextField (10);
p.add(fieldW, c);
c.gridx = 0;
c.gridy = 8;
labelW = new JLabel ("Relationship:");
p.add(labelW, c);
c.gridx = 1;
c.gridy = 8;
relationship = new JComboBox(relationshipValues);
p.add(relationship, c);
c.gridx = 1;
c.gridy = 9;
buttonS = new JButton("Save:");
p.add(buttonS, c);
c.gridx = 0;
c.gridy = 10;
tableDisplay = new JTable();
p.add(tableDisplay, c);
// pack the frame for better cross platform support
f.pack();
// Make it visible
f.setVisible(true);
f.setSize(1400,900); // default size is 0,0
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // End of Gui Method
private void UpdateTable() {
try {
String sql = "SELECT * FROM contact";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
tableDisplay.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void tableDisplayMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tableDisplay.getSelectedRow();
String tableClick = (tableDisplay.getModel().getValueAt(row, 1).toString());
String sql = " select * from contact where id = ' " + tableClick + " ' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()) {
System.out.println("hey dude this method is being called.");
String add2 = rs.getString("Business_Name");
fieldBN.setText(add2);
String add3 = rs.getString("First_Name");
fieldFN.setText(add3);
String add4 = rs.getString("Last_Name");
fieldLN.setText(add4);
String add5 = rs.getString("Phone");
fieldP.setText(add5);
String add6 = rs.getString("Email");
fieldE.setText(add6);
String add7 = rs.getString("Address_Line_1");
fieldA.setText(add7);
String add8 = rs.getString("Address_Line_2");
aLine2.setText(add8);
String add9 = rs.getString("Website");
fieldW.setText(add9);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Driver();
}
});
} // End main Method
} // End class Driver

It's difficult to know why you're having issues with the registering a MouseListener, there's not enough context to diagnose the problem.
You should start by placing out put statements in the code to check to see if the method is been called and that the query is returning values.
If all else fails, you should try regsitering the mouse listener manually. See How to Write a Mouse Listener for more details.
You query is also including spaces in the match...
String sql = " select * from contact where id = ' " + tableClick + " ' ";
^------------------^-----
Which will affect the ability for the database to match results to your query. Try removing these
String sql = " select * from contact where id = '" + tableClick + "'";

Related

My image is not added to the GUI as the background [duplicate]

This question already has answers here:
How do I draw an image to a JPanel or JFrame?
(2 answers)
Trying to draw an image on a JFrame
(1 answer)
Closed 29 days ago.
`import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class RPS implements ActionListener {
JFrame frame;
JPanel panel;
JButton buttonR;
JButton buttonP;
JButton buttonS;
JLabel title;
JLabel comChoice;
JLabel result;
ImageIcon img;
JLabel image;
JTextField name;
int userPoints = 0;
int compPoints = 0;
String userInput;
String rand1;
JLabel ps;
JLabel cs;
public RPS() {
frame = new JFrame();
panel = new JPanel(new GridBagLayout());
buttonR = new JButton("ROCK");
buttonP = new JButton("PAPER");
buttonS = new JButton("SCISSORS");
title = new JLabel("ROCK vs PAPER vs SCISSORS");
ps = new JLabel("Player Score : 0");
cs = new JLabel("Computer Score : 0");
comChoice = new JLabel("Computer choice : " );
result = new JLabel("");
name = new JTextField();
name.setPreferredSize(new Dimension(250,40));
image = new JLabel("",new ImageIcon(background.jpg"),JLabel.CENTER);
frame.add(image);
GridBagConstraints c = new GridBagConstraints(); //ADDING THE COMPONENTS
c.insets = new Insets(30, 30, 30, 30);
c.gridx = 3;
c.gridy = 0;
title.setFont(new Font("Rockwell Condensed", Font.BOLD, 40));
panel.add(title, c);
c.gridx = 3;
c.gridy = 1;
panel.add(result, c);
c.gridx = 3;
c.gridy = 1;
panel.add(name,c);
c.insets = new Insets(10, 10, 10, 10);
c.gridx = 4;
c.gridy = 2;
panel.add(buttonR, c);
c.gridx = 3;
c.gridy = 2;
panel.add(buttonP, c);
c.gridx = 2;
c.gridy = 2;
panel.add(buttonS, c);
c.insets = new Insets(15, 15, 15, 15);
c.gridx = 2;
c.gridy = 3;
panel.add(ps, c);
c.gridx = 4;
c.gridy = 3;
panel.add(cs, c);
c.insets = new Insets(15, 15, 15, 15);
c.gridx = 3;
c.gridy = 3;
panel.add(comChoice, c);
buttonR.addActionListener(this);
buttonP.addActionListener(this);
buttonS.addActionListener(this);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(540,399);
frame.setTitle("Rock Paper Scissors");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new RPS();
}
private String computerChoice() {
Random rand = new Random();
String compGuess[] = {"ROCK", "PAPER", "SCISSORS"};
String rand1 = compGuess[rand.nextInt(3)];
comChoice.setText("Computer choice : " + rand1);
return rand1;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonR) {
userInput = "ROCK";
computerChoice();
rand1 = computerChoice();
compare();
}
if (e.getSource() == buttonP) {
userInput = "PAPER";
computerChoice();
rand1 = computerChoice();
compare();
}
if (e.getSource() == buttonS) {
userInput = "SCISSORS";
rand1 = computerChoice();
compare();
}
}
private void compare() {
if (userInput.contains("ROCK"))
{
if (rand1 == "PAPER")
{
compPoints++;
cs.setText("Computer Score : "+Integer.toString(compPoints));
ps.setText(name.getText()+"'s Score : "+Integer.toString(userPoints));
result.setText("YOU LOSE !");
} else if (rand1 == "SCISSORS")
{
userPoints++;
ps.setText(name.getText()+"'s Score : "+Integer.toString(userPoints));
result.setText("YOU WIN !");
}
else
{
result.setText("IT'S A DRAW !");
}
} else if (userInput.contains("PAPER"))
{
if (rand1 == "ROCK")
{
userPoints++;
ps.setText(name.getText()+"'s Score : "+Integer.toString(userPoints));
result.setText("YOU WIN !");
} else if (rand1 == "SCISSORS")
{
compPoints++;
cs.setText("Computer Score : "+Integer.toString(compPoints));
ps.setText(name.getText()+"'s Score : "+Integer.toString(userPoints));
result.setText("YOU LOSE !");
}
else
{
result.setText("IT'S A DRAW !");
}
} else if (userInput.contains("SCISSORS"))
{
if (rand1 == "PAPER")
{
userPoints++;
ps.setText(name.getText()+"'s Score : "+Integer.toString(userPoints));
result.setText("YOU WIN !");
} else if (rand1 == "ROCK")
{
compPoints++;
cs.setText("Computer Score : "+Integer.toString(compPoints));
ps.setText(name.getText()+"'s Score : "+Integer.toString(userPoints));
result.setText("YOU LOSE !");
}
else
{
result.setText("IT'S A DRAW !");
ps.setText(name.getText()+"'s Score : "+Integer.toString(userPoints));
}
}
else
{
result.setText("IT'S A DRAW !");
}
}
}`
I already added the background file under the project file but the image is not added to the GUI.
I am very new to JAVA so maybe this is a silly mistake but I really hope somebody can help me with this. I tried other methods but most will give me errrors only this version of code that can rude but the image is not added at all.

Java AWT controls issue

I'd like to create a calculator using Java AWT library, however I'm having problems putting a label and a textfield on the same row. Also, everything is mixing up. When I run the program, at first it shows 2 labels and 2 textfields on the same row, but if I resize it, the labels, buttons & textfields are one on top of another. Could you please help me?
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Calculator extends Frame {
public static void main(String[] args) {
Frame frame= new Frame();
frame.setTitle("Mini Calculator App");
frame.setVisible(true);
frame.setSize(300,300);
LayoutManager gridBagLayout = new GridBagLayout();
frame.setLayout(gridBagLayout);
Label firstNumber = new Label("Add a number");
frame.add(firstNumber);
TextField numar1 = new TextField();
frame.add(numar1);
Label secondNumber = new Label("Add another number");
frame.add(secondNumber);
TextField numar2 = new TextField();
frame.add(numar2);
Choice operatie = new Choice();
operatie.add("+"); operatie.add("-");
operatie.add("*"); operatie.add("/");
frame.add(operatie);
Button calcul = new Button("Calculate");
frame.add(calcul);
Label result = new Label("Result is");
frame.add(result);
GridBagConstraints afisare;
afisare = new GridBagConstraints();
afisare.gridx = 0;
afisare.gridy = 0;
frame.add(firstNumber, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 0;
afisare.gridy = 1;
afisare.gridwidth = 10;
afisare.gridheight = 10;
frame.add(numar1, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 1;
afisare.gridy = 0;
frame.add(secondNumber, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 1;
afisare.gridy = 1;
frame.add(numar2, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 2;
afisare.gridy = 1;
frame.add(operatie, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 4;
afisare.gridy = 0;
frame.add(result, afisare);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
enter image description here
enter image description here

Placement of bufferedreader.close()

I am having some trouble in the placement of sections of my code. I am a high school student, and for a project I am making a flashcards app. I am using read/write to store the user's data. I am having trouble on where to close my buffered reader.
This is some of my code:
try {
FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read);
for (int row=0; row < lineNumber; row++) {
try {
//Reads the set and the subject in the text file
String strSetSubjectLine = br1.readLine();
//Splits the string of set and subject by using the comma
String [] names = strSetSubjectLine.split(",");
strSetName = names[0];
strSubjectName = names[1];
//Finds the line number to see the number of cards in each set
lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
lnr2.skip(Long.MAX_VALUE);
strLineNumber2 = String.valueOf(lnr2.getLineNumber());
lineNumber2 = Integer.parseInt(strLineNumber2);
} catch (IOException | NumberFormatException e) {
strLineNumber2 = "0";
}
//Adds the set name to the set name array
lblDeckName[row] = new JLabel (strSetName);
//Adds all buttons that will be used in the layout into a button array
JButton aryOptions [][] = new JButton [3][lineNumber];
//Defines and formats the Add Words button
JButton btnAddWords = new JButton("Add Words");
btnAddWords.setOpaque(false);
btnAddWords.setContentAreaFilled(false);
btnAddWords.setBorder(null);
btnAddWords.setBorderPainted(false);
//Defines and formats the Play button
JButton btnPlay = new JButton("Play");
btnPlay.setOpaque(false);
btnPlay.setContentAreaFilled(false);
btnPlay.setBorder(null);
btnPlay.setBorderPainted(false);
//Defines and formats the Delete Set button
JButton btnDelete = new JButton("Delete Set");
btnDelete.setOpaque(false);
btnDelete.setContentAreaFilled(false);
btnDelete.setBorder(null);
btnDelete.setBorderPainted(false);
//Adds each button to the array based on the number of sets
aryOptions [0][row] = btnAddWords;
aryOptions [1][row] = btnPlay;
aryOptions [2][row] = btnDelete;
//Formats the GridBagLayout (Spaces are for formatting purposes)
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = row;
layoutBackground.add(lblDeckName[row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = row;
layoutBackground.add(new JLabel(" "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx =2;
gbc.gridy = row;
layoutBackground.add(new JLabel (strSubjectName),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = row;
layoutBackground.add(new JLabel(" "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = row;
layoutBackground.add(new JLabel(strLineNumber2),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 5;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 6;
gbc.gridy = row;
layoutBackground.add(aryOptions[0][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 7;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 8;
gbc.gridy = row;
layoutBackground.add(aryOptions[1][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 9;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 10;
gbc.gridy = row;
layoutBackground.add(aryOptions[2][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 11;
gbc.gridy = row;
layoutBackground.add(new JLabel(" |"),gbc);
//Creates an action event for the delete set button
btnDelete.addActionListener((ActionEvent a) -> {
//Finds the source of the button that was clicked
String strSource = String.valueOf(a.getSource());
String strSourceCut1 = strSource.substring(25,30);
//Finds the index of the button that was clicked
String [] aryIndex = strSourceCut1.split(",");
String strIndex = aryIndex[0];
try {
//Defines new file reader and buffered reader
FileReader file_to_read2 = new FileReader(path);
BufferedReader br2 = new BufferedReader(file_to_read2);
//Finds the numerical index of the button that was clicked
int intIndex = Integer.parseInt(strIndex)/16;
//Creates a counter to count line numbers
int counter = 0;
while((br2.readLine()) != null) {
counter ++;
if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
try {
//Finds the name of the set based on what button was clicked
String chosenDeck2 = br2.readLine();
String [] aryDeleteDeck = chosenDeck2.split(",");
deleteDeck = aryDeleteDeck[0];
//Creates the path to the file that needs to be deleted
Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
Files.delete(p2);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
} else if ( counter == intIndex) {
//Reads the deck name based on the button that was clicked
String chosenDeck2 = br2.readLine();
//Splits the deck name from the subject
String [] aryDeleteDeck = chosenDeck2.split(",");
deleteDeck = aryDeleteDeck[0];
//Closes the buffered reader and file reader
//Gets the file that needs to be deleted
Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
Files.delete(p1);
}
}
br2.close();
file_to_read2.close();
}
catch (HeadlessException | IOException | NumberFormatException e) {
JOptionPane.showMessageDialog(null, e);
}
});
//Creates an action event for the add words button
btnAddWords.addActionListener((ActionEvent a) -> {
//Finds the source of the button that was clicked
String strSource = String.valueOf(a.getSource());
String strSourceCut1 = strSource.substring(25,30);
//Finds the index of the button that was clicked
String [] aryIndex = strSourceCut1.split(",");
String strIndex = aryIndex[0];
try {
//Creates a new file reader and buffered reader
FileReader file_to_read3 = new FileReader(path);
BufferedReader br3 = new BufferedReader(file_to_read3);
//Finds the index value
int intIndex = Integer.parseInt(strIndex)/16;
//Creates a counter to count line numbers
int counter = 0;
while((br3.readLine()) != null) {
//Increases counter value by 1
counter ++;
if(intIndex == 0)
{
try {
//Reads the set and subject for the
String chosenDeck2 = br3.readLine();
//Splits the subject from the set
String [] aryDeck = chosenDeck2.split(",");
chosenDeck = aryDeck[0];
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
} else if ( counter == intIndex) {
String chosenDeck2 = br3.readLine();
String [] aryDeck = chosenDeck2.split(",");
chosenDeck = aryDeck[0];
}
}
br3.close();
file_to_read3.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
//Opens the new words frame
frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
s.setVisible(true);
});
}
} catch (Exception e ) {
JOptionPane.showMessageDialog(null, e);
}
}
The problem I am facing is when I close my buffered reader "br1". If I close it in the for loop, I get a stream closed error, if I close it after the for loop, my other readers will not work. If I move the declaration of the reader into the for loop and try a try with resources statement, it will read the same line over and over again. If I try to make them all work off 1 buffered reader I get a stream closed error as well.
I am really stuck, and would really appreciate some help.
Thanks :)
You may rearrange your exception handling to use this properly.
try
{
//trying something
}
catch(SomeException e)
{
//we failed
e.printStackTrace();
}
finally
{
//called when we failed or when we succeeded, even after a return; statement
}
EDIT
This will pre-read the file and store the data in an ArrayList. Afterwards it closes the stream.
try {
FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read);
ArrayList<String> linesRead = new ArrayList<String>();
String line = br1.readLine();
while(line != null)
{
linesRead.add(line);
line = br1.readLine();
}
br1.close();
for (int row=0; row < lineNumber; row++) {
try {
//Reads the set and the subject in the text file
String strSetSubjectLine = linesRead.get(row);

JTable doesn't refresh when my database query is executed

This is a JDBC project. Data from a MySQL database on a WAMP server is displayed in a JTable. I want a user-entered ID on my JSpinner to delete the row with that ID from the table. I made a SQL Query and everything works, but the data on the my JTable doesn't refresh when my query is executed. I click my JNazad button (my back button), and reenter that window so that my JTable shows refreshed data. I don't implemented FireTableModel in my NapraviTablicu method, because its DefaultTableModel, and updates are automatically done with it . I don't know what I did wrong:
public class GUIBDelete extends JFrame{
private SpinnerModel SM;
private JSpinner Spinner;
private JLabel LUnos;
private JButton BNazad, BIzvrsi;
private String ID, SqlQuery;
private Vector NaziviKolona = new Vector();
private Vector Podaci = new Vector();
private JTable Tablica=new JTable();
private JScrollPane ScrollPane;
private DefaultTableModel model;
private JTable NapraviTablicu(){
try {
String SqlQuery = "SELECT * FROM `nfc_baza`";
Podaci.clear();
NaziviKolona.clear();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://"
+ "localhost:3306/nfc", "root", "");
Statement Stat = con.createStatement();
ResultSet Rez = Stat.executeQuery(SqlQuery);
ResultSetMetaData md = Rez.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
NaziviKolona.addElement(md.getColumnName(i));
}
while (Rez.next()) {
Vector red = new Vector(columns);
for (int i = 1; i <= columns; i++) {
red.addElement(Rez.getObject(i));
}
Podaci.addElement(red);
}
Rez.close();
Stat.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
model = new DefaultTableModel(Podaci, NaziviKolona);
JTable table = new JTable(model);
return table;
}
ActionListener a1 = new ActionListener() {
public void actionPerformed(ActionEvent a) {
dispose();
new GUIIzbornik();
}
};
ActionListener a2 = new ActionListener() {
public void actionPerformed(ActionEvent a) {
ID=null;
SqlQuery = "DELETE FROM `nfc`.`nfc_baza` WHERE `nfc_baza`.`ID` = ";
IzvrsiQuery();
}
private void IzvrsiQuery() {
Object sp = Spinner.getValue();
ID = sp.toString();
SqlQuery=SqlQuery+ID;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con2 = DriverManager.getConnection(
"jdbc:mysql://" + "localhost:3306/nfc", "root", "");
Statement Stat = con2.createStatement();
int Rez = Stat.executeUpdate(SqlQuery);
Stat.close();
con2.close();
JOptionPane.showMessageDialog(null, "Uspješno izvrseno!",
"Poruka!", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
System.out.println(e);
}
}
};
GUIBDelete(){
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
Tablica=NapraviTablicu();
ScrollPane = new JScrollPane(Tablica);
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(2, 2, 2, 2);
c.weightx = 0.1;
c.weighty = 0.1;
c.gridwidth = 4;
c.gridheight = 2;
c.gridx = 0;
c.gridy = 0;
add(ScrollPane, c);
LUnos= new JLabel("<html><br>Unesite ID elementa</br> kojeg želite obrisati:<html>");
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
add(LUnos, c);
SM = new SpinnerNumberModel(1, 1, 1000, 1);
Spinner = new JSpinner(SM);
c.gridx = 2;
c.gridy = 2;
c.gridwidth = 2;
add(Spinner, c);
BNazad = new JButton("Nazad");
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
BNazad.addActionListener(a1);
add(BNazad, c);
BIzvrsi = new JButton("Izvrši");
c.gridx = 2;
c.gridy = 3;
BIzvrsi.addActionListener(a2);
add(BIzvrsi, c);
setSize(400, 500);
setTitle("Brisanje podataka");
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUIBDelete i = new GUIBDelete();
}
});
}
}
It looks like you're deleting a row from a database table, and you want the JTable to reflect the change. In izvrsiQuery() update your TableModel and the JTable will update itself. For example,
...
con2.close();
model.removeRow(((Number)(spinner.getValue())).intValue() - 1);
JOptionPane.showMessageDialog(...);
...
Note that row numbers start at 0, and they must be translated when using a RowSorter.
As an aside, your code will be easier for others to read if you use common Java naming conventions and factor out constants.
Addendum: The example just removes a row by number. You'll have to search your TableModel for the row that corresponds to the deleted ID.
Addendum: Although less practical, you may want to refresh the entire table from the database after a DML operation using setModel(), as shown here.

pressing ENTER key do not work for JTextField in applet

I have a JTextField in a JApplet with a ActionListener. I compiled it using Eclipse and it works fine. But when I try to load it in a .html file using applet, the JTextField does not register/recognize the ENTER key when I press it. It seems like the ActionListener did not work. I used:
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
question = ProcessString(question);
answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
static String noAnswer;
static boolean knowAnswer = true;
// process the question string, take out non-ACSII characters, spaces, to
// lower space
public String ProcessString(String question) {
question = question.toLowerCase();
String[] words = question.split("\\s+");
question = "";
for (int wordCount = 0; wordCount < words.length; wordCount++) {
words[wordCount] = words[wordCount].replaceAll("[^A-Za-z]", "");
if (wordCount != words.length - 1)
question = question + words[wordCount] + " ";
else
question = question + words[wordCount];
// System.out.println(words[wordCount]);
}
return question;
}
public String Answer(String question) {
String answer = "";
/*
if the database know the answer (did not not know), then return the
answer. if the database does not know the answer, then recover the
answer in database.
*/
if (knowAnswer == true) {
// open the database file and search if questions matches any one in
// the
// database
Scanner sc = null;
try {
sc = new Scanner(new File("database.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int answerFrequency = 0;
boolean matchFound = false;
while (sc.hasNext()) {
int questionCount = sc.nextInt();
String line = sc.nextLine();
String[] databaseLine = line.split("\\s+");
String databaseQuestion = "";
String databaseAnswer = "";
// collect words for database questions
for (int wordCount = 1; wordCount <= questionCount; wordCount++) {
if (wordCount != questionCount)
databaseQuestion = databaseQuestion
+ databaseLine[wordCount] + " ";
else
databaseQuestion = databaseQuestion
+ databaseLine[wordCount];
}
// collect words for database answer
for (int wordCount = questionCount + 2; wordCount < databaseLine.length; wordCount++) {
databaseAnswer = databaseAnswer + databaseLine[wordCount]
+ " ";
}
// if the question is found in database, print answer
if (question.equals(databaseQuestion)) {
matchFound = true;
// the current answer is more frequency than the previous
// found
// answer, reassign the current answer the find answer
if (answerFrequency < Integer
.parseInt(databaseLine[questionCount + 1])) {
answerFrequency = Integer
.parseInt(databaseLine[questionCount + 1]);
answer = databaseAnswer;
}
}
}
if (matchFound == true) {
// System.out.println(answer);
knowAnswer = true;
} else {
// System.out.println("I don't know what you mean. How should I answer your question?");
knowAnswer = false;
noAnswer = question;
answer = "I don't know how to respond. How should I answer that?";
}
sc.close();
} else if (knowAnswer == false) {
String[] word = noAnswer.split(" ");
BufferedWriter writer = null;
answer = question;
try {
writer = new BufferedWriter(
new FileWriter("database.txt", true));
writer.newLine();
writer.write(word.length + " " + noAnswer + " 1 " + answer);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
System.out.println("Cannot write to file");
}
}
answer = "I got that.";
knowAnswer = true;
}
return answer;
}
Really appreciate the help.
This seems to work for me....
public class TestApplet04 extends JApplet implements ActionListener {
private JTextField textField;
private JTextArea textArea;
private String newline;
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
// question = ProcessString(question);
// answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
}
Updated after feedback
Here's you major problem...
sc = new Scanner(new File("database.txt"));
This is going to cause you a number of problems. First of all, the applet isn't likely to have access rights to read from the client machine, so you're likely to run into a security exception. Secondly, as the previous statement may have suggested, the file ins't likely to exist on the client machine.
You need to embed this resource within the Jar of your application and use getClass().getResource("...") to gain access to it. This will return a URL, from which you can use URL#openConnection to gain access to a InputStream, which can use in your scanner.
Try adding an Action to the ActionMap and setting the InputMap up for ENTER key.
textField.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter" );
textField.getActionMap().put("enter", new AbstractAction() {...} );
The field will have to have focus.
I'm also a newbie to Java, but found out that JTextfield is only a single line entry.
If you want a multiline entry, you would need to use a JTextArea instead.
Hope this helps :)

Categories