connection problem(JTextfield, Jtable, sql database) - java

i'm junho who is stuying JAVA, SQL.
Now i'm struggling with this below problem.
firstly, when i tried to put 20020202 in this field, it occurred error about unexpected datatype. However, i don't know how to change number to 'Date'
Secondly, i don't know how to make JTable method to input into this below part.
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
because if i dont put the below code,
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table1 = new JTable(model);
table1.setColumnSelectionAllowed(true);
table1.setCellSelectionEnabled(true);
JScrollPane scrollPane = new JScrollPane(table1);
scrollPane.setBounds(10, 53, 600, 200);
addGrid(gbl,gbc,scrollPane,0,4,2,3,0,0);
the table doesn't show up.
So, i m wondering how to fix this problem.
my writing skill for english is not good. So, it is not going to be enough info for you.
i wish someone gives advice for me.
this is whole code that i wrote.
i hope it will help you to understand what i am struggling with.
thank you so much.
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class DbPanel extends JPanel{
public DbPanel() {
Vector columnNames = new Vector();
Vector data = new Vector();
JPanel panel = new JPanel(); //
JPanel panel2 =new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
setLayout(gbl);
//DB 관리
/* String url = "jdbc:oracle:thin:#localhost:1521:xe";
String user = "madang";
String password = "madang";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url, user, password);
String sql = "select * from STOCK_INFO order by DATE_STOCK";
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
statement.close();
} catch (Exception e) {
System.out.println(e);
}*/
//DB 끝
JLabel label = new JLabel("start_date");
addGrid(gbl,gbc,label,0,0,1,1,0,0);
JTextField textfield = new JTextField(8);
addGrid(gbl,gbc,textfield,0,1,1,1,0,0);
JLabel label2 = new JLabel("end_date");
addGrid(gbl,gbc,label2, 2,0,1,1,0,0);
JTextField textfield2 = new JTextField(8);
addGrid(gbl,gbc,textfield2, 2,1,1,1,0,0);
JButton btn = new JButton("search");
addGrid(gbl, gbc, btn, 2, 4, 1, 3, 0, 0);
JLabel lblNewLabel = new JLabel("Stock_database");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
/* lblNewLabel.setBounds(10, 11, 927, 31);*/
addGrid(gbl,gbc,lblNewLabel,0,3,4,1,1,0);
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table1 = new JTable(model);
table1.setColumnSelectionAllowed(true);
table1.setCellSelectionEnabled(true);
JScrollPane scrollPane = new JScrollPane(table1);
scrollPane.setBounds(10, 53, 600, 200);
addGrid(gbl,gbc,scrollPane,0,4,2,3,0,0);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String url = "jdbc:oracle:thin:#localhost:1521:xe";
String user = "madang";
String password = "madang";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url, user, password);
String sql = "select * from stock_info between"+textfield.getText()+"and"+textfield2.getText();
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
statement.close();
} catch (Exception e1) {
System.out.println(e1);
}
}
});
/* TableColumn column;
for (int i = 0; i < table1.getColumnCount(); i++) {
column = table1.getColumnModel().getColumn(i);
column.setMaxWidth(250);
}*/
}
private void addGrid(GridBagLayout gbl, GridBagConstraints gbc, Component c, int gridx, int gridy, int gridwidth, int gridheight, int weightx, int weighty) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbl.setConstraints(c, gbc);
add(c);
}
}

firstly, when i tried to put 20020202 in this field, it occurred error about unexpected datatype. However, i don't know how to change number to 'Date'
Parse the String date into year, month and day values. Then you can create a Calendar
object:
Calendar date = new Calendar(...);
Once you have the Calendar object you can create your SQLDate using:
Date sqlDate = new Date( date.getTimeInMillis() );
Note you should use the java.sql.Date class, not the java.util.Date class.
the table doesn't show up.
The table doesn't show up because the columns are empty when the model is created. You need to create the model once you have the valid data.
So the code should be something like:
//DefaultTableModel model = new DefaultTableModel(data, columnNames);
//JTable table1 = new JTable(model);
JTable table1 = new JTable(); // create empty table to add to scroll pane
Then after you get the data from the ResultSet you can create the model and assign it to the table:
resultSet.close();
statement.close();
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table1.setModel( model );

Related

How to create JOptionPane with multiple list selections and extract all the choices?

