Refresh Jtable - refresh

I have a JTable created from Vector.
How can the JTable be refreshed to display new data that is added to the Vector?

Your JTable should update automatically when a change to the TableModel happens. I'm taking a leap here but I'm guessing that you're not using your own TableModel and just called the JTable constructor with your Vector. In this case you can get a hook on the TableModel and cast it to a DefaultTableModel and then call one its notification methods to let the JTable know of a change, something like:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.fireTableChanged(new TableModelEvent(........));
What I would really recommend is using your own TableModel unless this is something very trivial, but the fact you're updating the data indicates it's not.
Check out the sun tutorial on working with tables, inparticular the section on listening for data changes.
It might seem like more work up front, but it will save you alot of headaches in the long run and is The Right Way to do it

I call the initTable method followed by loadTable(). I'm sure there's plenty of other ways but this works like acharm.
private void initBerkheimerTable() {
tblBerkheimer = new JTable();
tblBerkheimer.getSelectionModel().addListSelectionListener(new SelectionListener());
tblBerkheimer.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tblBerkheimer.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Id", "Name", "Berkheimer PSD", "Rate", "Current PSD", "Current Rate"
}
) {
Class[] columnTypes = new Class[] {
String.class, String.class, String.class, String.class, String.class, String.class
};
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
boolean[] columnEditables=new boolean[]{false,false,false,false,false,false,false,false,false,false};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
scrollPane.setViewportView(tblBerkheimer);
add(scrollPane);
}
private void loadTable(){
PreparedStatement ps=null;
ResultSet rs=null;
try {
PayrollPsdAuditing.payroll=Database.connectToSQLServerDataBase(PayrollPsdAuditing.payrollIni);
ps=PayrollPsdAuditing.payroll.prepareStatement(
"SELECT a.EMPLOYID, " +
" a.NAME, " +
" a.PSD_CODE, " +
" a.RATE, " +
" b.STRINGS_I_2 as CURRENT_PSD, " +
" c.lcltaxrt as CURRENT_RATE " +
"FROM PYRL_PSD_VALIDATION a, " +
" EX010130 b, " +
" UPR41400 c " +
"WHERE a.employid=b.empid_i " +
" AND c.localtax=b.strings_i_2");
rs=ps.executeQuery();
while(rs.next()) {
Swing.fillJTable(tblBerkheimer,
new String[]{rs.getString("EMPLOYID").trim()
,rs.getString("NAME").trim()
,rs.getString("PSD_CODE").trim()
,String.valueOf(rs.getDouble("RATE"))
,rs.getString("CURRENT_PSD").trim()
,String.valueOf(rs.getDouble("CURRENT_RATE")/100000)});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
Database.close(PayrollPsdAuditing.payroll);
}
}

Related

Why do profile pic URLs returned from graph.facebook result in a 404

The backend of my application makes a request to:
https://graph.facebook.com/v2.8/me?access_token=<firebase-access-token>&fields=id,name,first_name,birthday,email,picture.type(large){url}&format=json&method=get&pretty=0&suppress_http_code=1
I get a successful (200) response with the JSON data I expect and picture field as such:
"picture": {
"data": {
"url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=<asid>&height=200&width=200&ext=<ext>&hash=<hash>"
}
}
(where in place of <asid> and <ext>, there are numbers and <hash> is some alphanumeric string).
However, when I make a GET request to the platform-lookaside URL above, I get a 404 error.
It's been happening every time since my very first graph.facebook request for the same user. The very first one returned a platform-lookaside URL which pointed to a proper image (not sure if this is simply coincidence).
Is there something I'm doing wrong or is this likely a bug with the Facebook API?
FB currently seems to have issues with some CDNs and therefore your issue might be only temporary. You should also see missing/broken images on some places on fb dot com. Worst time to debug your issue :)
Try this code it worked for me
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
try {
String name = object.getString("name");
String email = object.getString("email");
String last_name = object.getString("last_name");
String first_name = object.getString("first_name");
String middle_name = object.getString("middle_name");
String link = object.getString("link");
String picture = object.getJSONObject("picture").getJSONObject("data").getString("url");
Log.e("Email = ", " " + email);
Log.e("facebookLink = ", " " + link);
Log.e("name = ", " " + name);
Log.e("last_name = ", " " + last_name);
Log.e("first_name = ", " " + first_name);
Log.e("middle_name = ", " " + middle_name);
Log.e("pictureLink = ", " " + picture);
} catch (JSONException e) {
e.printStackTrace();
Log.e("Sttaaaaaaaaaaaaaaaaa", e.getMessage());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,link,last_name,first_name,middle_name,picture");
request.setParameters(parameters);
request.executeAsync();

How to save several pieces of information from a JavaFX form to a File

I can not seem to figure out how to store the data in the TextFields in a text file using JavaFX and accepting a certain number of entries. For example: One would fill out the form 3times and all of those 3 pieces of information would be in the txt file. How would I implement an ArrayList into the method in order to display?
I have already tried to implement a String ArrayList but it does not display the data in the TextFields when I press "Save Information", all that displays is [, , , ]
public void saveInfo(ActionEvent e) {
ArrayList<String> list = new ArrayList<>();
File fileIt = new File("InfoGathered.txt");
try {
PrintWriter output = new PrintWriter(fileIt);
for (int i = 0; i < ; i++) {
String s1 = new String();
output.println(tfFirstName.getText() + tfLastName.getText() + tfdBirth.getText() + tfEmpID.getText());
list.add(s1);
}
output.write(list.toString());
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
I am expecting the TextFields to appear within the File such as [Sam Smith 12/03/94 123-AB, Lena Smith 12/12/91 127-AB, Sam Smith 02/18/95 726-HF ]
There are so many things fundamentally wrong in your code, I do not even know where to start. But if it is the solution you want for your given problem, below code will write the text of TextFields to the file in your desired format.
public void saveInfo(ActionEvent e) {
File fileIt = new File("InfoGathered.txt");
try (PrintWriter output = new PrintWriter(fileIt)){
String outString = tfFirstName.getText() + " "
+ tfLastName.getText() + " "
+ tfdBirth.getText() + " "
+ tfEmpID.getText();
output.write(outString);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}

Understanding Window query type in Siddhi

I am trying to implement a basic window on an input stream in siddhi.
This is the window query
executionPlan = "" +
"define stream inputStream (height int); " +
"" +
"#info(name = 'query1') " +
"from inputStream #window.length(5) " +
"select avg(height) as avgHt " +
"insert into outputStream ;";
And this is how I am giving data to the input Stream.
Object[] obj1 = {10};
Object[] obj2 = {5};
for (int i=0;i<10;i++) {
try {
inputHandler.send(obj1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i=0;i<20;i++) {
try {
inputHandler.send(obj2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Am I wrong in supposing that the the query should give a callback after each input to the inputHandler. So for this example the initial output should be 10 and then It should gradually decrease and become 5. At a point where I have sent all the 10's and 2 5's then I should get a callback with average as (10+10+10+5+5)/5= 8. But this is not happening currently. For this implementation I get two callback with average 10 and 5 respectively. Why isn't there a gradual decrease from 10 to 5?
This is how I add the callback
executionPlanRuntime.addCallback("query1", new QueryCallback() {
#Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
// printing inEvents
EventPrinter.print(inEvents);
});
What am I missing here?
Since you are sending events in a burst it's batching events within. But if you add Thread.Sleep(100) in between the events you send then it will output as you expected.

QMYSQL query failing

I'm currently working on my project within C++ using Qt. I have MySQL as database storage and the idea is to make a small messenger like MSN and Skype.
However, my MySQL queries are failing. It simply gets no results or gives me an error. There's loads of code coming up, I'm sorry for that.
This is my mysql.cpp which creates and opens the database connection:
#include "mysql.h"
mysql::mysql()
{
this->db = QSqlDatabase::addDatabase("QMYSQL", "QMYSQL");
this->db.setHostName("localhost");
this->db.setUserName("root");
this->db.setPassword("Eequi4");
this->db.setDatabaseName("test");
this->db.open();
}
mysql::~mysql()
{
}
mysql_result mysql::create_result(QString query)
{
return mysql_result(this->db.exec(query));
}
QSqlError mysql::error()
{
return this->db.lastError();
}
The connection is opened. That works correctly.
This is my mysql_result.cpp, the file I use to add parameters, insert, get results etc:
#include "mysql_result.h"
mysql_result::mysql_result(QSqlQuery query)
{
this->query = query;
}
void mysql_result::add_parameter(QVariant value)
{
this->query.addBindValue(value);
}
void mysql_result::add_parameter(QString key, QVariant value)
{
this->query.bindValue(key, value);
}
int mysql_result::get_last_id()
{
return this->query.lastInsertId().toInt();
}
void mysql_result::execute()
{
this->query.execBatch();
}
QSqlQuery mysql_result::get_query()
{
return this->query;
}
mysql_result::~mysql_result()
{
}
Okay, this should work. If I have the following code, it correctly returns all member first_name's from the database:
mysql_result res = _mysql->create_result("SELECT * FROM members");
QSqlQuery qry = res.get_query();
while (qry.next())
{
qDebug() << qry.value("first_name");
}
In member_controller.cpp (the class I use to retrieve members by name/id), I got this:
member* member_controller::get_member(int id)
{
mysql_result result = engine::get_mysql().create_result("SELECT * FROM members WHERE member_id = :ID");
result.add_parameter(":ID", id);
QSqlQuery query = result.get_query();
if (query.exec() && query.next())
{
return new member(id, query.value("first_name").toString(), query.value("second_name").toString(), query.value("screen_name").toString(), query.value("email").toString(), query.value("status").toString());
}
else
{
qDebug() << engine::get_mysql().error() << "\n";
qDebug() << query.lastError() << "\n";
}
return new member(0, "", "", "", "", "");
}
What it does it will go to the else, and I get the error invalid syntax near :ID. If I replace :ID with #ID (just like in C#), it will go to the else without error code.. I don't know what the problem is.
Two things. The code needs to be optimized a bit and made easier, I'm gonna work on that. Also, is it possible/allowed to put code in a pastebin and paste the URL rather than put the code here?
Try changing your query to this:
"SELECT * FROM members WHERE member_id = ?"
and add your param like this:
result.add_parameter(0, id);
I'd also suspect, if (query.exec() && query.next()) is incorrect, and the check for .next() should be removed as I'd imagine that requires another record to exist in the result set.

Location not being saved to config.yml

I'm trying to save a Location in a config.yml, and when he steps onto that location, it provokes an action. However, that is not happening.
Sorry for including the entire code, but I thought it would be essential for this kind of program.
Main class:
public class Turrets extends JavaPlugin{
ArrayList<String> playersThatShouldPlaceBlock = new ArrayList<String>();
HashMap<String, String> turretName = new HashMap<String, String>();
String turretsMsg = ChatColor.RED + "[" + ChatColor.GOLD + "Turrets" + ChatColor.RED + "]" + ChatColor.GOLD + ": ";
public int waitForPlacement;
public void loadConfig() {
this.getConfig().addDefault("Turrets.", null);
this.saveConfig();
}
public void onEnable(){
new CreateTurretEvent(this);
loadConfig();
}
public void onDisable(){
loadConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
final Player p = (Player) sender;
if (cmd.getName().equalsIgnoreCase("turret")){
if (args.length < 2){
p.sendMessage(turretsMsg + ChatColor.RED + "Invalid usage! /turret [create or delete] [name]");
return true;
}
else if (args.length >= 2){
if (args[0].equalsIgnoreCase("create")){
if (args[1] != null){
p.sendMessage(turretsMsg + ChatColor.GOLD + "Place a block and YOU will become a turret when you step on it!");
playersThatShouldPlaceBlock.add(p.getName());
turretName.put(p.getName(), args[1]);
waitForPlacement = Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable(){
#Override
public void run() {
p.sendMessage(turretsMsg + ChatColor.RED + "You waited too long so the action was cancelled!");
playersThatShouldPlaceBlock.remove(p.getName());
}
}, 600L);
return true;
}
}
}
}
return false;
}
}
Listener class:
package me.mortadelle2.turrets;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerMoveEvent;
public class CreateTurretEvent implements Listener{
Turrets getter;
public CreateTurretEvent(Turrets plugin){
plugin.getServer().getPluginManager().registerEvents(this, plugin);
getter = plugin;
}
#EventHandler
public void playerPlacesBlockToBecomeTurret(BlockPlaceEvent e){
Player p = e.getPlayer();
if (getter.playersThatShouldPlaceBlock.contains(p.getName())){
p.sendMessage(getter.turretsMsg + "That block is now turretified!");
getter.getServer().getScheduler().cancelTask(getter.waitForPlacement);
getter.playersThatShouldPlaceBlock.remove(p.getName());
Location blockLocation = e.getBlock().getLocation();
getter.getConfig().set("Turrets." + getter.turretName.get(p.getName()), blockLocation);
}
}
#EventHandler
public void playerStepsOnTurret(PlayerMoveEvent e){
Player p = e.getPlayer();
if (getter.getConfig().contains("test")){ //I will add something more specific than test later
p.sendMessage("This is a test");
}
}
}
Problem 1: spelling mistake (this problem has been edited out of the question at question revision 3)
You seem to have misspelled onDisbale(){. When a plugin is disabled, it will run the method onDisable() on your plugin. In your case it isn't run because you don't have a method with that exact signature.
How to prevent this in the future
By added #Override at the start of a method, you are saying that it MUST override a existing method found in a parent class. This can be used like:
#Override
public void onDisable() {
Problem 2: Implementation of the PlayerMoveEvent isn't finished yet
Notice, stackoverflow isn't a "we write code for you service"
By analyzing your code, you are saving your config in the following format:
playername:
turretname: (location object)
Step 1: changing the location saving
The bukkit configuration doesn't work properly with Location objects, you should change your location saving to
getter.getConfig().set("Turrets." + getter.turretName.get(p.getName())+ ".world", player.getLocation().getWorld().getName());
getter.getConfig().set("Turrets." + getter.turretName.get(p.getName())+ ".x", player.getLocation().getBlockX());
getter.getConfig().set("Turrets." + getter.turretName.get(p.getName())+ ".y", player.getLocation().getBlockY());
getter.getConfig().set("Turrets." + getter.turretName.get(p.getName())+ ".z", player.getLocation().getBlockZ());
This changes the configuration to store the world, x, y and z seperately
Step 2: parsing the config at the PlayerMoveEvent
Because we changed our config format, it will be easier to detect what turret we are standing on at the PlayerMoveEvent
We will the following method of detecting what block we are standing on at the PlayerMove
Check if the turret exists inside the configuration
ConfigurationSection sec = getter.getConfig().getConfigurationSection("Turrets."+getter.turretName.get(p.getName()));
// Todo: check if the player exists inside getter.turretName
if(sec != null){
....
}
Parse the configuration to check if the location is found
Location loc = event.getPlayer().getLocation();
if(loc.getBlockX() == sec.getInt("x") && loc.getBlockY() == sec.getInt("y") && loc.getBlockZ() == sec.getInt("z") && loc.getWorld().getName().equals(sec.getString("world"))) {
event.getPlayer().sendMessage("This is a test");
}
This should fix the problem you are having. The following improvements can be done:
Only call the player move code when the player changes the block
Use more descriptive variable names, for example getter should be renamed to main or plugin