How to retrieve data from mysql database from what is the input on my textfield - user-interface

For example I have entered my pin to 123 in my text field I want that program to Show the balance, card number and account number of that certain pin
i used setters and getters to get the pin from the previous frame (login)
Here is my code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.table.*;
public class Test extends JFrame
{
private static final Test sh1 = new Test();
public static Test getInstance()
{
return sh1;
}
Container c;
Connection con;
Statement st;
ResultSet rs;
ResultSetMetaData rm;
JTable tb;
JButton btnback = new JButton("Back");
JTextField pin = new JTextField("");
public void setUser(String user) {this.pin.setText(user);}
public String getUser() {return this.pin.getText();}
public Test(){
this.setTitle("Data");
this.setSize(500,500);
this.setLocation(800, 80);
this.setBackground(Color.black);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();
c.setLayout(new FlowLayout());
c.add(btnback);
c.add(pin);
stud();
}
public void stud()
{
Vector ColName = new Vector();
Vector Data = new Vector();
try{
String driver="com.mysql.jdbc.Driver";
String db="jdbc:mysql://localhost:3306/atm";
String user="root";
String pass="";
Class.forName(driver);
con=DriverManager.getConnection(db,user,pass);
st=con.createStatement();
String pincodee = pin.getText().trim();
String sqltb = "Select balance,cardnumber , accountnumber from accounts WHERE "
+ "pincode = '"+pincodee+"' ";
rs = st.executeQuery(sqltb);
rm = rs.getMetaData();
int col = rm.getColumnCount();
for(int i = 1; i <= col; i++)
{
ColName.addElement(rm.getColumnName(i));
}
while(rs.next())
{
Vector row = new Vector(col);
for(int i = 1; i <= col; i++)
{
row.addElement(rs.getObject(i));
String s = rs.getString(2);
pin.setText(s);
}
Data.addElement(row);
}
}
catch (Exception ex)
{
}
tb = new JTable( Data, ColName);
tb.repaint();
JScrollPane sc = new JScrollPane(tb);
sc.validate();
c.add(sc);
}
public static void main(String[] args)
{
Test s = new Test();
s.setVisible(true);
}
}

You need to create a button which says 'Go!' or something like that and add an action listener to it that calls your stud() method.
look here for example..
http://www.javaprogrammingforums.com/java-swing-tutorials/278-how-add-actionlistener-jbutton-swing.html
Your code is not going to work either way, you need to rewrite a great deal of it but the ActionListener class is your friend if you want actions on the user interface to call logic code.

Related

How do I create an arraylist in and add and view it with buttons?