I am interested in creating a JOptionPane or any interactable pop-up Pane that contains multiple list selections. I also wish to extract the selections the user made.
The code below shows an MRE where I generate two different JOptionPanes with list selections and extract the choice from each. Essentially, I am trying to combine the two.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class JOptionPaneTest {
public static void main(String[] a) {
JFrame frame = new JFrame();
String bigList[] = new String[30];
String smallList[] = new String[5];
for (int i = 0; i < bigList.length; i++) {
bigList[i] = Integer.toString(i);
}
for (int i = 0; i < smallList.length; i++) {
smallList[i] = Integer.toString(i);
}
String choice = (String) JOptionPane.showInputDialog(frame, "Pick the first number", "Number 1", JOptionPane.QUESTION_MESSAGE,
null, bigList, "Titan");
String choice2 = (String) JOptionPane.showInputDialog(frame, "Pick the second number", "Number 2", JOptionPane.QUESTION_MESSAGE,
null, smallList, "Titan");
System.out.println(choice);
System.out.println(choice2);
}
}
What one of them looks like:
JOptionPane is actually very flexible. You could build a container containing any number of components and then use JOptionPane to display it, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
String bigList[] = new String[30];
String smallList[] = new String[5];
for (int i = 0; i < bigList.length; i++) {
bigList[i] = Integer.toString(i);
}
for (int i = 0; i < smallList.length; i++) {
smallList[i] = Integer.toString(i);
}
JComboBox<String> bigListComboBox = new JComboBox<>(new DefaultComboBoxModel<String>(bigList));
JComboBox<String> smallListComboBox = new JComboBox<>(new DefaultComboBoxModel<String>(smallList));
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(4, 4, 4, 4);
panel.add(new JLabel("Pick the first number"), gbc);
gbc.gridy++;
panel.add(new JLabel("Pick the second number"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(bigListComboBox, gbc);
gbc.gridy++;
panel.add(smallListComboBox, gbc);
JOptionPane.showMessageDialog(null, panel, "Pick two numbers", JOptionPane.QUESTION_MESSAGE);
System.out.println("First number = " + bigListComboBox.getSelectedItem());
System.out.println("Second number = " + smallListComboBox.getSelectedItem());
}
});
}
}

found raw type: JComboBox and cannot find symbol Class.forName

I connect my dosen.java with my Test5.java, I trying to make panel for Teacher to insert our score. but I make it simple like if teacher want to insert score he just need to find the the class and the subject come out from mapel combobox and insert the grade on the textfield in the bottom. when I put combobox in there I got error like raw type combobox and then my jtable got problem too.
UPDATE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.table.*;
import java.util.*;
import javax.swing.DefaultComboBoxModel;
public class dosen{
JPanel panel_dosen, panel_combo, panel_input;
JTable table;
JLabel label_input,label_input2;
JTextField tf_input,tf_input2;
JButton Insert;
JComboBox<String> classs, mapel; //first Problem
ResultSet rs;
JScrollPane scroll;
Connection conn = null;
Statement stmt = null;
String sql;
public dosen(){
table();
dataInsert();
panel_dosen = new JPanel();
panel_dosen.setLayout(new BorderLayout());
panel_dosen.add(panel_combo, BorderLayout.NORTH);
panel_dosen.add(scroll, BorderLayout.CENTER);
panel_dosen.add(panel_input, BorderLayout.SOUTH);
}
public void panelCombo(){ //combobox panel
panel_combo = new JPanel();
DefaultComboBoxModel classes = new DefaultComboBoxModel(new String[]{"Information System", "Hospitality", "Law", "Management", "Accounting"});
classs = new JComboBox(classes);
mapel = new JComboBox();
classs.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
if ("Information System".equals(classs.getSelectedItem())){
DefaultComboBoxModel ISsub = new DefaultComboBoxModel(new String[]{"Statistic and Probability", "Operating System", "Management Information System", "Inggris-2", "Object Oriented Programming"});
mapel.setModel(ISsub);
} else {
DefaultComboBoxModel Hossub = new DefaultComboBoxModel(new String[]{"Statistic and Probability", "Operating System", "Management Information System", "Inggris-2", "Object Oriented Programming1"});
mapel.setModel(Hossub);
}
}
});
classs.setSelectedIndex(0);
mapel.setSelectedIndex(0);
panel_combo.add(classs);
panel_combo.add(mapel);
}
public void table(){//i dont put panel on table because i dont think it needed
table = new JTable();
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
DefaultTableModel model = new DefaultTableModel();
String[] columnNames= {"NIM","Grade","Class"};
model.setColumnIdentifiers(columnNames);
table.setModel(model);
String Classes = "";
String Grade = "";
String NIM = "";
String url = "jdbc:mysql://localhost/kampus";
String username = "root";
String password = "abc";
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
sql = "select NIM, Grade, Class from nilai where Mapel = '"+ mapel.getSelectedItem() +"' AND Major = '" + classs.getSelectedItem() +"'";
PreparedStatement ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
NIM = rs.getString("NIM");
Classes = rs.getString("Kelas");
Grade = rs.getString("Nilai");
model.addRow(new Object[]{NIM, Grade, Classes});
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void dataInsert(){
panel_input = new JPanel();
panel_input.setLayout(new GridBagLayout());
label_input = new JLabel("NIM : ");
label_input2 = new JLabel("Nilai : ");
tf_input = new JTextField(15);
tf_input2 = new JTextField(15);
Insert = new JButton("Insert");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.LINE_START;
panel_input.add(label_input, gbc);
gbc.gridy++;
panel_input.add(label_input2, gbc);
gbc.gridy = 0;
gbc.gridx++;
gbc.anchor = GridBagConstraints.LINE_END;
panel_input.add(tf_input, gbc);
gbc.gridy++;
panel_input.add(tf_input2, gbc);
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel_input.add(Insert, gbc);
}
}
problem
dosen.java:31: warning: [rawtypes] found raw type: DefaultComboBoxModel
DefaultComboBoxModel classes = new DefaultComboBoxModel(new String[]{"Information System", "Hospitality", "Law", "Management", "Accounting"});
^
missing type arguments for generic class DefaultComboBoxModel<E>
where E is a type-variable:
E extends Object declared in class DefaultComboBoxModel
String Class = ""; Change this variable's name. Because of this line
Class.forName("com.mysql.jdbc.Driver");
forName method calling from a String instance. Bu there is not a method named forName in String.

