I am trying to make sure that what i choose on ComboBox will be the hostname during the connection i am going to attempt to do
if I hardcode the String Host connection works perfectly fine but I would like to use droplist to determine the host which i want to connect to
here is the code i am having
import javax.swing.*;
import java.awt.event.*;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.*;
import java.util.EmptyStackException;
#SuppressWarnings("serial")
public class welcomewindow extends JFrame {
public static void main(String[] args) {
#SuppressWarnings("unused")
welcomewindow frameTabel = new welcomewindow();
}
String host;
JButton blogin = new JButton("Login");
JLabel UIusername = new JLabel("Username",SwingConstants.LEFT);
JLabel Jumpbox = new JLabel("Choose your Jumpbox",SwingConstants.LEFT);
JLabel UIpassword = new JLabel("Password",SwingConstants.LEFT);
JTextField txuser = new JTextField(15);
//JComboBox ComboBox = new JComboBox();
#SuppressWarnings({ })
String[] J1J2 = {"ServerA", "ServerB"};
#SuppressWarnings({ "unchecked", "rawtypes" })
JComboBox JumpList= new JComboBox(J1J2);
JPasswordField pass = new JPasswordField(15);
#SuppressWarnings({ "rawtypes", "unchecked" })
welcomewindow(){
super("Login Authorization to Tracer");
setSize(300,150);
setLocation(500,280);
//panel.setLayout (null);
String[] J1J2 = {"ServerA", "ServerB"};
JComboBox JumpList= new JComboBox(J1J2);
UIusername.setVerticalAlignment(SwingConstants.CENTER);
UIpassword.setVerticalAlignment(SwingConstants.CENTER);
Jumpbox.setVerticalAlignment(SwingConstants.CENTER);
JLabel UIusername = new JLabel("Username",SwingConstants.LEFT);
JLabel UIpassword = new JLabel("Password",SwingConstants.LEFT);
JLabel Jumpbox = new JLabel("Choose Your Jumpbox",SwingConstants.LEFT);
blogin.setVerticalAlignment(SwingConstants.CENTER);
JumpList.setSelectedIndex(0);
JPanel panel = new JPanel();
panel.add(Jumpbox);
panel.add(JumpList);
panel.add(UIusername);
panel.add(txuser);
panel.add(UIpassword);
panel.add(pass);
panel.add(blogin);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
panel.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"EnterButton1");
panel.getRootPane().getActionMap().put("EnterButton1",new AbstractAction(){
public void actionPerformed(ActionEvent ae)
{
String puname = txuser.getText();
#SuppressWarnings("deprecation")
String ppaswd = pass.getText();
if(puname.isEmpty() || ppaswd.isEmpty()){
JOptionPane.showMessageDialog(null,"Username Or Password Field is empty");
}
else{
blogin.doClick();
}
}
});
actionlogin();
}
public void actionlogin(){
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String puname1 = txuser.getText();
#SuppressWarnings("deprecation")
String ppaswd1 = pass.getText();
String host = (String) JumpList.getSelectedItem();
if(puname1.isEmpty() || ppaswd1.isEmpty()){
JOptionPane.showMessageDialog(null,"Username Or Password Field is empty");
}
else{
String puname = txuser.getText();
#SuppressWarnings("deprecation")
String ppaswd = pass.getText();
String command1="pwd";
int port=22;
String remoteFile="/home/bsoghmonian/test.txt";
System.out.println(host);
boolean sshconnected = false;
try
{
System.out.println(host);
JSch jsch = new JSch();
Session session = jsch.getSession(puname, host, port);
session.setPassword(ppaswd);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
System.out.println("Crating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sshconnected = true;
System.out.println("SFTP Channel created.");
if(sshconnected){
instancewindow instancewelcome =new instancewindow();
instancewelcome.setVisible(true);
dispose();
}else{
throw new EmptyStackException();
}
............. till the end of the Program
The Issue I have here is even if I choose Server B user attempts to connect to ServerA I would like if user chooses ServerB the application attempts to connect the user to ServerB and when ServerA chosen then connects to ServerA
You defined the same JComboBox two times - you operate (change values) on a local one within welcomewindow(), but then you take JumpList.getSelectedItem() from the untouched global one, hence it's always the first option ;)
Related
I have written code using JDBC to create registration page in Android Studio. I create database in SQL Server 2019. In addition I tried to connect from the code to MSSQL database and insert values, but while I run the app I'm getting the error:
login failed for user.
I have examined many options that can cause this error and I fixed them. For example: The server authentication is SQL Server authentication,the TCP option at the server is enabled, I have the relevant permissions of the user, also I check the if the firewall is the cause for this error. However, I continue to receive the error.
The connection class:
public class ConnectionClass {
public static String ip= "***.***.*.*:1433"; //
public static String user_name ="****";
public static String password = "****";
public static String database = "tests";
}
The Registeration class:
EditText email;
EditText password;
EditText confirmPassword;
Button sign_up;
EditText name;
Connection connection1;
Statement statement;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_parent);
email = (EditText) findViewById(R.id.editTextTextEmailAddress2);
password = (EditText) findViewById(R.id.editTextTextPassword);
confirmPassword = (EditText) findViewById(R.id.editTextTextPassword2);
sign_up = (Button) findViewById(R.id.button);
name = (EditText) findViewById(R.id.editTextTextPassword3);
status = (TextView) findViewById(R.id.status);
sign_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ParentSignUp.registerUser().execute("");
}
});
}
public class registerUser extends AsyncTask<String, String, String>{
String z ="";
Boolean isSuccess = false;
public registerUser() {
super();
}
#Override
protected void onPreExecute() {
status.setText("Sending Data to Database");
}
#Override
protected void onPostExecute(String s) {
name.setText("");
email.setText("");
password.setText("");
confirmPassword.setText("");
}
#Override
protected String doInBackground(String... strings) {
try {
connection1 = connection_class(ConnectionClass.user_name.toString(), ConnectionClass.password.toString(),
ConnectionClass.database.toString(), ConnectionClass.ip.toString());
if (connection1 == null) {
z = "Check Internet Connection";
}
else {
String sql = "INSERT INTO test (name,password, email) VALUES ('example', 'example', 'example')";
statement = connection1.createStatement();
statement.executeUpdate(sql);
}
}
catch (Exception e) {
isSuccess = false;
z = e.getMessage();
}
return null;
}
}
#SuppressLint("NewApi")
public Connection connection_class (String user, String password, String database, String server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String connectionUrl = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connectionUrl = "jdbc:jtds:sqlserver://" + server + "/" + database + ";user=" + user + ";"+"password=" + password + ";";
connection = DriverManager.getConnection(connectionUrl);
}catch (Exception e){
Log.e("SQL Connection Error : ", e.getMessage());
}
return connection;
}
I have written a jar which has jedis connection pool feature, by using which I have written the groovy script in nifi for redis location search. But it is behaving stangely, sometimes it is working and sometimes not.
Redis.java
public class Redis {
private static Object staticLock = new Object();
private static JedisPool pool;
private static String host;
private static int port;
private static int connectTimeout;
private static int operationTimeout;
private static String password;
private static JedisPoolConfig config;
public static void initializeSettings(String host, int port, String password, int connectTimeout, int operationTimeout) {
Redis.host = host;
Redis.port = port;
Redis.password = password;
Redis.connectTimeout = connectTimeout;
Redis.operationTimeout = operationTimeout;
}
public static JedisPool getPoolInstance() {
if (pool == null) { // avoid synchronization lock if initialization has already happened
synchronized(staticLock) {
if (pool == null) { // don't re-initialize if another thread beat us to it.
JedisPoolConfig poolConfig = getPoolConfig();
boolean useSsl = port == 6380 ? true : false;
int db = 0;
String clientName = "MyClientName"; // null means use default
SSLSocketFactory sslSocketFactory = null; // null means use default
SSLParameters sslParameters = null; // null means use default
HostnameVerifier hostnameVerifier = new SimpleHostNameVerifier(host);
pool = new JedisPool(poolConfig, host, port);
//(poolConfig, host, port, connectTimeout,operationTimeout,password, db,
// clientName, useSsl, sslSocketFactory, sslParameters, hostnameVerifier);
}
}
}
return pool;
}
public static JedisPoolConfig getPoolConfig() {
if (config == null) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
int maxConnections = 200;
poolConfig.setMaxTotal(maxConnections);
poolConfig.setMaxIdle(maxConnections);
poolConfig.setBlockWhenExhausted(true);
poolConfig.setMaxWaitMillis(operationTimeout);
poolConfig.setMinIdle(50);
Redis.config = poolConfig;
}
return config;
}
public static String getPoolCurrentUsage()
{
JedisPool jedisPool = getPoolInstance();
JedisPoolConfig poolConfig = getPoolConfig();
int active = jedisPool.getNumActive();
int idle = jedisPool.getNumIdle();
int total = active + idle;
String log = String.format(
"JedisPool: Active=%d, Idle=%d, Waiters=%d, total=%d, maxTotal=%d, minIdle=%d, maxIdle=%d",
active,
idle,
jedisPool.getNumWaiters(),
total,
poolConfig.getMaxTotal(),
poolConfig.getMinIdle(),
poolConfig.getMaxIdle()
);
return log;
}
private static class SimpleHostNameVerifier implements HostnameVerifier {
private String exactCN;
private String wildCardCN;
public SimpleHostNameVerifier(String cacheHostname)
{
exactCN = "CN=" + cacheHostname;
wildCardCN = "CN=*" + cacheHostname.substring(cacheHostname.indexOf('.'));
}
public boolean verify(String s, SSLSession sslSession) {
try {
String cn = sslSession.getPeerPrincipal().getName();
return cn.equalsIgnoreCase(wildCardCN) || cn.equalsIgnoreCase(exactCN);
} catch (SSLPeerUnverifiedException ex) {
return false;
}
}
}
}
CustomFunction:
public class Functions {
SecureRandom rand = new SecureRandom();
private static final String UTF8= "UTF-8";
public static JedisPool jedisPool=null;
public static String searchPlace(double lattitude,double longitude) {
try(Jedis jedis = jedisPool.getResource()) {
}
catch(Exception e){
log.error('execption',e);
}
}
}
Groovyscript:
import org.apache.nifi.processor.ProcessContext;
import com.customlib.functions.*;
def flowFile = session.get();
if (flowFile == null) {
return;
}
def flowFiles = [] as List<FlowFile>
def failflowFiles = [] as List<FlowFile>
def input=null;
def data=null;
static onStart(ProcessContext context){
Redis.initializeSettings("host", 6379, null,0,0);
Functions.jedisPool= Redis.getPoolInstance();
}
static onStop(ProcessContext context){
Functions.jedisPool.destroy();
}
try{
log.warn('is jedispool connected::::'+Functions.jedisPool.isClosed());
def inputStream = session.read(flowFile)
def writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
data=writer.toString();
input = new JsonSlurper().parseText( data );
log.warn('place is::::'+Functions.getLocationByLatLong(input["data"]["lat"], input["data"]["longi"]);
.......
...........
}
catch(Exception e){
}
newFlowFile = session.write(newFlowFile, { outputStream ->
outputStream.write( data.getBytes(StandardCharsets.UTF_8) )
} as OutputStreamCallback)
failflowFiles<< newFlowFile;
}
session.transfer(flowFiles, REL_SUCCESS)
session.transfer(failflowFiles, REL_FAILURE)
session.remove(flowFile)
The nifi is in 3 node cluster. The function lib is configured in groovyscript module directory.In the above groovy script processor, the log statement is jedispool connected:::: is sometimes printing false,sometimes true but after deploying for the first time jar every time works. But later it is unpredictable, I am not getting what is wrong in the code. How the groovyscript will load the jar. How can I acheive the lib based search using groovy script.
Redis.pool never gets null after initialization. You are calling pool.destroy() but not setting it to null.
getPoolInstance() checks if pool is null only then it creates a new pool.
I don't see any reason to have 2 variables to hold reference to the same pool: in Redis and in Functions class.
I'm writing an App with login and register, it works but I want to add something. Is it possible, when a user register his datas, to get directly from his phone the Mac Address and store it together the other datas?
For example, he has to insert name, user, password and email, when he clicks on register in the database there are all this datas and the macaddress of his phone too.
This is my RegisterActivity.java:
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by amardeep on 10/26/2017.
*/
public class RegisterActivity extends AppCompatActivity {
//Declaration EditTexts
EditText editTextUserName;
EditText editTextEmail;
EditText editTextPassword;
//Declaration TextInputLayout
TextInputLayout textInputLayoutUserName;
TextInputLayout textInputLayoutEmail;
TextInputLayout textInputLayoutPassword;
//Declaration Button
Button buttonRegister;
//Declaration SqliteHelper
SqliteHelper sqliteHelper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sqliteHelper = new SqliteHelper(this);
initTextViewLogin();
initViews();
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validate()) {
String UserName = editTextUserName.getText().toString();
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
//Check in the database is there any user associated with this email
if (!sqliteHelper.isEmailExists(Email)) {
//Email does not exist now add new user to database
sqliteHelper.addUser(new User(null, UserName, Email, Password));
Snackbar.make(buttonRegister, "User created successfully! Please Login ", Snackbar.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, Snackbar.LENGTH_LONG);
}else {
//Email exists with email input provided so show error user already exist
Snackbar.make(buttonRegister, "User already exists with same email ", Snackbar.LENGTH_LONG).show();
}
}
}
});
}
//this method used to set Login TextView click event
private void initTextViewLogin() {
TextView textViewLogin = (TextView) findViewById(R.id.textViewLogin);
textViewLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
//this method is used to connect XML views to its Objects
private void initViews() {
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputLayoutUserName = (TextInputLayout) findViewById(R.id.textInputLayoutUserName);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
}
//This method is used to validate input given by user
public boolean validate() {
boolean valid = false;
//Get values from EditText fields
String UserName = editTextUserName.getText().toString();
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
//Handling validation for UserName field
if (UserName.isEmpty()) {
valid = false;
textInputLayoutUserName.setError("Please enter valid username!");
} else {
if (UserName.length() > 5) {
valid = true;
textInputLayoutUserName.setError(null);
} else {
valid = false;
textInputLayoutUserName.setError("Username is to short!");
}
}
//Handling validation for Email field
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
textInputLayoutEmail.setError("Please enter valid email!");
} else {
valid = true;
textInputLayoutEmail.setError(null);
}
//Handling validation for Password field
if (Password.isEmpty()) {
valid = false;
textInputLayoutPassword.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
textInputLayoutPassword.setError(null);
} else {
valid = false;
textInputLayoutPassword.setError("Password is to short!");
}
}
return valid;
}
}
Thank you very much!
I want rename the PowerPoint slide master by apache poi. In PowerPoint GUI we do View - Slide Master - then we right click the top most slide on left side and select Rename Master from context menu.
In a PowerPoint presentation the master is named such as it's theme. We can get all masters using XMLSlideShow.getSlideMasters. XSLFSlideMaster
extends XSLFSheet. So we can get the theme of each master using XSLFSheet.getTheme. Once we have the XSLFTheme there are getters and setters for the name.
Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xslf.usermodel.*;
public class XSLFRenameMasterTheme {
public static void main(String[] args) throws Exception {
XMLSlideShow slideshow = new XMLSlideShow(new FileInputStream("Presentation.pptx"));
for (XSLFSlideMaster master : slideshow.getSlideMasters()) {
XSLFTheme theme = master.getTheme();
String name = theme.getName();
System.out.println(name);
theme.setName(name + " renamed");
System.out.println(theme.getName());
}
FileOutputStream out = new FileOutputStream("PresentationRenamedMaster.pptx");
slideshow.write(out);
out.close();
slideshow.close();
}
}
For HSLFSlideShow is seems there is no access to master names supported. One can get the HSLFSlideMasters but not the names of them.
So if one needs doing that nevertheless, then one must know about the internals of the binary *.ppt file system. This is documented in [MS-PPT]: PowerPoint (.ppt) Binary File Format. The sheet names are in a SlideNameAtom. With knowledge about the internals one can create a class for that kind of record. This can providing methods for get and set the name then.
Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.hslf.record.Record;
import org.apache.poi.hslf.record.RecordAtom;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.StringUtil;
public class HSLFRenameMaster {
// method for get SlideNameAtom out of the master
private static SlideNameAtom getSlideNameAtom(HSLFSlideMaster master) throws Exception {
SlideNameAtom slideNameAtomRecord = null;
Record record = master.getSheetContainer().findFirstOfType(0x0FBA);
if (record != null) { // SlideNameAtom exists
// get present data
ByteArrayOutputStream out = new ByteArrayOutputStream();
record.writeOut(out);
out.flush();
byte[] data = out.toByteArray();
out.close();
// create new SlideNameAtom from data
slideNameAtomRecord = new SlideNameAtom(data);
// replace old record with new SlideNameAtom
master.getSheetContainer().addChildBefore(
slideNameAtomRecord,
record
);
master.getSheetContainer().removeChild(record);
}
return slideNameAtomRecord;
}
public static void main(String[] args) throws Exception {
HSLFSlideShow slideshow = new HSLFSlideShow(new FileInputStream("Presentation.ppt"));
for (HSLFSlideMaster master : slideshow.getSlideMasters()) {
SlideNameAtom slideNameAtomRecord = getSlideNameAtom(master);
if (slideNameAtomRecord != null) {
String name = slideNameAtomRecord.getName();
System.out.println(name);
slideNameAtomRecord.setName(name + " renamed");
System.out.println(slideNameAtomRecord.getName());
}
}
FileOutputStream out = new FileOutputStream("PresentationRenamedMaster.ppt");
slideshow.write(out);
out.close();
slideshow.close();
}
//class SlideNameAtom
//having methods for manipulating the [SlideNameAtom](https://msdn.microsoft.com/en-us/library/dd906297(v=office.12).aspx)
private static class SlideNameAtom extends RecordAtom {
private byte[] data;
private String name;
public SlideNameAtom() {
this.name = "Office";
setName(name);
}
public SlideNameAtom(byte[] data) {
this.data = data;
this.name = getName();
}
public void setName(String name) {
this.name = name;
int length = 8;
length += StringUtil.getToUnicodeLE(name).length;
this.data = new byte[length];
data[0] = (byte)0x20; data[1] = (byte)0x00;
data[2] = (byte)0xBA; data[3] = (byte)0x0F; //MUST be 0x0fba = RT_CString (little endian)
LittleEndian.putInt(data, 4, StringUtil.getToUnicodeLE(name).length);
StringUtil.putUnicodeLE(name, data, 8);
}
public String getName() {
return StringUtil.getFromUnicodeLE(this.data, 8, (this.data.length-8)/2);
}
#Override
public void writeOut(OutputStream out) throws IOException {
out.write(data);
}
#Override
public long getRecordType() { return 0x0FBA; }
}
}
The question is whether renaming the master is worth that effort.
i need to read the contents of text file, line by line and display it on the Jtable, the table should be editable by users as needed, Any help Appreciated. I am new to Java. Thank You.
My Text File: File Name(people.txt)
COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY COLUMN_DEFAULT EXTRA
Names VARCHAR(500) NO
Address VARCHAR(500) NO
My Code So Far:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class readtext {
static public void main(String[] arg){
JScrollPane scroll;
JTable table;
DefaultTableModel model;
String fname="people";
try
{
FileInputStream fstream = new FileInputStream("D:/joy/text/"+fname+".txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine,str = null;
//Read File Line By Line
String text = "";
Vector myVector = new Vector();
while ((strLine = br.readLine()) != null) //loop through each line
{
myVector.add(strLine );
// Print the content on the console
text +=(strLine+"\n"); // Store the text file in the string
}
in.close();//Close the input stream
int i=0;
String fline=myVector.elementAt(0).toString();
String[] sp=fline.split("\\s+");
for(String spt:sp){
System.out.println(spt);
//model = new DefaultTableModel(spt, ); // I dont know how to put the strings
into Jtable here
table = new JTable(){
public boolean isCellEditable(int row, int column){
return false;
}
};
int a=0;// for text box name
for(i=1;i<myVector.size();i++){
str=myVector.elementAt(i).toString();
String[] res =str.split("\\s+");
int k=0;
for(String st:res)
System.out.println(st);
k++;a++; }
} }
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thank You.
File Content: (Each attribute is separated by a semicolon and each line is a record.)
Hello1;123
World1;234
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class FileToJTable {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
new FileToJTable().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
try {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JTable table = new JTable();
String readLine = null;
StudentTableModel tableModel = new StudentTableModel();
File file = new File(""/*Give your File Path here*/);
FileReader reader = new FileReader(file);
BufferedReader bufReader = new BufferedReader(reader);
List<Student> studentList = new ArrayList<Student>();
while((readLine = bufReader.readLine()) != null) {
String[] splitData = readLine.split(";");
Student student = new Student();
student.setName(splitData[0]);
student.setNumber(splitData[1]);
studentList.add(student);
}
tableModel.setList(studentList);
table.setModel(tableModel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.setTitle("File to JTable");
frame.pack();
frame.setVisible(true);
} catch(IOException ex) {}
}
class Student {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
class StudentTableModel extends AbstractTableModel {
private List<Student> list = new ArrayList<Student>();
private String[] columnNames = {"Name", "Number"};
public void setList(List<Student> list) {
this.list = list;
fireTableDataChanged();
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return list.size();
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return list.get(rowIndex).getName();
case 1:
return list.get(rowIndex).getNumber();
default:
return null;
}
}
}
}
Well i didnt read ur code...however i'm telling u one of the simplest way of doing this...hope this helps
Define a DefaultTableModel:
String columns[] = { //Column Names// };
JTable contactTable = new JTable();
DefaultTableModel tableModel;
// specify number of columns
tableModel = new DefaultTableModel(0,2);
tableModel.setColumnIdentifiers(columns);
contactTable.setModel(tableModel);
Reading from text file:
String line;
BufferedReader reader;
try{
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null)
{
tableModel.addRow(line.split(", "));
}
reader.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
Also, if you want to allow users to edit the data, then you need to set a TableCellEditor on the cells that you want people to edit. You probably also want to start using a TableModel instead of hard coding the data in the JTable itself.
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html