I'm trying to make a GUI program that enters and removes cars from an arraylist and displays the cars using JButtons. I am unable to get the arraylist to print from clicking on one of the buttons. I'm also unsure if my arraylist is made correctly. Any help would be greatly appreciated.
import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Window extends JFrame {
public Window() {
super ("Rent-a-Car");
setSize(400, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
JPanel p = new JPanel();
JButton b1 = new JButton("Add Car");
JButton b2 = new JButton("Rent Car");
JButton b3 = new JButton("Library");
p.add(b1);
p.add(b2);
p.add(b3);
add(p);
final ArrayList<String> cars = new ArrayList<String>();
cars.add("Audi");
cars.add("VolksWagon");
cars.add("Mercedes");
cars.add("BMW");
cars.add("Ford");
cars.add("Subaru");
cars.add("Lexus");
cars.add("Acura");
cars.add("Nissan");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Scanner sc = new Scanner(System.in);
JOptionPane.showInputDialog("Enter car model");
String model = sc.next();
JOptionPane.showMessageDialog(null, "Car added");
cars.add(model);
}
});
/*b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0 < cars.size(); i++) {
System.out.println();
}
}
});*/
}
}
In your ActionListener for b1 you're trying to scan it from the wrong place. If you run this, you've probably noticed that the JOptionPane doesn't do anything when you submit a car with the add button. However, if you enter a string into the terminal, an dialog will pop up saying "Car added". This is because Scanner sc is scanning System.in! This is not meant for GUIs.
Fortunately, it's really simple to get input from a JOptionPane.
EDIT: Added a few things like a JTextArea in a JScrollPane that is easy to append to and changed it to a simple GridLayout.
I also moved the ActionListeners into an inner class so that you don't clutter up your code with anonymous functions everywhere. It's also a bit easier to add stuff with the (e.getSource()) conditionals, too.
Set model equal to the result of showInputDialog as such:
import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
import javax.swing.*;
public class Window extends JFrame {
private JPanel p;
private JButton b1, b2, b3;
private JTextArea textArea;
private JScrollPane scrollPane;
private ArrayList<String> cars;
public Window() {
super ("Rent-a-Car");
setLayout(new GridLayout(2, 1));
setSize(400, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
p = new JPanel();
b1 = new JButton("Add Car");
b2 = new JButton("Rent Car");
b3 = new JButton("Library");
b1.addActionListener(new ButtonListener());
b2.addActionListener(new ButtonListener());
b3.addActionListener(new ButtonListener());
textArea = new JTextArea("");
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
p.add(b1);
p.add(b2);
p.add(b3);
add(p);
//add(textArea);
add(scrollPane);
cars = new ArrayList<String>();
cars.add("Audi");
cars.add("VolksWagon");
cars.add("Mercedes");
cars.add("BMW");
cars.add("Ford");
cars.add("Subaru");
cars.add("Lexus");
cars.add("Acura");
cars.add("Nissan");
}
public void displayText(String s) {
textArea.append(s + "\n");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
String model = JOptionPane.showInputDialog("Enter car model");
cars.add(model);
displayText("Added car: " + model);
}
else if (e.getSource() == b2) {
//add something later
}
else if (e.getSource() == b3) {
for (String car : cars) {
displayText(car);
}
}
}
}
}

Trying to use a JScrollPane to display an array of strings but i keep getting an error

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class SavingAccountFrame extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_LENGTH = 500;
private static final double INITIAL_BALANCE = 0.0;
private static final double ANNUAL_RATE = 0.0;
private static final int YEARS = 0;
String[] result;
private JLabel initialLabel;
private JLabel rate;
private JLabel years;
private JTextField initialBal;
private JTextField annualRate;
private JTextField numOfYears;
private JButton calculate;
private JPanel panel;
private JList box;
private JScrollPane scroll;
SavingAccountFrame(){
createTextField();
createButton();
createScrollPane();
createPanel();
setSize(FRAME_WIDTH, FRAME_LENGTH);
}
private void createTextField(){
final int FIELD_WIDTH = 10;
initialLabel = new JLabel("Initial Balance");
initialBal = new JTextField(FIELD_WIDTH);
rate = new JLabel("Annual Rate");
annualRate = new JTextField(FIELD_WIDTH);
years = new JLabel("Number of Years");
numOfYears = new JTextField(FIELD_WIDTH);
}
private void createButton(){
calculate = new JButton("Calculate");
class CalcListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double iB = Double.parseDouble(initialBal.getText());
double r = Double.parseDouble(rate.getText());
int y = Integer.parseInt(years.getText());
r = r / 100;
for (int i = 0; i < y; i++) {
double newbalance = iB * r;
iB += newbalance;
String test = String.valueOf(iB);
result[i] = test;
}
box = new JList(result);
scroll = new JScrollPane(box);
getContentPane().add(scroll);
}
}
ActionListener d = new CalcListener();
calculate.addActionListener(d);
}
private void createScrollPane(){
scroll = new JScrollPane();
}
private void createPanel()
{
panel = new JPanel();
panel = new JPanel();
panel.add(initialLabel);
panel.add(initialBal);
panel.add(rate);
panel.add(annualRate);
panel.add(years);
panel.add(numOfYears);
panel.add(calculate);
panel.add(scroll);
add(panel);
}
}
import javax.swing.JFrame;
public class SavingAccount {
public static void main(String[] args) {
JFrame frame = new SavingAccountFrame();
frame.setTitle("Savings Account");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
i am having a bit of homework trouble and my code keeps spitting out this error when i press the calculate button.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Annual Rate"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1242)
at java.lang.Double.parseDouble(Double.java:527)
at SavingAccountFrame$1CalcListener.actionPerformed(SavingAccountFrame.java:54)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6268)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6033)
at java.awt.Container.processEvent(Container.java:2045)
at java.awt.Component.dispatchEventImpl(Component.java:4629)
at java.awt.Container.dispatchEventImpl(Container.java:2103)
at java.awt.Component.dispatchEvent(Component.java:4455)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4633)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4297)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4227)
at java.awt.Container.dispatchEventImpl(Container.java:2089)
at java.awt.Window.dispatchEventImpl(Window.java:2517)
at java.awt.Component.dispatchEvent(Component.java:4455)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:649)
at java.awt.EventQueue.access$000(EventQueue.java:96)
at java.awt.EventQueue$1.run(EventQueue.java:608)
at java.awt.EventQueue$1.run(EventQueue.java:606)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:116)
at java.awt.EventQueue$2.run(EventQueue.java:622)
at java.awt.EventQueue$2.run(EventQueue.java:620)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:619)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
Can someone please clarify for me what this exception is and how to fix it. I can't pinpoint where the seems to point null or where the format is incorrect. Please and thank you
The error is here
double r = Double.parseDouble(rate.getText());
in createButton.
instead you should use annualRate.parseDouble.
because rate is a JLabel but not the textfield.
rate = new JLabel("Annual Rate");
When you try to parse the "Annual Rate" into a number, it will give you java.lang.NumberFormatException