I want to update table when Button is clicked

I am newbie of Swing.
I want to update table after click button (done button).
I think data correct but the screen does not work.
The followings are explanation of my program
check checkBoxes and the click Done button
the bottom layer should change.
there is no main
This is my code:
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui extends JFrame {
class Table extends JTable{
public Table(DefaultTableModel model) {
super(model);
}
public Class getColumnClass(int column) {
switch (column) {
case 1:
return Boolean.class;
default:
return String.class;
}
}
}
private final int BANDNUM = 43;
int[] checkBands;
Object[][] data;
Table table;
JScrollPane upperScrollpane;
JScrollPane downScrollPane;
JSplitPane splitPane;
public Gui() {
// BASE SETTING
setSize(900, 800);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout(5, 5));
JPanel northPanel = new JPanel(new MigLayout());
// northPanel SETTING
JLabel labelIp = new JLabel("IP");
JTextField tFIp = new JTextField(20);
JLabel labelMask = new JLabel("Subnet Mask");
JTextField tFMask = new JTextField(20);
JLabel labelPing = new JLabel("Ping");
JTextField tFPing = new JTextField(10);
JButton btnReady = new JButton("Ready");
JLabel labelReady = new JLabel("NOT READY");
northPanel.add(labelIp);
northPanel.add(tFIp);
northPanel.add(labelMask);
northPanel.add(tFMask);
northPanel.add(labelPing);
northPanel.add(tFPing);
northPanel.add(btnReady);
northPanel.add(labelReady, "wrap");
// upper scrollpane -> will be included in JsplitPane Upper Side
JPanel checkPanel = new JPanel(new MigLayout());
JCheckBox[] checkBoxes = new JCheckBox[BANDNUM];
JButton doneButton = new JButton("DONE");
for (int i = 0; i < BANDNUM; i++) {
checkBoxes[i] = new JCheckBox("" + (i + 1));
checkBoxes[i].setHorizontalTextPosition(SwingConstants.CENTER);
checkBoxes[i].setVerticalTextPosition(SwingConstants.BOTTOM);
if (i == 32) {
checkPanel.add(checkBoxes[i], "wrap");
} else if (i == 42) {
checkPanel.add(checkBoxes[i], "wrap");
} else {
checkPanel.add(checkBoxes[i]);
}
}
checkPanel.add(doneButton, "span 3");
// startButton Action
/////////////////////////////////////////
//I think you should watch from this line!!!
/////////////////////////////////////////
doneButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// 1. CHECK WHAT ARE CLICKED
int length = 0;
for (int i = 0; i < BANDNUM; i++)
if (checkBoxes[i].isSelected())
length++;
checkBands = new int[length];
System.out.println(length);
int k = 0;
for (int i = 0; i < BANDNUM; i++) {
if (checkBoxes[i].isSelected()) {
checkBands[k++] = i + 1;
}
}
// 2. Ready for display
data = new Object[length][6];
for (int i = 0; i < length; i++) {
data[i][0] = checkBands[i];
data[i][1] = true;
data[i][2] = 1;
data[i][3] = 2;
data[i][4] = 3;
data[i][5] = 4;
}
// 3. display
String[] colNames = { "BAND", "Test1", "Test2", "Test3",
"Test4", "Test5" };
DefaultTableModel model = new DefaultTableModel(data, colNames);
table = new Table(model);
setVisible(true);
table.repaint();
downScrollPane.repaint();
splitPane.repaint();
}
});
// down scrollpane -> will be included in JsplitPane down Side
String[] colNames = { "BAND", "Test1", "Test2", "Test3", "Test4",
"Test5" };
Object[][] data = { { null, null, null, null, null, null }};
DefaultTableModel model = new DefaultTableModel(data, colNames);
table = new Table(model);
// include
upperScrollpane = new JScrollPane(checkPanel);
downScrollPane = new JScrollPane(table);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upperScrollpane, downScrollPane);
mainPanel.add(northPanel, BorderLayout.NORTH);
mainPanel.add(splitPane, BorderLayout.CENTER);
getContentPane().add(mainPanel);
setVisible(true);
}
}
Instead of doing this...
String[] colNames = { "BAND", "Test1", "Test2", "Test3",
"Test4", "Test5" };
DefaultTableModel model = new DefaultTableModel(data, colNames);
table = new Table(model);
Simply update the existing model
DefaultTableModel model = (DefaultTableModel)table.getModel();
for (Object[] row : data) {
model.addRow(row);
}
or simply
DefaultTableModel model = (DefaultTableModel)table.getModel();
for (int i = 0; i < length; i++) {
data = new Object[6];
data[0] = checkBands[i];
data[1] = true;
data[2] = 1;
data[3] = 2;
data[4] = 3;
data[5] = 4;
model.addRow(data);
}
This assumes that you want to keep adding new rows to the table. You can also use model.setRowCount(0) to clear the table first and then add new rows to it, if that's what you want to.
Swing works a principle of MVC (Model-View-Controller) which separates the view (the JTable) from the data/model (TableModel), this means that the JTable is not bound to the data and can easily be changed or modified by simply changing or modifying the table's model. This is an important concept to understand, as Swing makes a great deal of use of this methodology

