How do I call variables from a Java class in another Class - java

If I have a class with prepared statements, how do I call them when a user presses a button.
class updateeButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
name = displayName.getText();
price = bookPrice.getText();
Queries update = new Queries();???????????????????
}
}
Prepared Statement in different class
public int update(String price, String name) throws SQLException {
ps2.setString(1, name);
ps2.setString(2, price);
System.out.print("Update - ");
return ps2.executeUpdate();
}

Create an object and invoke the update method with parameters as shown below:
public void actionPerformed(ActionEvent e) {
name = displayName.getText();
price = bookPrice.getText();
Queries update = new Queries();
update.update(price, name);//invoke the method using the object
}

Related

Do I have to create another RowMapper?

I'm developing this application to fetch data from a single table from an existing Oracle database.
Here we've got the entity:
public class OrdemDeServicoCount {
private Long ordensInternas;
private Long ordensAtrasadas;
// assume getters and setters
}
The mapper:
public class OrdemMapper implements RowMapper<OrdemDeServicoCount> {
#Override
public OrdemDeServicoCount mapRow(ResultSet rs, int rowNum) throws SQLException {
OrdemDeServicoCount ordens = new OrdemDeServicoCount();
ordens.setOrdensInternas(rs.getLong("ordensInternas"));
// ordens.setOrdensAtrasadas(rs.getLong("ordensAtrasadas"));
return ordens;
}
}
And finally, the DAO:
public class OrdemDAO {
private JdbcTemplate jdbcTemplate;
public OrdemDAO(JdbcTemplate jdbcTemplate) {
super();
this.jdbcTemplate = jdbcTemplate;
}
public List<OrdemDeServicoCount> countOrdensInternasSemEncerrar() {
String sql = "SELECT COUNT(a.nr_sequencia) AS ordensInternas FROM MAN_ORDEM_SERVICO a "
+ "WHERE a.IE_STATUS_ORDEM IN (1,2) AND a.NR_GRUPO_PLANEJ IN (21)";
List<OrdemDeServicoCount> ordens = jdbcTemplate.query(sql, new OrdemMapper());
return ordens;
}
By the way, you all must know that if I declare uncomment the line ordens.setOrdensInternas(rs.getLong("ordensInternas")); in the mapper, I would get an error, because in my DAO, I'm not using that field.
But what if I need to create another method that uses just the ordensInternas field? Then again, I'd get an error...
So, my doubt here is: if I need to use the ordensAtrasadas field from the entity, will I have to create another class just to implement another mapper? Or is there a way that I can do any conditional in my current OrdemMapper class?
Just put your assignments in individual try-catch statements.
public class OrdemMapper implements RowMapper<OrdemDeServicoCount> {
#Override
public OrdemDeServicoCount mapRow(ResultSet rs, int rowNum) throws SQLException {
OrdemDeServicoCount ordens = new OrdemDeServicoCount();
try {
ordens.setOrdensInternas(rs.getLong("ordensInternas"));
} catch (SQLException ex) {
// This will happen if the columnIndex is invalid among other things
}
try {
ordens.setOrdensAtrasadas(rs.getLong("ordensAtrasadas"));
} catch (SQLException ex) {
// This will happen if the columnIndex is invalid among other things
}
return ordens;
}
}

Java netbeans How to pass value to jComboBox

How to pass value from one class to jcombobox in another class
Public void getItem (){
try {
dBconnection...
while(rs.next){
String customers = rs.getString (1);
this.jcombobox1.addItem (customers);
}
}
}
From this method to jcombobox in another class. The error is in jcombobox?
Since you are already having B's class object in A lets say ex Bclassobj.
Public void getItem (){
try {
while(rs.next){
this.jcombobox1.addItem (rs.getString (1));
Bclassobj.Bclassjcombobox.addItem (rs.getString (1));
}
}
}
Generally this is a poor way of coding, no offense.
You should not mix the code for:
Getting the connection to database
Executing some SQL command and fetching data from ResultSet
Creating graphics
Simply change your method Public void getItem () to Public List<String> getCustomers(). This method's business should be just fetching the data from database, and returning the list of Customer's names as List<String>.
Then in your another class, simply call this method and set the whole List<String> as the model of your JComboBox.
See the example below:
public class AnotherClass extends JFrame{
private JComboBox<String> jComboBox;
public AnotherClass() {
init();
}
private void init(){
//... other components
DBClass db = new DBClass();
List<String> customers = db.getCustomers();
jComboBox = new JComboBox<>(customers.toArray(new String[]{}));
this.add(jComboBox);
//... other components
}
}
class DBClass{
public List<String> getCustomers (){
List<String> customers = new ArrayList<>();
try{
//dBconnection...
ResultSet rs = null;// your code for getting ResultSet
while(rs.next()){
String customer = rs.getString (1);
customers.add(customer);
}
}catch(SQLException e){
e.printStackTrace();
}
return customers;
}
}
Good Luck.

MySQL error store boolean value into tinyint

Class Code
this is some of code from Class Code that may help.
private ResultSet rs;
private Connection cn;
private Statement st;
public void insertData(String data)
{
try
{
st.executeUpdate(data);
{
JOptionPane.showMessageDialog(null, "Data berhasil Disimpan");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Gagal Insert Data");
}
}
InsertDaftar Class
public class InsertDaftar implements DaftarInterface {
public String nama;
public boolean kuasa;
Code cd = new Code();
public void setNama(String nama){
this.nama=nama;
}
public void setKuasa(Boolean kuasa){
this.kuasa=kuasa;
}
public void Akun(){
String data = "INSERT INTO akun (Nama,Kuasa)"+"values('"+this.nama+"','"+this.kuasa+"')";
cd.insertData(data);
}
I have created some code boolean for radio button.
boolean akun_kuasa;
if (admin.isSelected()){
akun_kuasa=true;
}
if (teller.isSelected()){
akun_kuasa=false;
}
//todo
InsertDaftar id = new InsertDaftar()
id.setNama(akun_nama.getText());
id.setKuasa(akun_kuasa);
there are warning message on
id.setKuasa(akun_kuasa);
Warning in Netbeans.
Initialize variable of akun_kuasa
I have tried to change type of "akun_kuasa" into int,
and changed akun_kuasa into 0 and 1, but there still error.
I have searched this problem. but there are to many about BOOLEAN or TinyInt.
NOTE: id is an object that have a method to store into database.
akun_kuasa can be undefined after the if's
Set it to false first? Only u would know
It is a good compiler warning to u
akun_kuasa is declared but potentially undefined
when u call the setter

Java SwingWorker load data from database to List

I have a problem with my MVC application that displays data in a JTable. Everything worked fine, but I decided to add a SwingWorker to retrieve data from the database.
My controller calls the model with data from the database. It looks like this.
Model.java
public class Model {
private List<Category> people = new Vector<Category>();
public List<Category> getPeople() {
return new ArrayList<Category>(people);
}
public void load() throws Exception {
people.clear();
DAOFactory factory = DAOFactory.getFactory(DAOFactory.MYSQL);
CategoryDAO personDAO = factory.getCategoryDAO();
people.addAll(personDAO.getCategory());
}
}
I add SwingWorker to getCategory class
MySQLCategodyDAO.java
public class MySQLCategoryDAO extends SwingWorker<Void, Vector<Object>> implements CategoryDAO{
private Job job;
private List<Category> cat;
public MySQLCategoryDAO(Job job){
this.job = job;
}
#Override
protected Void doInBackground() throws Exception {
// TODO Auto-generated method stub
if(job == Job.SELECT){
getCategory();
System.out.println("Table selected");
}
return null;
}
#Override()
public void done(){
}
public List<Category> getCategory() throws SQLException
{
cat = new ArrayList<Category>();
Connection conn = Database.getInstance().getConnection();
System.out.println(conn);
String sql = "select id, name from kategorie";
Statement selectStatement = conn.createStatement();
ResultSet results = selectStatement.executeQuery(sql);
while(results.next())
{
int id = results.getInt("id");
String name = results.getString("name");
Category category = new Category(id, name);
cat.add(category);
}
results.close();
selectStatement.close();
return cat;
}
}
View just retrieves the data from the model:
people = model.getPeople();
for (Category person : people) {
tablemodel
.addRow(new Object[] { person.getId(), person.getName() });
}
The problem comes when you call SwingWorker in class Model.java
public void load() throws Exception {
people.clear();
DAOFactory factory = DAOFactory.getFactory(DAOFactory.MYSQL);
CategoryDAO personDAO = factory.getCategoryDAO();
people.addAll(new MySQLCategoryDAO(Job.SELECT).execute()); - ERROR
}
Error:-
The method addAll(Collection<? extends Category>) in the type List<Category> is not applicable for the
arguments (void)
I know SwingWorker returns nothing, because there is an error. I should write the code in the method done(), but I have no idea how to solve it.
execute does not have a return value so it can't be used in the way you are trying to use it. The idea of SwingWorker is that the task should be executed asynchronously so you need to rework your design.
The SwingWorker bears a result (the List<Category>) and you either need to:
put the result somewhere from inside the SwingWorker (such as with the publish mechanism)
or call get from the outside to wait for the task to finish and return.
Here is the tutorial for review: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
Quick example:
class MySQLCategoryDAO extends SwingWorker<Void, Category> {
// ...
private List<Category> list; // do not modify inside doInBackground
MySQLCategoryDAO(Job job, List<Category> list) {
this.list = list;
// ...
}
#Override
protected Void doInBackground() {
// ...
while(results.next()) {
int id = results.getInt("id");
String name = results.getString("name");
publish(new Category(id, name)); // publish results to the EDT
}
// ...
return null;
}
#Override
protected void process(List<Category> chunks) {
list.addAll(chunks); // add results to the list on the EDT
// add to the JTable (?)
}
}
public void load() throws Exception {
people.clear();
DAOFactory factory = DAOFactory.getFactory(DAOFactory.MYSQL);
CategoryDAO personDAO = factory.getCategoryDAO();
// just execute
new MySQLCategoryDAO(Job.SELECT, people).execute();
}
If you want to populate the entire table at once then you can also publish a List after the loop instead of one Category at a time. process would receive a List<List<Category>> with a singular element.
Sorry my mistake.
From the view gets to model.getPeople (), but nothing is returned. I did a test:
But nothing is returned
public class Model {
private List<Category> people = new Vector<Category>();
public List<Category> getPeople() {
for (Category person : people) {
System.out.println(person.getName()); //no data
}
return new ArrayList<Category>(people);
}
public void load() throws Exception {
people.clear();
DAOFactory factory = DAOFactory.getFactory(DAOFactory.MYSQL);
new MySQLCategoryDAO(Job.SELECT,people).execute();
}
}

Java Combobox, Managing 2 fields from database

I want to get a result set with 2 fields from my DB.
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
And then I want to show the field called "name_prov" in the comboBox (As the item). But I also want to have my "id_prov" which is the ID (PRIMARY KEY) as the value for this item. This serves for the purpose of relating the name (of the providers in this case) with its ID just by using the combobox.
This is the code of the JComboBox event FocusGained that Im currently using.
try {
//CBProv is the Combobox
CBProv.removeAllItems();
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
while(rs.next())
{
CBProvedores.addItem(rs.getString("name_prov"));
//Here should be the Value related to the item I am creating
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e );
}
Is there anyway I can accomplish this?
First create a POJO, which will hold both your name and id.
public class ComboItem {
private String id;
private String name;
public ComboItem(String id, String name) {
this.id = id;
this.name = name;
}
// Add the getter and setter as you want.
// This will be used internally by JComboBox as the label to be displayed.
#Override
public String toString() {
return name;
}
}
Then use this POJO objects to be put into your JComboBox.
try {
//CBProv is the Combobox
CBProv.removeAllItems();
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
while(rs.next())
{
String id = rs.getString("id_prov"); // Get the Id
String name = rs.getString("name_prov"); // Get the Name
ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
CBProv.addItem(comboItem); // Put it into the ComboBox
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e );
}
And then finally to get the value selected, you can do this:-
CBProv.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ComboItem comboItem = (ComboItem) CBProv.getSelectedItem();
// comboItem.getId(), comboItem.getName() - Use as you wish.
}
});
Hi there i am Also still a newbie to java and javafx. This is what i did in javafx and it worked for me Hope you can work around it in java.
private void fillProviders()
{
List<String> providerList = new ArrayList<String>();
try
{
String Sql = "select * from prov ";
pat= conn.prepareStatement(Sql);
rs=pat.executeQuery();
while (rs.next())
{
providerList.add(rs.getString("id_prov")+" "+ rs.getString("name_prov"));
}
ObservableList<String> provider = FXCollections.observableArrayList(providerList);
bankName.setItems(provider);
}
catch( Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Hope it works for you. Note that my my combobox Name is bankName

Categories

Resources