Im made a program that takes strings from the whole jtable and populates my database in ms access. But whenever i run it my database has [] instead of the actual information. How do i take the information in my jtable and use that to populate my database?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class apples extends JPanel {
static JTable table;
static JFrame frame;
static apples a;
static ActionListener actionListener;
static ActionListener actionListenerImport;
static ActionListener actionListenerAddrow;
static String[] columns = {"Fname","Lname"};
static String[][] data;
static DefaultTableModel model = new DefaultTableModel(data, columns);
public static void main(String[] args) {
table = new JTable(model);
frame = new JFrame();
table.setPreferredScrollableViewportSize(new Dimension(450, 200));
table.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane(table);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(jps);
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton("Start");
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
panel.add(b1, c);
JButton b2 = new JButton("Import");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
panel.add(b2, c);
JButton b3 = new JButton("Add Row");
c.gridx = 3;
c.gridy = 0;
c.insets = new Insets(10,10,10,10);
panel.add(b3, c);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.getContentPane().add(jps, BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:TestDatabase");
Statement s = con.createStatement();
String deleteRows = "DELETE FROM Table1";
s.execute(deleteRows);
ArrayList<String> numdata = new ArrayList<String>();
ArrayList<String> numdata2 = new ArrayList<String>();
String insertTable = ("INSERT INTO Table1(Fname,Lname) VALUES('"+numdata+"','"+numdata2+"');");//get data from table and put in here
for (int count = 0; count < model.getRowCount(); count++){
numdata.add(model.getValueAt(count, 0).toString());
for (int count1 = 0; count1 < model.getRowCount(); count1++){
numdata2.add(model.getValueAt(count, 1).toString());
s.executeUpdate(insertTable);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
e.getMessage();
} catch (SQLException e) {
e.printStackTrace();
e.getMessage();
}
}
};
actionListenerImport = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:TestDatabase");
Statement s = con.createStatement();
String selTable = "SELECT * FROM Table1";
s.execute(selTable);
ResultSet rs = s.getResultSet();
while((rs!= null) && (rs.next())) {
model.addRow(new String[]{rs.getString(1),rs.getString(2)});
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
e.getMessage();
} catch (SQLException e) {
e.printStackTrace();
e.getMessage();
}
}
};
actionListenerAddrow = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
model.addRow(new String[]{"",""});
}
};
b1.addActionListener(actionListener);
b2.addActionListener(actionListenerImport);
b3.addActionListener(actionListenerAddrow);
}
}
ArrayList<String> numdata = new ArrayList<String>();
ArrayList<String> numdata2 = new ArrayList<String>();
String insertTable = ("INSERT INTO Table1(Fname,Lname) VALUES('"+numdata+"','"+numdata2+"');");
You are attempting to add an ArrayList into your database. You can't just change the values of numdata and numdata2 in your loop.
Instead you need to create a dynamic SQL statement. The easiest way to do this is to use a PreparedStatement, then you can dynamically change the parameters. The code would be something like:
String sql = "INSERT INTO Table1(Fname,Lname) VALUES(?,?)";
PreparedStatement stmt = connection.prepareStatement(sql);
for (int count = 0; count < model.getRowCount(); count++)
{
String numdata = model.getValueAt(count, 0).toString();
String numdata2 = model.getValueAt(count, 1).toString();
stmt.setString( 1, numdata );
stmt.setString( 2, numdata2 );
stmt.executeUpdate();
}
Related
I Browse a csv file and load the contents of the file to Jtable.
I want to add the JcomboBox in every row of the JTable .
Here is my tool for your reference:
I dont know how to add the ComboBox in each column of row.please help me to solve this problem .Any help is appreciated
Here is my code for your reference....
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.List;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import com.csvreader.CsvReader;
public class GUI {
private JPanel dialog = null;
private AboutDialog adlg;
public void addComponentsToPane() {
final JTextField txtfldcsvpth = new JTextField("Select a folder");
final JTextField txtsimprepname = new JTextField("Select a folder");
final JButton Btnbrowsecsv = new JButton("Select file");
final JButton BtnsimpRep = new JButton("Create SimpRep");
final JTable table = new JTable(){
final long serialVersionUID = 1L;
public boolean isCellEditable(int row,int column) {
return false;
};
};
BtnsimpRep.setEnabled(true);
dialog.setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.anchor = GridBagConstraints.LINE_START;
gBC.fill = GridBagConstraints.HORIZONTAL;
gBC.insets = new Insets(3, 3, 3, 3);
gBC.weightx = 1;
gBC.weighty = 0;
/******************************Browse Csv File***************************************/
JLabel label1 = new JLabel("Input File");
label1.setHorizontalAlignment(SwingConstants.RIGHT);
label1.setHorizontalTextPosition(SwingConstants.RIGHT);
label1.setPreferredSize(new Dimension(100, Btnbrowsecsv
.getPreferredSize().height));
gBC.gridx = 0;
gBC.gridy = 0;
dialog.add(label1, gBC);
//jtextfield for CsvPath
gBC.gridx = 1;
gBC.gridy = 0;
txtfldcsvpth.setPreferredSize(new Dimension(200, Btnbrowsecsv
.getPreferredSize().height));
txtfldcsvpth.setEditable(false);
dialog.add(txtfldcsvpth, gBC);
//Jbutton for Csv Browsing..
gBC.gridx = 2;
gBC.gridy = 0;
Btnbrowsecsv.setToolTipText("Select folder containing STEP files");
Btnbrowsecsv.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String selectedFile = fileChooserMethod();
if (selectedFile != null) {
txtfldcsvpth.setText(selectedFile);
try{
BufferedReader br = new BufferedReader(new FileReader(new File(selectedFile)));
ArrayList <String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
JOptionPane.showMessageDialog(null, elements);
String[] columNames = new String[] {"Serial No","PartNumber", "Quantity"};
Object[][] content = new Object[elements.size()][3];
for(int i=1; i<elements.size(); i++) {
content[i][0] = i;
content[i][1] = elements.get(i)[1].trim();
content[i][2] = elements.get(i)[0].trim();
//content[i][2] = elements.get(i)[2].trim();
// content[i][3] = elements.get(i)[3].trim();
}
JOptionPane.showMessageDialog(null, content.length);
table.setModel(new DefaultTableModel(content,columNames));
}catch(Exception e){
}
}
}
});
dialog.add(Btnbrowsecsv, gBC);
/******************************JTable for CsvGrid***************************************/
JScrollPane js=new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
js.setPreferredSize(new Dimension(300 + Btnbrowsecsv
.getPreferredSize().width, 400));
js.setVisible(true);
js.setHorizontalScrollBar(null);
// final JTable jt=new JTable(data,column);
table.setCellSelectionEnabled(false);
table.setRowSelectionAllowed(false);
table.setBorder(BorderFactory.createEtchedBorder());
table.setRowHeight(20);
table.setVisible(true);
gBC.gridx = 0;
gBC.gridy = 1;
gBC.gridwidth = 3;
dialog.add(js, gBC);
/******************************JButton for SimpRepCreation***************************************/
gBC.gridx = 0;
gBC.gridy = 4;
gBC.gridwidth = 3;
BtnsimpRep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
boolean allFilesConverted = false;
}
});
dialog.add(BtnsimpRep, gBC);
}
public GUI() {
// JDialog.setDefaultLookAndFeelDecorated(true);
dialog = new JPanel();
// Set up the content pane.
addComponentsToPane();
dialog.setSize(dialog.getPreferredSize());
adlg = new AboutDialog(dialog);
}
/*****************************file choosing method********************************************/
private String fileChooserMethod() {
JFileChooser fileChooser = new JFileChooser(".");
FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV files", "csv");
fileChooser.setFileFilter(filter);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int retVal = fileChooser.showDialog(dialog, "Select File");
if (retVal == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().getPath();
} else {
return null;
}
}
public static Object gettable (String csvPath){
try {
BufferedReader br = new BufferedReader(new FileReader(new File(csvPath)));
ArrayList <String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
Object[][] content = new Object[elements.size()][2];
for(int i=0; i<elements.size(); i++) {
content[i][0] = elements.get(i)[0].trim();
content[i][1] = elements.get(i)[1].trim();
//content[i][2] = elements.get(i)[2].trim();
//content[i][3] = elements.get(i)[3].trim();
}
return content;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
new GUI();
}
}
Thanks Regards,
Dinesh
Do you need to set the combo box in a specific cell?
You can set a cell renderer which uses a JCombobox. Similar to this:
http://www.java2s.com/Tutorial/Java/0240__Swing/UsingaJComboBoxinaCellinaJTableComponent.htm
got a problem here, trying to create a login to database system at the moment. I have to classes : UserLogManagerMainWindow and DatabaseConnectionFrame. My program is about log management. I want to make a database connection :
UserLogManagerMainWindow class has a button "Connect to database", on it's click DatabaseConnectionFrame initialize and gets up a frame with jlabels and jtextfields, after I enter everything i need, i press "Login" button, after this I want that my UserLogManagerMainWindow class continues on pressenting the logs from connected database.
I have written some code about how it supposed to look : "the logic about what am i trying to say"
connectToDatabaseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
DatabaseConnectionFrame dcf = new DatabaseConnectionFrame();
dcf.setVisible(true);
if(dcf.answer == true) {
importButtons(menuBar);
setJMenuBar(menuBar);
try {
DatabaseComm.getColumnNamesToPanel(model, titles);
projects = DatabaseComm.AddLogsToArrayReturnProjectNames(events);
DatabaseComm.fillDataToPanel(model, events, titles, row);
DatabaseComm.resizeColumnWidth(table);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else {
System.out.println("not working");
}
}
});
But if statement does not working, i know why. That's why i'm asking how to make it work? More likely, threading is the key, but not good at it at the moment. Any tips without threading? And if threading is the only way, may i get some help of it?
Giving DatabaseConnectionFrame class below either:
package manager;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class DatabaseConnectionFrame extends JFrame{
private JPanel contentPane;
private JTextField address;
private JPasswordField password;
private JTextField username;
private JButton btnLogin;
private JButton btnCancel;
private JLabel lblPort;
private JTextField port;
public boolean answer = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DatabaseConnectionFrame frame = new DatabaseConnectionFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DatabaseConnectionFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(450,250);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
JLabel lblDatabaseIpAddress = new JLabel("Database ip address:");
GridBagConstraints gbc_lblDatabaseIpAddress = new GridBagConstraints();
gbc_lblDatabaseIpAddress.anchor = GridBagConstraints.EAST;
gbc_lblDatabaseIpAddress.insets = new Insets(0, 0, 5, 5);
gbc_lblDatabaseIpAddress.gridx = 0;
gbc_lblDatabaseIpAddress.gridy = 0;
contentPane.add(lblDatabaseIpAddress, gbc_lblDatabaseIpAddress);
address = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
contentPane.add(address, gbc_textField);
address.setColumns(10);
lblPort = new JLabel("Port");
GridBagConstraints gbc_lblPort = new GridBagConstraints();
gbc_lblPort.anchor = GridBagConstraints.EAST;
gbc_lblPort.insets = new Insets(0, 0, 5, 5);
gbc_lblPort.gridx = 0;
gbc_lblPort.gridy = 1;
contentPane.add(lblPort, gbc_lblPort);
port = new JTextField();
GridBagConstraints gbc_textField1 = new GridBagConstraints();
gbc_textField1.insets = new Insets(0, 0, 5, 0);
gbc_textField1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField1.gridx = 1;
gbc_textField1.gridy = 1;
contentPane.add(port, gbc_textField1);
port.setColumns(10);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_lblUsername = new GridBagConstraints();
gbc_lblUsername.anchor = GridBagConstraints.EAST;
gbc_lblUsername.insets = new Insets(0, 0, 5, 5);
gbc_lblUsername.gridx = 0;
gbc_lblUsername.gridy = 2;
contentPane.add(lblUsername, gbc_lblUsername);
username = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.insets = new Insets(0, 0, 5, 0);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 1;
gbc_textField_1.gridy = 2;
contentPane.add(username, gbc_textField_1);
username.setColumns(10);
JLabel lblPassword = new JLabel("Password");
GridBagConstraints gbc_lblPassword = new GridBagConstraints();
gbc_lblPassword.anchor = GridBagConstraints.EAST;
gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
gbc_lblPassword.gridx = 0;
gbc_lblPassword.gridy = 3;
contentPane.add(lblPassword, gbc_lblPassword);
password = new JPasswordField();
GridBagConstraints gbc_passwordField = new GridBagConstraints();
gbc_passwordField.insets = new Insets(0, 0, 5, 0);
gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
gbc_passwordField.gridx = 1;
gbc_passwordField.gridy = 3;
contentPane.add(password, gbc_passwordField);
btnLogin = new JButton("Login");
GridBagConstraints gbc_btnLogin = new GridBagConstraints();
gbc_btnLogin.insets = new Insets(0, 0, 0, 5);
gbc_btnLogin.gridx = 0;
gbc_btnLogin.gridy = 4;
contentPane.add(btnLogin, gbc_btnLogin);
btnCancel = new JButton("Cancel");
GridBagConstraints gbc_btnCancel = new GridBagConstraints();
gbc_btnCancel.gridx = 1;
gbc_btnCancel.gridy = 4;
contentPane.add(btnCancel, gbc_btnCancel);
btnCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String dbAddress = address.getText();
String dbPort = port.getText();
String dbUsername = username.getText();
char[] dbPassword = password.getPassword();
if( dbAddress.isEmpty() || dbPort.isEmpty() || dbUsername.isEmpty() || dbPassword.length == 0) {
JOptionPane.showMessageDialog(getParent(),
"All fields have to be filled!");
}
else {
if(databaseValidation(dbAddress, dbPort, dbUsername, dbPassword)) {
JOptionPane.showMessageDialog(getParent(),
"Connected!");
answer = true;
setVisible(false);
}
else {
JOptionPane.showMessageDialog(getParent(),
"There was error connecting to the database!");
answer = false;
}
}
System.out.println(answer);
}
});
}
public boolean databaseValidation(String address, String port, String username, char[] password) {
String pw = String.valueOf(password);
System.out.println(pw);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port + "/logctrl?user=" + username + "&password=" + pw );
} catch (SQLException e) {
System.out.println("Error connecting to database!");
return false;
}
System.out.println("Connected");
return true;
}
}
If you want to wait for the user input, you have two choices, you either make your own observer pattern which can be called at some point in the future when the state changes in some way or you use a dialog, which will block the codes execution at the point the dialog is made visible and will wait till it's closed
See How to use dialogs for details
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Show the dialog");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(TestPane.this), "I'm in charge now", true);
JButton btn = new JButton("Waiting");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(btn);
dialog.pack();
dialog.setLocationRelativeTo(TestPane.this);
dialog.setVisible(true);
JOptionPane.showMessageDialog(TestPane.this, "You won't see this till the dialog is closed");
}
});
}
}
}
Im trying to filter my Jtabke using my Jcomboox but i cant do it and in the :
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting
it only says how to filter using search txt field or sort using headers but not how to use a JComboBox change event to filter a JTable is there a simple code to do this??
EDITED
GOT iT WORKING
This is my Code:
public class Sql extends JFrame{
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"fecha","clave_pdv","pdv","turno","clave_platillo","platillo","precio","total sin iva"});
public TableRowSorter<DefaultTableModel> sorter;
Connection conn = null;
Connection conn1 = null;
Statement st = null;
Statement st1 = null;
ResultSet rs = null;
ResultSet rs1 = null;
//Create list of values
private final JComboBox comboBox = new JComboBox();
private final JComboBox comboBox_1 = new JComboBox();
private JTextField textField;
public Sql(){
table.setAutoCreateRowSorter(true);
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
st = conn.createStatement();
rs= st.executeQuery("SELECT DISTINCT Nombre_Pdv FROM VENTA_PLATILLOS");
while(rs.next()){
comboBox.addItem(rs.getString(1));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn1 = DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
st1 = conn.createStatement();
rs1 = st1.executeQuery("SELECT DISTINCT Nombre_Turno FROM VENTA_PLATILLOS");
while(rs1.next()){
comboBox_1.addItem(rs1.getString(1));
}
}
catch(Exception e){
e.printStackTrace();
}
getContentPane().setLayout(null);
table.setModel(model);
table.setBounds(50, 50, 50, 50);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(139, 88, 535, 227);
getContentPane().add(scrollPane);
comboBox.setBounds(404, 11, 130, 31);
getContentPane().add(comboBox);
comboBox_1.setBounds(544, 11, 130, 31);
getContentPane().add(comboBox_1);
textField = new JTextField();
textField.setBounds(24, 16, 86, 20);
getContentPane().add(textField);
textField.setColumns(10);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 2);
sorter.setRowFilter(rf);
}
});
comboBox_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox_1.getSelectedItem().toString(), 3);
sorter.setRowFilter(rf);
}
});
sorter = new TableRowSorter<DefaultTableModel>(model);
table.setRowSorter(sorter);
//Populate table
sqlConection bd = new sqlConection();
List<Value> values = bd.selectAll();
for(Value v : values){
model.addRow(new Object[]{v.fecha,v.clave_pdv,v.pdv,v.turno,v.clave_platillo,v.platillo,v.precio,v.total});
}
}
Try this, using a TableRowSorter, fill the table with some numbers and filter it ...
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class TableFilter extends JFrame {
private JTable table;
private DefaultTableModel model;
private TableRowSorter<DefaultTableModel> sorter;
public TableFilter() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
pack();
setVisible(true);
}
public static void main(String args[]) {
new TableFilter();
}
private void initComponents() {
JPanel panel = new JPanel();
final JComboBox<String> comboBox = new JComboBox<>(new String[]{"","1","2","3"});
JButton button = new JButton("filter");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 0);
sorter.setRowFilter(rf);
}
});
panel.add(comboBox);
panel.add(button);
table = new JTable(model = new DefaultTableModel(3,3));
sorter = new TableRowSorter<DefaultTableModel>(model);
table.setRowSorter(sorter);
add(panel,BorderLayout.SOUTH);
add(new JScrollPane(table));
}
}
Fill the table with some numbers
filter it
MainFrame.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
public class MainFrame extends JFrame{
private TextPanel textPanel1;
private TextPanel textPanel2;
private FormPanel formPanel;
private JSplitPane splitPane;
private JTabbedPane tabPane;
public MainFrame() {
super("Hello");
setLayout(new BorderLayout());
tabPane = new JTabbedPane();
textPanel1 = new TextPanel();
tabPane.addTab("Tab 1", textPanel1);
textPanel2 = new TextPanel();
tabPane.addTab("Tab 2", textPanel2);
//Newly Added code
formPanel = new FormPanel(textPanel1,textPanel2);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,formPanel,tabPane);
splitPane.setOneTouchExpandable(true);
add(splitPane,BorderLayout.CENTER);
// add(formPanel,BorderLayout.WEST);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(500, 400));
setSize(600, 500);
}
}
TextPanel.java
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Scrollbar;
import java.io.ByteArrayOutputStream;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
public class TextPanel extends JPanel {
private JTextArea textArea1;
private JTextArea textArea2;
private FormPanel formPanel;
//Newly added code
private TextPanel textPanel;
public TextPanel(){
setLayout(new BorderLayout());
textArea1 = new JTextArea();
add(new JScrollPane(textArea1),BorderLayout.CENTER);
//textArea2 = new JTextArea();
//add(new JScrollPane(textArea2),BorderLayout.CENTER);
}
//Newly added code
public void appendText(String string, TextPanel textPanel2) {
// TODO Auto-generated method stub
this.textPanel = textPanel2;
textArea1.append(string);
}
}
FormPanel.java
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.ObjectInputStream.GetField;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class FormPanel extends JPanel {
private static int numberOfTabs = 1;
private JLabel serverName_1;
private JLabel serverName_2;
private JButton startServer_1;
private JButton startServer_2;
//Added New Code
private TextPanel textPanel1;
private TextPanel textPanel2;
JumpHosts jumpHosts = new JumpHosts();
//Added New Code
public FormPanel(final TextPanel textPanel1,final TextPanel textPanel2){
Dimension dim = getPreferredSize();
dim.width = 350;
setPreferredSize(dim);
setMinimumSize(dim);
//Added New Code
this.textPanel = textPanel1;
this.textPanel = textPanel2;
serverName_1 = new JLabel("server1 ");
startServer_1 = new JButton("Start");
serverName_2 = new JLabel("server2 ");
startServer_2 = new JButton("Start");
startServer_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] ev = new String[]{"username#10.10.10.10","username#server1"};
String cmd = "ls -ltr";
//jumpHosts.JumpHosts(ev,cmd);
//Newly added code
jumpHosts.JumpHosts(ev,cmd,textPanel1);
}
});
startServer_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] ev = new String[]{"username#10.10.10.10","username#server2"};
String cmd = "ls -ltr";
//jumpHosts.JumpHosts(ev,cmd);
//Newly added code
jumpHosts.JumpHosts(ev,cmd,textPanel2);
}
});
Border innerborder = BorderFactory.createTitledBorder("Detail");
Border outerborder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
setBorder(BorderFactory.createCompoundBorder(outerborder, innerborder));
layoutComponents();
}
public void layoutComponents(){
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
//////////// First row ////////////
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 0.01;
gc.gridx = 0;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(serverName_1,gc);
/////////// Next Column ////////////
gc.gridy = 0;
gc.weightx = 2;
gc.weighty = 0.01;
gc.gridx = 2;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(startServer_1,gc);
//////////// Second row ////////////
gc.gridy++;
gc.weightx = 1;
gc.weighty = 0.1;
gc.gridx = 0;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(serverName_2,gc);
/////////// Next Column ////////////
//gc.gridy = 1;
gc.weightx = 2;
gc.weighty = 0.1;
gc.gridx = 2;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(startServer_2,gc);
}
}
JumpHosts.java
import com.jcraft.jsch.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.*;
public class JumpHosts {
TextPanel textPanel = new TextPanel();
//Newly added code
public void JumpHosts(final String[] arg,final String command,final TextPanel textPanel) {
StringBuffer resultDisplayBuffer = new StringBuffer();
SwingWorker sw = new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
try{
JSch jsch = new JSch();
if(arg.length <= 1){
System.out.println("This program expects more arguments.");
System.exit(-1);
}
Session session = null;
Session[] sessions = new Session[arg.length];
String host = arg[0];
String user = host.substring(0, host.indexOf('#'));
host = host.substring(host.indexOf('#')+1);
sessions[0] = session = jsch.getSession(user, host, 22);
session.setUserInfo(new MyUserInfo());
session.connect();
//textPanel.appendText("The session has been established to "+user+"#"+host+"\n");
//Newly added code
textPanel.appendText("The session has been established to "+user+"#"+host+"\n",textPanel);
for(int i = 1; i < arg.length; i++){
host = arg[i];
user = host.substring(0, host.indexOf('#'));
host = host.substring(host.indexOf('#')+1);
int assinged_port = session.setPortForwardingL(0, host, 22);
textPanel.appendText("portforwarding: "+
"localhost:"+assinged_port+" -> "+host+":"+22+"\n");
sessions[i] = session =
jsch.getSession(user, "localhost", assinged_port);
session.setUserInfo(new MyUserInfo());
session.setHostKeyAlias(host);
session.connect();
textPanel.appendText("The session has been established to "+
user+"#"+host+"\n");
}
String sudo_pass;
{
JTextField passwordField=(JTextField)new JPasswordField(8);
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null,
ob,
"Enter password for sudo",
JOptionPane.OK_CANCEL_OPTION);
if(result!=JOptionPane.OK_OPTION){
System.exit(-1);
}
sudo_pass=passwordField.getText();
}
Channel channel=session.openChannel("exec");
// man sudo
// -S The -S (stdin) option causes sudo to read the password from the
// standard input instead of the terminal device.
// -p The -p (prompt) option allows you to override the default
// password prompt and use a custom one.
((ChannelExec)channel).setCommand("sudo -S -p '' "+command);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass + "\n").getBytes());
out.flush();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
textPanel.appendText(new String(tmp,0,i));
}
if (channel.isClosed()) {
textPanel.appendText(new String("exit-status: " + channel.getExitStatus())+ "\n");
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee);
}
}
channel.disconnect();
textPanel.appendText("Disconnect\n\n");
for(int i = sessions.length-1; i >= 0; i--){
sessions[i].disconnect();
}
}
catch(Exception e){
System.out.println(e);
}
return null;
}
public void done(){
try {
System.out.println(get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
sw.execute();
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
so whenever I am clicking on any button the output gets redirected to only one textarea whereas other seems to be no usable. i.e to the last created tab.
I want that when I am clicking on button 1 then it should write to tab 1 and when I am clicking on button 2 then it should write to tab 2 and so on.
Examples appreciated as I am new to java
In JumpHosts:
TextPanel textPanel = new TextPanel();
you create an instance of TextPanel which is referenced by no other object in the program. This is not either of the TextPanels you created in MainFrame.
You need to pass the TextPanels created in MainFrame, namely:
private TextPanel textPanel;
private TextPanel textPanel2;
into your JumpHosts constructor:
JumpHosts(TextPanel textPanel1, TextPanel textPanel2)
to be able to reference the same TextPanel as MainFrame does.
Response to Followup:
You will need to pass your TextPanel first to your FormPanel constructor from within your MainFrame constructor. You will then need to modify your FormPanel contructor to pass the TextPanel to your JumpHosts constructor.
Currently my code will not run because I have no main, but when I make a main it must be static, and I am under the impression I shouldn't be making all of my variables for the Swing elements Static, as per the advice of many.
I'm not sure how to invoke the methods without using main as the constructor, currently my gui does not appear.
Thanks.
package movieinfo;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.commons.io.FileUtils;
public class Swinggui {
JButton enter;
public JTextField movietext;
JList listofmovies;// converts moviestowatch into gui
// element.
File textfilemovie; // file which movies marked for watching
// are saved
java.util.List<String> moviestowatch; // arraylist which is
// populated by
// textfilemovie
// than printed to
// GUI element
ListSelectionListener setSearch;
JButton add;
String info;
public Swinggui() throws IOException {
yourMovies();
gui();
jsonAndButtons();
}
public void gui() {
JFrame maingui = new JFrame("Gui");
maingui.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
enter = new JButton("Get Info");
c.gridx = 2;
c.gridy = 1;
maingui.add(enter, c);
add = new JButton("add");
c.gridx = 5;
c.gridy = 6;
maingui.add(add, c);
JTextArea movieinfo = new JTextArea(info, 5, 20);
movieinfo.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2,
Color.red));
movietext = new JTextField(18);
c.gridx = 1;
c.gridy = 1;
maingui.add(movietext, c);
final JScrollPane scrolll = new JScrollPane(movieinfo);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 2;
maingui.add(scrolll, c);
final JLabel titlee = new JLabel("Enter movie name below!");
c.gridx = 1;
c.gridy = 0;
maingui.add(titlee, c);
c.gridx = 1;
c.gridy = 3;
maingui.add(titlee, c);
final JLabel watchlist = new JLabel("Watchlist");
c.gridx = 5;
c.gridy = 1;
maingui.add(watchlist, c);
maingui.setResizable(false);
maingui.setVisible(true);
listofmovies = new JList(moviestowatch.toArray());
c.gridx = 4;
c.gridy = 3;
maingui.add(new JScrollPane(listofmovies), c);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
scrolll.getPreferredSize();
listofmovies.addListSelectionListener(setSearch);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
}
public void jsonAndButtons() {
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(apicall.getMovieInfo(movietext.getText()
.replaceAll(" ", "%20")));
info = apicall.getMovieInfo(movietext.getText().replaceAll(" ",
"%20"));
}
});
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
FileUtils.writeStringToFile(new File(
org.apache.commons.io.FileUtils.getUserDirectory()
+ "/yourmovies.txt"),
"\n" + movietext.getText(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
moviestowatch = FileUtils.readLines(textfilemovie);
listofmovies = new JList(moviestowatch.toArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void yourMovies() throws IOException {
textfilemovie = new File(
org.apache.commons.io.FileUtils.getUserDirectory()
+ "/yourmovies.txt");
textfilemovie.createNewFile();
moviestowatch = FileUtils.readLines(textfilemovie);
setSearch = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
info = apicall.getMovieInfo(((String) listofmovies
.getSelectedValue()).replaceAll(" ", "%20"));
}
};
}
}
Firstly, don't keep everything in one class. Create some other class and then create object of that type, and invoke its methods, it would look like this in your main() method:
MyClass myClass = new MyClass();
myClass.doStuff();
inside your main put:
new Swinggui();
This will pull you out of the static context and bring you into the non-static Swinggui constructor
Make your class Swinggui extend JFrame.
Then create a main method and create object of Swinggui
Swinggui gui = new Swinggui();
now you must make gui visible, for this write.
gui.setVisible(true);
And you are good to go.
Refer everything in code using "this" and you would have non static items.