Accessing class variables from private actionPerformed method

In the code below, I don't know why the values of variables uNomba and list are NULL when accessed from jButton1ActionPerformed method. I would appreciate your help, on how I can successfully execute "new NewPlayer(uNomba, count, check, list).load();" such that all the values are passed to NewPlayer class. Thank you.
The first class - i.e The NewPlayer class
package mysound;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class NewPlayer extends JPanel implements KeyListener, Runnable{
boolean isUpPressed, isDownPressed, isSpacePressed, isDone;
static JFrame f;
int spacebars=0;
boolean within;
public List spacebarLogMs = new ArrayList();
public List numSbar = new ArrayList();
Calendar cal = Calendar.getInstance();
LogResult logNow = new LogResult();
String directory;
String tabname; //table name used in the database connection
String bdir;
private int uNomba; //user number obtained from NewSound class
private String target;
private int incr;
private int userno;
private boolean moveon=true;
private List randlist;
private List numlist;
public void load() {
f = new JFrame();
f.setSize(600,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(this);
f.setVisible(true);
setFocusable(true);
addKeyListener(this);
new Thread(this).start();
}
public NewPlayer() {
}
public NewPlayer(int UNOMBA, List NUMLIST){
this.uNomba = UNOMBA; //user number obtained from NewSound class
this.numlist=NUMLIST;
}
public NewPlayer(int USERNO, int INCR, boolean MOVEON, List NUMLIST){
this.userno=USERNO;
this.incr=INCR;
this.moveon=MOVEON;
this.numlist=NUMLIST;
}
public void keyTyped(KeyEvent ke) {
}
public void keyPressed(KeyEvent ke) {
switch(ke.getKeyCode()) {
case KeyEvent.VK_UP: isUpPressed = true; break;
case KeyEvent.VK_DOWN: isDownPressed = true; break;
case KeyEvent.VK_SPACE: isSpacePressed = true;
numSbar.add(System.currentTimeMillis());
System.out.println("That was a spacebar. "+spacebars++);
System.out.println("Current time: "+numSbar);
break;
}
}
public void keyReleased(KeyEvent ke) {
switch(ke.getKeyCode()) {
case KeyEvent.VK_UP: isUpPressed = false; break;
case KeyEvent.VK_DOWN: isDownPressed = false; break;
case KeyEvent.VK_SPACE: isSpacePressed = false; break;
}
}
public void closePrj(){
f.dispose();
}
public void run() { //introduce a target sound
String targetChoice;
int tIndex;
int i;
bdir="C:\\Users\\Abiodun\\Desktop\\testdata\\main\\zero\\atext\\"; //dir for text files
MainPlayer items = new MainPlayer (uNomba);
i=incr;
while(moveon){
System.out.println("Counter i: "+i+" Numlist: "+numlist);
if (i<numlist.size()){
int num = (int) numlist.get(i);
System.out.println("Num :"+num);
items.selectTarget(num);
items.selectChallenge(num);
items.playChallenge();
new WriteTime(bdir).tagTime(numSbar);
items.dataLogger();
moveon=false;
new Continue (uNomba, i, moveon, numlist).load();
}
}
}
}
The second class i.e the Continue class
public class Continue extends javax.swing.JDialog {
private int count;
private int usernumb;
private boolean check;
private int uNomba;
private String cdirectory;
private String cbdir;
private String ctabname;
private String ctarget;
private List list;
/**
* Creates new form Continue
*/
public Continue(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
public Continue(int CUNOMBA, int COUNT, boolean CHECK, List NLIST){
this.uNomba = CUNOMBA; //user number obtained from NewSound class
this.count=COUNT;
this.check=CHECK;
this.list=NLIST;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
new NewPlayer().setVisible(false);//closePrj();
count++;
check=true;
new NewPlayer(uNomba, count, check, list).load();
System.out.println("Continue: UserNumber: "+uNumb+", Count: "+count+", Check: "+check+", nList"+lst);
this.setVisible(false);
}
Thanks sgroh. Here is what I just added: I created the following in
In NewPlayer class:
Continue ct = new Continue (new NewPlayer(uNomba, i, moveon, numlist));
In Continue Class,
private NewPlayer np;
public Continue (NewPlayer npy){
this.npy=np;
}
Just a recap, the main problem I am having is that I cannot access the values I passed from NewPlayer class from Continue class. I tested the values in side the following constructor in Continue class but not anywhere else in Continue class.
public Continue(int CUNOMBA, int COUNT, boolean CHECK, List NLIST){
this.uNomba = CUNOMBA; //user number obtained from NewSound class
this.count=COUNT;
this.check=CHECK;
this.nlist=NLIST;
System.out.println("Continue-constructor - uNomba: "+uNomba+", nList: "+list); //works fine! but not outside this constructor.
}
This code even compile, You haven't a constructor default (without fields).
this:
public Continue(java.awt.Frame parent, boolean modal) {
and This:
public Continue(int CUNOMBA, int COUNT, boolean CHECK, List NLIST){
this woun't compile:
Continue ctn = new Continue();
You have to create the Continue object using the right constructor or create the Default constructor.
You want also to print the variable uNumb in the System.out.println that doesn't exists.

Accessing SWbemObject Object Properties using J-Interop Library

I am very new to J-Interop Library and WMI. I was just playing around with the following sample code from j-interop samples (MSWMI, which deals with WMI Communication).
package org.jinterop.dcom.test;
import java.net.UnknownHostException;
import java.util.logging.Level;
import org.jinterop.dcom.common.IJIUnreferenced;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JICallBuilder;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JIFlags;
import org.jinterop.dcom.core.JIProgId;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.JIObjectFactory;
import org.jinterop.dcom.impls.automation.IJIDispatch;
import org.jinterop.dcom.impls.automation.IJIEnumVariant;
public class MSWMI {
private JIComServer comStub = null;
private IJIComObject comObject = null;
private IJIDispatch dispatch = null;
private String address = null;
private JISession session = null;
public MSWMI(String address, String[] args) throws JIException, UnknownHostException
{
this.address = address;
session = JISession.createSession(args[1],args[2],args[3]);
session.useSessionSecurity(true);
session.setGlobalSocketTimeout(5000);
comStub = new JIComServer(JIProgId.valueOf("WbemScripting.SWbemLocator"),address,session);
IJIComObject unknown = comStub.createInstance();
comObject = (IJIComObject)unknown.queryInterface("76A6415B-CB41-11d1-8B02-00600806D9B6");//ISWbemLocator
//This will obtain the dispatch interface
dispatch = (IJIDispatch)JIObjectFactory.narrowObject(comObject.queryInterface(IJIDispatch.IID));
}
public void performOp() throws JIException, InterruptedException
{
System.gc();
JIVariant results[] = dispatch.callMethodA("ConnectServer",new Object[]{new JIString(address),JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM()
,JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM(),new Integer(0),JIVariant.OPTIONAL_PARAM()});
//using the dispatch results above you can use the "ConnectServer" api to retrieve a pointer to IJIDispatch
//of ISWbemServices
//OR
//Make a direct call like below , in this case you would get back an interface pointer to ISWbemServices , NOT to it's IDispatch
JICallBuilder callObject = new JICallBuilder();
callObject.addInParamAsString(address,JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsInt(0,JIFlags.FLAG_NULL);
callObject.addInParamAsPointer(null,JIFlags.FLAG_NULL);
callObject.setOpnum(0);
callObject.addOutParamAsType(IJIComObject.class,JIFlags.FLAG_NULL);
IJIComObject wbemServices = JIObjectFactory.narrowObject((IJIComObject)((Object[])comObject.call(callObject))[0]);
wbemServices.setInstanceLevelSocketTimeout(1000);
wbemServices.registerUnreferencedHandler(new IJIUnreferenced(){
public void unReferenced()
{
System.out.println("wbemServices unreferenced... ");
}
});
//Lets have a look at both.
IJIDispatch wbemServices_dispatch = (IJIDispatch)JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());
results = wbemServices_dispatch.callMethodA("InstancesOf", new Object[]{new JIString("Win32_Process"), new Integer(0), JIVariant.OPTIONAL_PARAM()});
IJIDispatch wbemObjectSet_dispatch = (IJIDispatch)JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());
JIVariant variant = wbemObjectSet_dispatch.get("_NewEnum");
IJIComObject object2 = variant.getObjectAsComObject();
System.out.println(object2.isDispatchSupported());
System.out.println(object2.isDispatchSupported());
object2.registerUnreferencedHandler(new IJIUnreferenced(){
public void unReferenced()
{
System.out.println("object2 unreferenced...");
}
});
IJIEnumVariant enumVARIANT = (IJIEnumVariant)JIObjectFactory.narrowObject(object2.queryInterface(IJIEnumVariant.IID));
//This will return back a dispatch of ISWbemObjectSet
//OR
//It returns back the pointer to ISWbemObjectSet
callObject = new JICallBuilder();
callObject.addInParamAsString("Win32_Process",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsInt(0,JIFlags.FLAG_NULL);
callObject.addInParamAsPointer(null,JIFlags.FLAG_NULL);
callObject.setOpnum(4);
callObject.addOutParamAsType(IJIComObject.class,JIFlags.FLAG_NULL);
IJIComObject wbemObjectSet = JIObjectFactory.narrowObject((IJIComObject)((Object[])wbemServices.call(callObject))[0]);
//okay seen enough of the other usage, lets just stick to disptach, it's lot simpler
JIVariant Count = wbemObjectSet_dispatch.get("Count");
int count = Count.getObjectAsInt();
for (int i = 0; i < count; i++)
{
Object[] values = enumVARIANT.next(1);
JIArray array = (JIArray)values[0];
Object[] arrayObj = (Object[])array.getArrayInstance();
for (int j = 0; j < arrayObj.length; j++)
{
IJIDispatch wbemObject_dispatch = (IJIDispatch)JIObjectFactory.narrowObject(((JIVariant)arrayObj[j]).getObjectAsComObject());
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
System.out.println(variant2.getObjectAsString().getString());
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
}
private void killme() throws JIException
{
JISession.destroySession(session);
}
public static void main(String[] args) {
try {
if (args.length < 4)
{
System.out.println("Please provide address domain username password");
return;
}
JISystem.getLogger().setLevel(Level.INFO);
JISystem.setInBuiltLogHandler(false);
JISystem.setAutoRegisteration(true);
MSWMI test = new MSWMI(args[0],args);
for (int i = 0 ; i < 100; i++)
{
System.out.println("Index i: " + i);
test.performOp();
}
test.killme();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I understand that the following line of code calls the method "GetObjectText_" of the SWbemObject Object and we can see all the properties of the class instance.
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
What I wish to find out is, what should I do if I just need to retrieve a single property value, for example, if all I wanted was to retrieve the "InstallDate" property of the "Win32_Process" Class, what method would I call or how to access a particular property if I knew the property name I wish to access.
Any help on this topic would be great. Thanks a lot!!
You could access a property with the following code:
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.get("Caption"));
This replaces the line:
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
The “InstallDate” properties were all empty so I use the “Caption”.

Black Berry Table View

here is my app. how to add table view or grids in the following.
should i draw every thing plz help
this is my code
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.util.*;
import java.util.*;
/*An application in which user enters the data. this data is displayed when user press the save button*/
public class Display extends UiApplication {
/*declaring Strings to store the data of the user*/
String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
/*declaring text fields for user input*/
private AutoTextEditField firstName;
private AutoTextEditField lastName;
private EmailAddressEditField email;
/*declaring choice field for user input*/
private ObjectChoiceField gender;
/*declaring check box field for user input*/
private CheckboxField status;
//Declaring button fields
private ButtonField save;
private ButtonField close;
private ButtonField List;
/*declaring vector*/
private static Vector _data;
/*declaring persistent object*/
private static PersistentObject store;
/*creating an entry point*/
public static void main(String[] args)
{
Display obj = new Display();
obj.enterEventDispatcher();
}
/*creating default constructor*/
public Display()
{
/*Creating an object of the main screen class to use its functionalities*/
MainScreen mainScreen = new MainScreen();
//setting title of the main screen
mainScreen.setTitle(new LabelField("Enter Your Data"));
//creating text fields for user input
firstName = new AutoTextEditField("First Name: ", "");
lastName= new AutoTextEditField("Last Name: ", "");
email= new EmailAddressEditField("Email:: ", "");
//creating choice field for user input
String [] items = {"Male","Female"};
gender= new ObjectChoiceField("Gender",items);
//creating Check box field
status = new CheckboxField("Active",true);
//creating Button fields and adding functionality using listeners
save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
save.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
save();
}
});
close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
close.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
onClose();
}
});
List = new ButtonField("List",ButtonField.CONSUME_CLICK);
List.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context){
pushScreen(new ListScreen());
}
});
//adding the input fields to the main screen
mainScreen.add(firstName);
mainScreen.add(lastName);
mainScreen.add(email);
mainScreen.add(gender);
mainScreen.add(status);
//adding buttons to the main screen
HorizontalFieldManager horizontal = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
horizontal.add(close);
horizontal.add(save);
horizontal.add(List);
mainScreen.add(horizontal);
//adding menu items
mainScreen.addMenuItem(saveItem);
mainScreen.addMenuItem(getItem);
mainScreen.addMenuItem(Deleteall);
//pushing the main screen
pushScreen(mainScreen);
}
private MenuItem Deleteall = new MenuItem("Delete all",110,10)
{
public void run()
{
int response = Dialog.ask(Dialog.D_YES_NO,"Are u sure u want to delete entire Database");
if(Dialog.YES == response){
PersistentStore.destroyPersistentObject(0xdec6a67096f833cL);
onClose();
}
else
Dialog.inform("Thank God");
}
};
//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10)
{
public void run()
{
//Calling save method
save();
}
};
//adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11)
{
//running thread for this menu item
public void run()
{
//synchronizing thread
synchronized (store)
{
//getting contents of the persistent object
_data = (Vector) store.getContents();
try{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
getFirstName = (info.getElement(StoreInfo.NAME));
getLastName = (info.getElement(StoreInfo.LastNAME));
getEmail = (info.getElement(StoreInfo.EMail));
getGender = (info.getElement(StoreInfo.GenDer));
getStatus = (info.getElement(StoreInfo.setStatus));
//calling the show method
show();
}
}
}
catch(Exception e){}
}
}
};
public void save()
{
//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
info.setElement(StoreInfo.setStatus, "Active");
else
info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store)
{
store.setContents(_data);
store.commit();
}
//resetting the input fields
Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
gender.setSelectedIndex("Male");
status.setChecked(true);
}
//coding for persistent store
static {
store =
PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new Vector());
store.commit();
}
}
_data = new Vector();
_data = (Vector) store.getContents();
}
//new class store info implementing persistable
private static final class StoreInfo implements Persistable
{
//declaring variables
private Vector _elements;
public static final int NAME = 0;
public static final int LastNAME = 1;
public static final int EMail= 2;
public static final int GenDer = 3;
public static final int setStatus = 4;
public StoreInfo()
{
_elements = new Vector(5);
for (int i = 0; i < _elements.capacity(); ++i)
{
_elements.addElement(new String(""));
}
}
public String getElement(int id)
{
return (String) _elements.elementAt(id);
}
public void setElement(int id, String value)
{
_elements.setElementAt(value, id);
}
}
//details for show method
public void show()
{
Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus);
}
public void list()
{
Dialog.alert("haha");
}
//creating save method
//overriding onClose method
public boolean onClose()
{
System.exit(0);
return true;
}
class ListScreen extends MainScreen
{
String firstUserName="Ali";
String lastUserName="Asif";
String userEmail="assad";
String userGender="asdasd";
String userStatus="active";
private AutoTextEditField userFirstName;
private AutoTextEditField userLastName;
private EmailAddressEditField userMail;
private ObjectChoiceField usersGender;
private CheckboxField usersStatus;
private ButtonField btnBack;
public ListScreen()
{
SeparatorField sps = new SeparatorField();
HorizontalFieldManager hr = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER|HorizontalFieldManager.HORIZONTAL_SCROLLBAR);
VerticalFieldManager vr = new VerticalFieldManager();
setTitle(new LabelField("List of All Data"));
list();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
hr.add(btnBack);
add(hr);
add(sps);
}
public void list()
{
_data = (Vector) store.getContents();
try{
int sn=0;
for (int i = _data.size()-1; i >-1; i--,sn++)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
//calling the listAll method
listAll();
}
}
}
catch(Exception e){}
}
public void listAll()
{
SeparatorField sp = new SeparatorField();
SeparatorField sps = new SeparatorField();
HorizontalFieldManager hrs = new HorizontalFieldManager(HorizontalFieldManager.HORIZONTAL_SCROLL);
hrs.add(new RichTextField(""+firstUserName+" "+lastUserName+" | "+userEmail+" | "+userGender+" | "+userStatus));
//add(new RichTextField("Email: "+userEmail));
//add(new RichTextField("Gender: "+userGender));
//add(new RichTextField("Status: "+userStatus));
//SeparatorField sp = new SeparatorField();
add(hrs);
add(sp);
add(sps);
}
public boolean onClose()
{
System.exit(0);
return true;
}
}
}
There is a nice GridFieldManager by Anthony Rizk.
Code:
public void list()
{
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
add(mGrid);
_data = (Vector) store.getContents();
try {
int sn = 0;
for (int i = _data.size() - 1; i > -1; i--, sn++) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
// if not empty
// create a new object of Store Info class
// storing information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
}
}
} catch (Exception e) {
}
}
See also
BlackBerry Grid Layout Manager updated

Resources