how to populate data from textarea to jlist - java

I'm having a problem with the jlist..the data is showing in my jlist whenever i put a data on my textarea but instead of populating the data it will remove the previous one and will only show the current input.. here is my code by the way
private void postButtonActionPerformed(java.awt.event.ActionEvent evt) {
String theAccountID = showAccountID.getText();
String theFirstName = showFName.getText();
String theLastName = showSName.getText();
String name = theFirstName + " " + theLastName;
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
String dateAndTimeCreated = dateFormat.format(date);
String show = thePost.getText();
Post obj = new Post(show);
String post = obj.getContent();
DefaultListModel model = new DefaultListModel();
String postOutput = dateAndTimeCreated + " " + name + ": " + post;
try
{
if(obj.getContent().equals(""))
{
JOptionPane.showMessageDialog(null, "This status update appears to be blank. Please write something to update your status.");
}
else
{
model.addElement(postOutput);
showPostStatus.setModel(model);
String sql = "insert into Post(account_id,post,datePostCreated) values (?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1,theAccountID);
pst.setString(2,post);
pst.setString(3,dateAndTimeCreated);
pst.execute();
pst.close();
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
thePost.setText(null);
}

You are re-creating the ListModel each time postButtonActionPerformed is called, this (effectively) discards everything else that the JList was displaying in favor of the contents of the new model
You could consider create a DefaultListModel as an instance field, set it as the JLists model and simply update this model as required
You could also do something like...
DefaultListModel model = (DefaultListModel)showPostStatus.getModel();
// update the model...
You won't need to apply the model, as any changes you make will be reflected within the JList itself automatically...

Related

How can I use a updated list in other if-else block?

I am a beginner and working with IntelijIDEA configurations first time.
Conditions of a task is:
When starting the program with the -c parameter, the program should add a person with the given parameters to the end of the allPeople list, and display the id (index) on the screen.
When starting the program with the -r parameter, the program should display data about a person with the given id according to the format specified in the task.
The current code:
public class Solution{
public static List<Person> allPeople = new ArrayList<Person>();
static
{
allPeople.add(Person.createMale("Иванов Иван", new Date())); //сегодня родился id=0
allPeople.add(Person.createMale("Петров Петр", new Date())); //сегодня родился id=1
}
public static void main(String[] args) throws ParseException
{
if (Objects.equals(args[0], "-c"))
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
Date date = sdf.parse(args[3]);
Person artman = Person.createMale(args[1], date);
allPeople.add(artman);
//trying to create a new list for updated allPeople list
//List<Person> allPeopleUpd = new ArrayList<Person>(allPeople);
}
if (Objects.equals(args[0], "-r"))
{
List<Person> allPeopleUpd = new ArrayList<Person>(allPeople); //it's not an updated list
String name = allPeopleUpd.get(Integer.parseInt(args[1])).getName();
String sex = String.valueOf(allPeopleUpd.get(Integer.parseInt(args[1])).getSex());
String bd = String.valueOf(allPeopleUpd.get(Integer.parseInt(args[1])).getBirthDate());
System.out.println(name + " " + sex + " " + bd);
}
}
}
How to do a first condition I understood, but the problem is that the second if statement (with a "-r" parameter) don't see a changes that I made in the first if statement. What should I do to make a updated list visible for the second if statement?
P.S. createMale() and getters are from another Person class, never mind

Command manager procedure in MicroStrategy not converting to date

I am running below command manager procedure in Microstrategy but it does not convert the string into date, tried lot of options. Can someone please assist?
*********** PROCEDURE***************************************
String sQuery = "LIST ALL SUBSCRIPTIONS FOR SCHEDULE \"" + sScheduleName + "\" FOR PROJECT \"" + projectName + "\";";
ResultSet oSubs=executeCapture(sQuery);
oSubs.moveFirst();
while(!oSubs.isEof()){
String sSubsName = oSubs.getFieldValueString(DisplayPropertyEnum.GUID);
ResultSet RecList = executeCapture("LIST ALL PROPERTIES FOR SUBSCRIPTION GUID " +sSubsName+ " FOR PROJECT \"projectname\";");
RecList.moveFirst();
while(!RecList.isEof()){
ResultSet oResultSetSubProps = (ResultSet)RecList.getResultCell(SUBSCRIPTION_RESULT_SET).getValue();
oResultSetSubProps.moveFirst();
while(!oResultSetSubProps.isEof())
{
String d1 = oResultSetSubProps.getFieldValueString(DisplayPropertyEnum.EXPIRATIONDATE);
// the below few lines in red return nothing, its unable to convert to Date as it is unable to recognize the Expiration date in the String format.
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("M/dd/yyyy");
String dateInString = d1;
Date date = formatter.parse(dateInString);
printOut(formatter.format(date));
oResultSetSubProps.moveNext();
}
RecList.moveNext();
}
oSubs.moveNext();
}
This worked for me. The string was neither empty, nor null and no even blank but it would still not parse it so i had to use the length of the string.
java.text.DateFormat formatter = new java.text.SimpleDateFormat("M/d/yyyy",Locale.US);
String dateInString = d1;
if(d1.trim().length()>0)
{
Date date = formatter.parse(dateInString);
if(todaydate.compareTo(date)>0)
{
printOut(name+";"+formatter.format(date));
}
}
if(d1.contains("/"))
{
Date EDate=new Date(d1);
Date today= new Date();
if(d1.compareTo(today)<0)
{
printOut("Expired");
}
}
else
{
printOut("Active");
}
//blank or null values can be handled in Else condition instead.. Hope it helps..

how to show my clicked row from my JTable connection to my MS access data Base to JTextFields

I have program which i show MS Access Database row and column to my JTable and if click a cell from that JTable all data will be shown to it respective JTextField. Here are my codes.
public void reloadData() throws ClassNotFoundException, SQLException
{
columnNames.clear();
data.clear();
String DBPAD = "sourceFolder/employeeTable1.mdb";
String DB = "jdbc:ucanaccess://" + DBPAD;
con1x = DriverManager.getConnection(DB);
st1x = con1x.createStatement();
rs1x = st1x.executeQuery("Select * FROM employeeTable1");
ResultSetMetaData rsmd = rs1x.getMetaData();
int column = rsmd.getColumnCount();
columnNames.addElement("Employee Name");
columnNames.addElement("Employee Address");
columnNames.addElement("Employee Marital Status");
columnNames.addElement("Employee Date of Membership");
columnNames.addElement("Employee Blood Type");
columnNames.addElement("Employment Status");
columnNames.addElement("Employee Gender");
columnNames.addElement("Employee Date Of Birth");
columnNames.addElement("Employee Age");
columnNames.addElement("Beginning Capital");
columnNames.addElement("Gross Salary");
columnNames.addElement("Salary Deductions");
columnNames.addElement("Net Salary");
while(rs1x.next())
{
Vector<Object> row = new Vector<Object>(column);
for(int i=1; i<=column; i++)
{
row.addElement(rs1x.getObject(i));
}
data.addElement(row);
}
try
{
mainTableJTableCoop.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent event)
{
String employeeName = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 0).toString());
endrollNameFields.setText(employeeName);
String employeeAddress = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 1).toString());
endrollAddressFields.setText(employeeAddress);
String employeeMaritalSatatus = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 2).toString());
maritalstatusFields.setText(employeeMaritalSatatus);
String employeeDateOfMembership = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 3).toString());
dateOfMembershipFields.setText(employeeDateOfMembership);
String employeeBloodType = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 4).toString());
bloodTypeFields.setText(employeeBloodType);
String employeeEmploymentStatus = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 5).toString());
endrollEmployeestatusFields.setText(employeeEmploymentStatus);
String employeeGender = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 6).toString());
genderFields.setText(employeeGender);
String dateOfBirth = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 7).toString());
birthDateFields.setText(dateOfBirth);
String employeeAge = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 8).toString());
ageFields.setText(employeeAge);
String beginningCapital = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 9).toString());
beginningCapitalFields.setText(beginningCapital);
String grossSalary = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 10).toString());
grossSalaryFields.setText(grossSalary);
String deductions = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 11).toString());
salaryDeductionFields.setText(deductions);
String netSalary = (mainTableJTableCoop.getValueAt(mainTableJTableCoop.getSelectedRow(), 12).toString());
netSalaryFields.setText(netSalary);
}
});
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
My Codes looks OK but every time I click a row from my JTable which is connected to my MS access database the information that appears in my JTextFields are always the data from the first row, even if i click the second, third row. Any suggestion to achieved my desired output?
Without a runnable example is difficult to 100% sure, my first thought is, you shouldn't be adding another ListSelectionListener to the JTable when reloadData is called. This will add ANOTHER listener every time you call this method, accumulatively, which could have some interesting side effects and possibly degrade your program.
Also ListSelectionListener may be notified twice of change in selection, once when the selection is deselected (what ever was currently selected) and once when the new selection occurs.
You should check the state of the getValueIsAdjusting of the ListSelectionEvent to determine if the another event might be delivered or not
public void valueChanged(ListSelectionEvent event)
{
if (!event.getValueIsAdjusting()) {
int selectedRow = mainTableJTableCoop.getSelectedRow();
See How to Write a List Selection Listener for more details.
Consider providing a runnable example which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses
for now i would say try using a print statement to see the values that this "mainTableJTableCoop.getSelectedRow()" returns each time your event handler receives an event, this can get you started in figuring out where the problem is coming from.

Using a textbox for input for a JList

Okay I know this has got to be something very simple I am trying to do but I am pulling my hair out trying to figure it out. I have a GUI with three text boxes and one JList I am trying to add to the list. Here is my addButton code below:
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String emailText = custEmailTextBox.getText();
String firstText = firstNameTextBox.getText();
String lastText = lastNameTextBox.getText();
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement(firstText + " : " + lastText + " : " + emailText);
custList.setModel(model);
}
I can add text to my list but if I try to add a second line of text it just overwrites the first one. How can I just add to the list with out overwriting the other?
I can add text to my jlist box but if I try to add a second line of
text it just overwrites the first one.
Because, each time your are adding a text to JList you are creating new DefaultListModel and setting that model to the JList which removes the already added texts in JList. To overcome this problem create the object of DefaultListModel once outside the addButtonActionPerformed method.Also set the model for JList once. Your code should be something like this:
DefaultListModel<String> model = new DefaultListModel<>();
private void someMethod() //call this method in your constructor or method where you have initialized your GUI
{
custList.setModel(model);
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String emailText = custEmailTextBox.getText();
String firstText = firstNameTextBox.getText();
String lastText = lastNameTextBox.getText();
model.addElement(firstText + " : " + lastText + " : " + emailText);
}
By default a JList will use a DefaultListModel.
Cast the JList model via list.getModel(), and just remove your setModel method call which resets the list data.

Load database Field Values to A JCombobox

How to load values from an Oracle db to a JComboBox to make it easier for the user To Choose from I Have tried this:
Connection dbcon = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
dbcon = DriverManager.getConnection("
jdbc:oracle:thin:#localhost:1521:XE", "USERNAME", "PASSWORD");
Statement st = dbcon.createStatement();
String combo = "Select EMP_IDNUM from employees";
ResultSet res = st.executeQuery(combo);
while(res.next()){
String ids = res.getString("EMP_IDNUM");
String [] str = new String[]{ids};
cboId = new JComboBox(str);
}
} catch (Exception d) {
System.out.println(d);
}
This is Only getting me the first Value Into the JComboBox cboID. What Is the Best way to Load the entire Field Data (EMP_IDNUM) into the Jcombobox??
String [] str = new String[]{ids};
It means your String array is having only one ids value which you have loaded String ids = res.getString("EMP_IDNUM");
if(rs.getRow()>0){
String [] str = new String[res.getRow()];
int i=0;
while(res.next()){
str[i++] = res.getString("EMP_IDNUM");
}
}
JComboBox jcb = new JComboBox(str);
Instead of array you can use Vector also to create JComboBox.
you can use this code:
Vector v = new Vector();
while(res.next()){
String ids = res.getString("EMP_IDNUM");
v.add(ids)
}
JComboBox jcb = new JComboBox(v);
In this code you create a Vector with your Strings, and then invoke directly the JComboBox(Vector items) constructor of JComboBox
there are three important areas
a) close all JDBC Objects in the finally block, because these Object aren't, never GC'ed
try {
} catch (Exception d) {
System.out.println(d);
} finally {
try {
st.close()
res.close()
dbcon.close()
} catch (Exception d) {
//not important
}
}
b) don't to create any Objects inside try - catch - finally, prepare that before
meaning cboId = new JComboBox(str);
c) put all data from JDBC to the ComboBoxModel, prepare that before

Categories