I'm writing a code for a JTable that contains search results from a DB, and I need to initialize it with no rows in each click on "doSort" button by setRowCount(0) method or by initTable() method, I've wrote the following code, but it does not work:
private void doSortActionPerformed(java.awt.event.ActionEvent evt) {
try {
ArrayList<String> all = null;
String resStr = null;
mail = new Mail();
tm.setRowCount(0);
initTable(tm);
if(incomSelect.isSelected())
try {
all = mail.select("SELECT * FROM mails WHERE type = 'incoming'");
} catch (SQLException ex) {
}
else if(outcomSelect.isSelected())
try {
all = mail.select("SELECT * FROM mails WHERE type = 'outcoming'");
} catch (SQLException ex) {
}
for(int i=0; i<all.size(); i++) {
resStr = all.get(i);
String[] resArr = resStr.split(",");
tm.insertRow(i, resArr);
}
} catch (SQLException ex) {
}
}
And initTable() code:
public void initTable(DefaultTableModel mod){
for (int i = mod.getRowCount()-1; i >= 0; i--) {
mod.removeRow(i);
}
}
Related
I'm trying to make simple telegram bot on Java.
The question is: how can I receive messages in a loop, when the user typed /start? I have already some
#Override
public void onUpdateReceived(Update update) {
Message msg = update.getMessage();
String txt = msg.getText();
if (txt.equals("/start")) {
sendMsg(msg, "Привет, меня зовут бот " + name + "!");
showHelp(msg);
run(msg, update);
} else if (txt.equals("/help")) {
showHelp(msg);
}
}
Here's showhelp:
private void showHelp(Message msg) {
try {
String inAbout = ReadFile.readFileInString(this.about);
sendMsg(msg, inAbout);
} catch (Exception ex) {
ex.printStackTrace();
}
}
sendMsg:
private void sendMsg(Message msg, String text) {
SendMessage s = new SendMessage();
s.setChatId(msg.getChatId());
s.setText(text);
try {
execute(s);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
In Run I want to read questions from data and wait for users answer, check if correct and do it in loop. In the end show how many he answered correct.
public void run(Message msg, Update update) {
try {
List<String> data = ReadFile.readFileInList(this.getData());
List<String> dataAnswers = ReadFile.readFileInList(this.answers);
this.sizeOfAnswers = data.size();
for (int i = 0; i < data.size(); i++) {
String line = data.get(i);
sendMsg(msg, line);
String inAnswer = update.getMessage().getText();
String rAns = dataAnswers.get(i);
boolean flag = checkAnswer(inAnswer, rAns);
if (flag) {
this.currentUser.incrementScore();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
String finalString = "Поздравляю, ты ответил на " + this.currentUser.getScore() + "/" + this.sizeOfAnswers
+ " вопросов!";
sendMsg(msg, finalString);
}
}
Also here is maybe some multi user problems. How should I do it? Now it's showing all questions in one second without waiting for an answer.
How it's working now
I'm working on a modbus UDP implementation [ J2Mod(2.3.4) ] in Java. I have found almost no useful documentation. I have a boolean array like flags.
Slave will read it via SimpleProcessImage->DigitalIn
Slave will use that flags and change them
Then write it to SimpleProcessImage->DigitalOut in every 10 secs.
I need help on 1st step. When I use master.readCoils(i, 1) and master.writeCoils(i, true). It only use DigitalOut. It write to DigitalOut and read from DigitalOut.
for (int i = 0; i < interSize ; i++) {
SimpleDigitalOut dout = (SimpleDigitalOut) image.getDigitalOut(i);
dout.set(i%5==0);
image.setDigitalOut(i, dout);
}
If I change DigitalOut on slave side as shown above, I can get changed values through DigitalOut. But I need to use them both; DigitalOut and DigitalIn.
Here's my code for slave.
public class Slave {
private SimpleProcessImage image;
private ModbusSlave slave;
private int interSize = 62000;
int step;
public Slave(){
image = new SimpleProcessImage();
step=0;
for (int i = 0; i < interSize; i++) {
image.addDigitalOut(i, new SimpleDigitalOut(false));
image.addDigitalIn(i, new SimpleDigitalIn(false));
}
(new Timer()).scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
read();
write();
}
}, 0, 10000);
startServer();
}
private void read() {
System.out.print("Read In : ");
for (int i = 0; i < interSize; i++) {
System.out.print((image.getDigitalIn(i).isSet() ? 1 : 0) + " ");
}
System.out.print("Read Out: ");
for (int i = 0; i < interSize; i++) {
System.out.print((image.getDigitalOut(i).isSet() ? 1 : 0) + " ");
}
}
public void startServer() {
try {
slave = ModbusSlaveFactory.createUDPSlave(502);
slave.addProcessImage(0, image);
slave.open();
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
Also here my client
public class Client {
private ModbusUDPMaster master;
int interSize = 62000 ;
Client() {
master = new ModbusUDPMaster("127.0.0.1", 502);
try {
master.connect();
} catch (Exception e) {
e.printStackTrace();
}
write();
while(true){
read();
}
}
public static void main(String... args) {
new Client();
}
private void write() {
for (int i = 0; i < interSize; i++) {
try {
master.writeCoil(i, i%3==0);
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
private void read() {
try {
for (int i = 0; i < interSize; i++) {
System.out.print(master.readCoils(i, 1).toString());
}
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
If anybody still looking for answer, as shown here, you can read DigitalIn via readInputDiscretes function.
Read Discretes
// master.readInputDiscretes(<discrete ref>, <count>); // Uses a UNIT ID of 1
master.readInputDiscretes(<unit id>, <discrete ref>, <count>);
The problem I am having is acquiring all reachable clients on a network.The below method returns some clients when called. In most cases other android clients.However for the PC it fails when firewall is on.Is there a more effective way to get all clients in Java/android purely or will I need to use android NDK?Any help from experts in this domain will be appreciated.Thanks in advance.
/***
* ping_JavaStyle(final int j)
* uses multi threads to enhance performance
* while pinging from 0>j<=255
* #param j
*/
private void ping_JavaStyle(final int j)
{
new Thread(new Runnable() { // new thread for parallel execution
public void run() {
try {
String testIp = prefix + String.valueOf(j);
InetAddress address = InetAddress.getByName(testIp);
String output = address.toString().substring(1);
if (address.isReachable(3000)) {
System.out.println(output + " is on the network");
ipList.add(testIp);
} else {
if (retest(testIp, 139)) {
ipList.add(testIp);
} else {
System.out.println("Not Reachable: " + output);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
After Researching some more, got this working.With help of this repo:https://github.com/stealthcopter/AndroidNetworkTools
Below code solves the problem:
** RunnableTask.Java
* Created by Kirk on 10/29/2017.
*/
public class RunnableTask implements Callable<Boolean> {
private String testIp = "";
private Boolean is_Reachable = false;
public RunnableTask(String testIp) {
this.testIp = testIp;
}
#Override
public Boolean call() throws Exception {
try {
PingResult pingResult = Ping.onAddress(this.testIp).setTimes(1).setTimeOutMillis(1500).doPing();
if (pingResult.isReachable) {
is_Reachable = true;
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return is_Reachable;
}
}
And use in the caller method:
private static final int NTHREDS = 255;
//.......
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
List<Future<Boolean>> thread_Values_list = new ArrayList<>();
for (int i = 1; i <= 255; i++) {
final int j = i;
try {
try {
String testIp = prefix + String.valueOf(j);
RunnableTask worker = new RunnableTask(testIp);
Future<Boolean> submit = executor.submit(worker);
thread_Values_list.add(submit);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
}
for (Future<Boolean> finishedThread : thread_Values_list) {
String reachable_Ip = "";
try {
if (finishedThread.get()) {
reachable_Ip = prefix + String.valueOf(finishThread_counter);
ipList.add(reachable_Ip);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
finishThread_counter++;
}
executor.shutdown();
}
I am working on a basic desktop Java application. I have a "more" buttons and when I click on it a new line of JTextField and JDateChooser appears. All I want is to store these lines into database. How can I implement it?
Here is my code.
MemberDao.java
public boolean isExist(CachedRowSet crs, String colName) throws SQLException {
ResultSetMetaData meta = crs.getMetaData();
int columns = meta.getColumnCount();
for (int x = 1; x <= columns; x++) {
if (colName.equals(meta.getColumnName(x))) {
return true;
}
}
return false;
}
InsertMember.java
if(evt.getSource()==more){
try {
if(MemberDao.getInstance().isExist(crs,"mem_familyname")){
System.out.println("found");
} else {
System.out.println("not found");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
But this code gives me a NullPinterException
The aim is to make the link clickable in jtable so that when user clicks on the link the desired page gets opened in the browser. One of the items fetched from database is link and my attempt is to make it active and clickable. I get the error as
Unhandled exception type URISyntaxException
For the line in my code:
final URI uri = new URI("http://www.roseindia.net");
And even if i put it in try catch block, the error doesn't seem to resolve. Rather on surrounding in a try-catch block, I get the error as
Cannot refer to a non-final variable uri inside an inner class defined in a different method
So what could be the possible solution and fix?
public class JTableButtonMouseListener extends MouseAdapter
{
private final JTable table;
public JTableButtonMouseListener(JTable table)
{
this.table = table;
}
public void mouseClicked(MouseEvent e) {
counter=0;
// System.out.println("***************************************************************");
System.out.println("counter value="+counter++);
//System.out.println("/////////////////////////////////////////////////////////////////////");
int column = table.getColumnModel().getColumnIndexAtX(e.getX());
int row = e.getY()/table.getRowHeight();
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
Object value = table.getValueAt(row, column);
// System.out.println("row clicked="+row);
//System.out.println("column clicked="+column);
System.out.println("object value="+value);
System.out.println(".............................................................");
/* public void getsecname(String s)
{
String ss=s;
}*/
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
// final URI uri = null;
// URI uri;
try{
final URI uri = new URI("http://www.roseindia.net");
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
// button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
} else {
}
}
});
}
// String link_string=ob.toString();
//ob.setClickable(true);
if(value==null)
{
Object v=table.getValueAt(row, 1);
//System.out.println("--------------------------------------------");
s = v.toString();
jmenu_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jmenu_frame.setContentPane(new ListModelExample(s));
jmenu_frame.setSize(260, 200);
jmenu_frame.setVisible(true);
jmenu_frame.setLocationRelativeTo(null);
//it ends here
}
if (value instanceof JButton) {
((JButton)value).doClick();
}
}
}
}
You can not use non-final variable inside your inner class. Discussion.
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
try {
final URI uri = new URI("http://www.roseindia.net");
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
//button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
}
}
});
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
What is telling you is that you need a try catch block to handle a URISyntaxException:
final URI;
try{
uri = new URI("http://www.roseindia.net");
} catch (URISyntaxException e) {
e.printStackTrace();
}
To solve uri cannot be resolved to a variable You could instead of using try catch, add a throws URISyntaxException to the method in which uri is declared. But I do not think that is a good practice. Maybe it works in your case.