How to open JTable?

I have to program that takes ip Addresses from a file and outputs the country its in onto a JTable. I have no errors but when i click the button the JTable doesn't open up. How do i make the JTable open up?
package org.koushik.javabrains;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import net.webservicex.GeoIP;
import net.webservicex.GeoIPService;
import net.webservicex.GeoIPServiceSoap;
public class IPLocationFinder {
public static void main(String[] args) {
final JFileChooser filechooser = new JFileChooser();
filechooser.setVisible(false);
final JTable jt;
final String[] columns= {"IP address","Country"};
final String[][] data = {{}};
final DefaultTableModel model = new DefaultTableModel(data, columns);
jt = new JTable(model);
jt.setPreferredScrollableViewportSize(new Dimension(450, 60));
jt.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane();
jt.add(jps);
final JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
frame.getContentPane().add(panel, BorderLayout.CENTER);
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton("Start");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,10,10);
panel.add(b1, c);
frame.setBounds(400,150,600,200);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
new IPLocationFinder();
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader("C:/IP Addresses/ip.txt"));
String l;
try {
while ((l = inputStream.readLine()) != null) {
String ipAddress = l;
GeoIPService ipService = new GeoIPService();
GeoIPServiceSoap geoIPServiceSoap = ipService.getGeoIPServiceSoap();
GeoIP geoIp = geoIPServiceSoap.getGeoIP(ipAddress);
model.addRow(new String[][]{{"Column 1", geoIp.getCountryName()}});
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
b1.addActionListener(actionListener);
}
}
You have several problems:
You never add the JTable to your panel.
You're adding a JScrollPane to your JTable when it should be the other way around. The JScrollPane should have its view set to the scrollable component, which in this case is the JTable. Otherwise, as your table's rows increase, the elements above it are simply going to be pushed up.
You've added an empty row to your table by saying final String[][] data = { {} };. When you start adding rows, you'll have a blank row to start. Therefore, you should remove the inner curly braces.
You should be aware that your JTable data is being prescribed as a 2D String array and although you're technically adding the data correctly, it's going to show up as an address in your first column:
To fix the above issue, change your addRow data to a 2D array such as model.addRow(new String[] { "Column 1", "Country 1" });
Below is a simplified, corrected version:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class IPLocationFinder {
public static void main(String[] args) {
final String[] columns = { "IP address", "Country" };
final String[][] data = {};
final DefaultTableModel model = new DefaultTableModel(data, columns);
final JTable jt = new JTable(model);
final JFrame frame = new JFrame();
final JScrollPane jps = new JScrollPane(jt);
final JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton("Start");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
panel.add(b1, c);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.getContentPane().add(jps, BorderLayout.CENTER);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
model.addRow(new String[] { "Column 1", "Country 1" });
}
};
b1.addActionListener(actionListener);
frame.pack();
frame.setVisible(true);
}
}
I'm gessing you're using a panel to show the jtable, however as you can notice, there's no a panel.add(jt); line.
So, go ahead and add that line inside the Action
EDIT
As #Braj comment, the jt must be added to the scroll. Then instead add the JTable, add the JScroll.
panel.add(jsp);

JDBC + Swing: Not able to get table contents

I am learning JDBC, completely new to it. I know MySQL very well. I have a search form in my applet (tab 2), where I search for food. And when I click search, I want it to search for the exact food from the Database and return the table contents of that particular row alone. But I am not getting any result. Only an empty frame opens. But when I put the query as "SELECT * FROM table", I am getting the complete table. But I want only one row, the one that is searched for. Can anyone please tell me where I am going wrong? Here's my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.DriverManager;
import java.util.Vector;
import javax.swing.*;
import com.mysql.jdbc.*;
public class Tryout extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
final Vector columnNames = new Vector();
final Vector data = new Vector();
private JTabbedPane tabbedPane = new JTabbedPane();
private JPanel inputpanel;
private JPanel searchpanel;
public String s;
public Tryout() {
inputpanel = createPage1();
searchpanel = createPage2();
tabbedPane.addTab("Input Form", inputpanel);
tabbedPane.addTab("Search Form", searchpanel);
this.add(tabbedPane, BorderLayout.CENTER);
}
public JPanel createPage1() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Some code
return panel;
}
public JPanel createPage2() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 0.5;
c.weighty = 0.5;
JLabel region = new JLabel("Enter Region");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 0;
c.gridy = 0;
panel.add(region, c);
JTextField field = new JTextField(20);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 1;
c.gridy = 0;
panel.add(field, c);
JButton search = new JButton("SEARCH");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 2;
c.gridy = 0;
panel.add(search, c);
s = field.getText();
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
try{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/delikat", "root", "");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT * FROM delicious WHERE name = ?");
statement.setString(1,s);
ResultSet rs= (ResultSet) statement.executeQuery();
ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
statement.close();
}
catch(Exception e) {}
JFrame tab=new JFrame();
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
tab.add( scrollPane );
tab.setVisible(true);
tab.setSize(300,100);
}
});
return panel;
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Tryout ex = new Tryout();
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex.setSize(500,500);
ex.setVisible(true);
}
});
}
}
Here is my table:
Also, I am trying to display the table in the panel itself below the search form but it gives error when I add
panel.add(scrollpane);
How do I rectify this problem too?
Thanks
What Sudhanshu means is:
PreparedStatement statement = con.preparedStatement("SELECT * FROM delicious WHERE name = ?");
statement.setString(1,s);
ResultSet rs= (ResultSet) statement.executeQuery();
Enclose name is quotes if its of type string (varchar). Better use PreparedStatement in such cases.
Basic debugging. Did you display the value of "s" that is being used in the PreparedStatement?
s = field.getText();
From what I can see, this statement is executed when you build the GUI which means nothing because the user hasn't even entered any text into this text field.
That statement needs to be executed when you actually invoke the SQL.

Categories