How would go about selecting rows from a MySQL database into JTable? - java

I'm still learning java and was wondering how could I implement selecting rows from a MySQL database into a JTable. I've been stuck on this for a day now and am asking for any help. I tried other methods on here but still got stuck. I pasted my code below:
package src;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Random;
import javax.swing.*;
public class FishApp extends JFrame {
FishApp() throws ClassNotFoundException {
//Create the frame
JFrame frame = new JFrame("Fishing Log Application");
//Create label
JLabel tab1Label = new JLabel("Log a fish you caught!", SwingConstants.CENTER);
JLabel tab2Label = new JLabel("This is a directory of all the recorded catches.", SwingConstants.CENTER);
JLabel tab3label = new JLabel("<html>I developed this application in order for fisherman like you and me<br/> to be able to log their catches and note down additional info of their trip. <br/>This application was created by Brendan Dill in 2022. <br/>Any questions or concerns contact here <a href='brdxn.github.io'>here</a></html>", SwingConstants.CENTER);
JLabel speciesLabel = new JLabel("Species: ");
JLabel lengthLabel = new JLabel("Length (inches): ");
JLabel weightLabel = new JLabel("Weight (pounds): ");
JLabel dateLabel = new JLabel("Date caught: ");
JLabel locationLabel = new JLabel("Location caught: ");
JLabel additionalLabel = new JLabel("Additional Info: ");
//Create panel 1
JPanel p1 = new JPanel();
//Create fields for panel 1
JTextField speciesField = new JTextField("common name format",20);
JTextField lengthField = new JTextField(5);
JTextField weightField = new JTextField(6);
JTextField dateField = new JTextField("mm-dd-yyyy format", 10);
JTextField locationField = new JTextField("place, city, state format", 30);
JTextArea additionalField = new JTextArea();
//Get text from field
Random id = new Random();
int fishID = id.nextInt(1000);
//Create log button
JButton logBtn = new JButton("Log catch!");
//Create load button
JButton loadBtn = new JButton("Load catches...");
loadBtn.setBounds(50,50,50,30);
//Create table
/* String data[][]={ {"1","Flounder","21","5","9/18/22","Ocean","Chartruse Bucktail"}};
String column[]={"FishId","Species","Length", "Weight", "Date", "Location", "Additional Info"};
JTable fishTable=new JTable(data,column);
fishTable.setBounds(30,40,200,600);
JScrollPane sp=new JScrollPane(fishTable); */
//Set the layout for panel 1
p1.setLayout(new GridLayout(0,1));
//Add label in panel 1
p1.add(tab1Label);
p1.add(speciesLabel);
p1.add(speciesField);
p1.add(lengthLabel);
p1.add(lengthField);
p1.add(weightLabel);
p1.add(weightField);
p1.add(dateLabel);
p1.add(dateField);
p1.add(locationLabel);
p1.add(locationField);
p1.add(additionalLabel);
p1.add(additionalField);
p1.add(logBtn);
//Create panel 2
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(0,1));
p2.add(tab2Label);
//p2.add(sp);
p2.add(loadBtn);
//Create panel 3
JPanel p3 = new JPanel();
p3.add(tab3label);
//Create the tab container
JTabbedPane tabs = new JTabbedPane();
//Set tab container position
tabs.setBounds(20,20,750,750);
//Associate each panel with the corresponding tab
tabs.add("Log Fish", p1);
tabs.add("Directory", p2);
tabs.add("About", p3);
//Add tabs to the frame
frame.add(tabs);
frame.setSize(800,800);
frame.setLayout(null);
frame.setVisible(true);
//Log catch into database
logBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String species = speciesField.getText();
String length = lengthField.getText();
String weight = weightField.getText();
String date = dateField.getText();
String location = locationField.getText();
String additional = additionalField.getText();
try {Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sys","root","");
// Insert query shouldn't have *
String query = "INSERT INTO `FishEntry` (FishId, Species, Length, Weight, Date, Location, AdditionalInfo) VALUES (?, ?, ?, ?, ?, ?, ?);";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, fishID);
preparedStmt.setString(2, species);
preparedStmt.setString(3, length);
preparedStmt.setString(4, weight);
preparedStmt.setString(5, date);
preparedStmt.setString(6, location);
preparedStmt.setString(7, additional);
preparedStmt.executeUpdate();
}
catch (Exception d) {
System.out.println("Error found "+ d);
}
}
});
//Load Catches from MySQL database
loadBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sys","root","");
String query = "SELECT * FROM FishEntry;";
PreparedStatement preparedStmt = conn.prepareStatement(query);
ResultSet rs = preparedStmt.executeQuery(query);
int i = 0;
String data[][]= new String[8][7];
String column[]={"FishId","Species","Length", "Weight", "Date", "Location", "Additional Info"};
JTable fishTable=new JTable(data,column);
fishTable.setBounds(30,40,200,600);
JScrollPane sp=new JScrollPane(fishTable);
while(rs.next()) {
int fishId2 = rs.getInt("FishId");
String species2 = rs.getString("Species");
String length2 = rs.getString("Length");
String weight2 = rs.getString("Weight");
String date2 = rs.getString("Date");
String location2 = rs.getString("Location");
String additional2 = rs.getString("AdditionalInfo");
data[i][0] = fishId2 + "";
data[i][1] = species2;
data[i][2] = length2;
data[i][3] = weight2;
data[i][4] = date2;
data[i][5] = location2;
data[i][6] = additional2;
i++;
}
p2.add(sp);
}
catch (SQLException | ClassNotFoundException d) {
System.out.println("Error found "+ d);
}
}
});
}
public static void main(String[] args) throws ClassNotFoundException
{
new FishApp();
}
}
Any ideas on how to implement this?
Example of where I want to put the JTable:

Related

Adding JList to show basic DB information

My goal is to put a JList with the data from my DB over the 2 JTextFields, but i dont know how to do it. Do you guys and girls know what the mistake is and how I can fix it?
(The Variable personList has all the Data in it. Just need to put it in JList. But this Variable personList is a ArrayList.)
public class Datenbank2 extends JFrame {
public Datenbank2() {
super("Datenbank der Lehrlinge 1 Lehrjahr");
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel linkesPanel = new JPanel();
this.setBounds(600, 300, 500, 450);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager
.getConnection("jdbc:sqlite:C://Users/N-YP/workspace/UebungJava/ch/nyp/uebungen/datenbanken/SqLiteDB.db");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Person");
ArrayList<JLabel> personList = new ArrayList<JLabel>();
while (rs.next()) {
String vorname = rs.getString("Vorname");
String nachname = rs.getString("Nachname");
personList.add(new JLabel(vorname + " " + nachname));
System.out.println(vorname + " " + nachname);
}
JTextField eingVorname = new JTextField();
JTextField eingNachname = new JTextField();
eingVorname.setPreferredSize(new Dimension(230, 30));
eingNachname.setPreferredSize(new Dimension(230, 30));
BorderLayout borderLayout = new BorderLayout();
this.getContentPane().setLayout(borderLayout);
this.add(centerPanel, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);
centerPanel.add(linkesPanel, BorderLayout.WEST);
FlowLayout flowLayout = new FlowLayout();
centerPanel.setLayout(flowLayout);
for (JLabel personLabel : personList) {
centerPanel.add(personLabel);
}
southPanel.setLayout(flowLayout);
southPanel.add(eingVorname);
southPanel.add(eingNachname);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(0);
System.out
.println("Datenbank geöffnet (muss später aber wieder geschlossen werden).");
}
}
public static void main(String[] args) {
Datenbank2 javamitdb = new Datenbank2();
javamitdb.setVisible(true);
}
}
Thank you and have a nice Day.
Well use DefaultListModel and its addElement() method in your while loop to add each result, like the following:
listModel = new DefaultListModel();
while (rs.next()) {
String vorname = rs.getString("Vorname");
String nachname = rs.getString("Nachname");
listModel.addElement(vorname + " " + nachname);
System.out.println(vorname + " " + nachname);
}
//then create a list with this model
list = new JList(listModel);
Take a look at How to Use Lists for further information.

Cannot show JTable in JFrame

I am trying to show the results of an sql query "SELECT * FROM..." in a JFrame. After a bit of digging I made the below using and some code that I found in another post here. My problem is that it does not show the Jtable in my JFrame. I am complete newbie in this (this is my first try combining sql and java for gui) so any help would be really appreciated...
CODE for frame:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public class Frame extends JFrame {
public Frame() throws HeadlessException {
super();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Border loweredetched = null;
Font font = new Font("monospaced", Font.PLAIN, 11);
JPanel panel = new JPanel(new BorderLayout());
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JPanel lowerPanel = new JPanel();
panel.add(leftPanel, BorderLayout.WEST);
panel.add(rightPanel, BorderLayout.EAST);
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
//JScrollPane scrollPane = new JScrollPane(GetSongs.table);
/*JTextArea text = new JTextArea(15, 3);
text.setMargin(new Insets(5, 5, 5, 5));
text.setBackground(Color.darkGray);
text.setForeground(Color.white);
text.setFont(font);
text.setEditable(false);*/
JButton button = new JButton("Update");
lowerPanel.add(button);
leftPanel.setBorder(BorderFactory.createTitledBorder(loweredetched, "Songs"));
leftPanel. add( new JScrollPane( GetSongs.table ), BorderLayout.CENTER );;
leftPanel.add(lowerPanel);
JTextArea textR = new JTextArea(1, 3);
textR.setMargin(new Insets(5, 5, 5, 5));
textR.setBackground(Color.darkGray);
textR.setForeground(Color.white);
textR.setFont(font);
textR.setEditable(false);
rightPanel.setBorder(BorderFactory.createTitledBorder(loweredetched, "ToBuy"));
rightPanel.add(textR);
getContentPane().add(panel, BorderLayout.NORTH);
pack();
}
public static void main(String[] args){
new Frame();
}
}
CODE of class to connect to db and make query:
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class GetSongs extends JFrame {
// MAKES A QUERY TAKES THE RESULT SET AND PRODUCES A JTABLE
public static JTable table;
public GetSongs() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
String connectionURL = "jdbc:mysql://localhost:3306/songs";
Connection connection = null;
Statement statement = null;
//do not use in production!!
String dbuser = "root";
String dbpass = "";
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance(); //
connection = DriverManager.getConnection(connectionURL, dbuser, dbpass);
statement = connection.createStatement();
String query = "SELECT * FROM songs JOIN purchases WHERE id = song_id and user_id =2;";
rs = statement.executeQuery(query);
table = new JTable(buildTableModel(rs));
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
}
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
System.out.println(columnCount);
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
}
As an alternative, you could use a SwingWorker.
You would retrieve all the database information in the doInBackground() method, and then you would populate your table in the done() method.
Since I can't explain it all to you, there is more information here:
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

Give a layout that suits the components

I'm struggling to give a good layout to my Swing components. Currently FlowLayout being is used, but it doesn't look pretty. My requirement is to display the label l0 in top line. Then the label l1, combobox c1 and button b1 in second column (center aligned). Finally, the output that gets displayed in Jtable beneath. How do I do this?
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search_1 extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table = new JTable();;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
Vector v = new Vector();
JMenuBar menu = new JMenuBar();
r_search_1()
{
frame1 = new JFrame("yippee");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setLayout(new FlowLayout());
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
frame1.add(l0);
frame1.add(l1);
//frame1.add(b1);
frame1.setVisible(true);
frame1.setSize(1000, 400);
try
{
File dbFile = new File("executive_db.accdb");
String path = dbFile.getAbsolutePath();
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
while (rs.next())
{
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setEditable(true);c1.setSelectedItem("");
c1.setBounds(150, 110, 150, 20);
frame1.add(c1);
frame1.add(b1);
st.close();
rs.close();
} catch (Exception e) {
}
// setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData()
{
// frame1 = new JFrame("Database Search Result");
// frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//frame1.setLayout(new FlowLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
String section_name = "";
String report_name = "";
String contact_name = "";
String link = "";
try
{
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
section_name = rs.getString("Section_Name");
report_name = rs.getString("Report_Name");
contact_name = rs.getString("Contact_Name");
link = rs.getString("Link");
model.addRow(new Object[]{section_name, report_name, contact_name, link});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
// frame1.setSize(1000, 400);
//table.close()
}
public static void main(String args[]) {
new r_search_1();
}
}
This is my requirement:
Notes
It is named PoorlySpecifiedLayout because you forgot the part about.. "and (if resizable) with extra width/height."
The UI is naturally taller than seen above. It was shortened to make a better screenshot.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class PoorlySpecifiedLayout {
// the GUI as seen by the user (without frame)
JPanel ui = new JPanel(new BorderLayout(5,5));
String[] comboValues = {
"String to pad combo."
};
String[] tableHeader = {
"Section Name","Report Name","Contact","Link"
};
String[][] tableBody = {{"", "", "", ""}};
PoorlySpecifiedLayout() {
initUI();
}
public final void initUI() {
ui.setBorder(new EmptyBorder(20,20,20,20));
JPanel top = new JPanel(new BorderLayout(15, 5));
ui.add(top, BorderLayout.PAGE_START);
top.add(new JLabel(
"Fetching search results", SwingConstants.CENTER));
JPanel controls = new JPanel(new FlowLayout(SwingConstants.LEADING, 10, 5));
top.add(controls, BorderLayout.PAGE_END);
controls.add(new JLabel("Search:"));
controls.add(new JComboBox(comboValues));
JButton submit = new JButton("submit");
Insets padButton = new Insets(5,20,5,20);
submit.setMargin(padButton);
controls.add(submit);
JTable table = new JTable(tableBody, tableHeader);
ui.add(new JScrollPane(table));
}
public final JComponent getUI(){
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
PoorlySpecifiedLayout psl = new PoorlySpecifiedLayout();
JFrame f = new JFrame("Poorly Specified Layout");
f.add(psl.getUI());
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Edit: as per advice by Andrew Thompson - a picture.
Here is an example of how to do it using BorderLyout for the search / submit row and table, and adding the title in a border title instead of a label:
public class Search extends JFrame {
private final static String TITLE = "Fetching Search Results";
private final static String[] COLUMN_HEADERS = {"Section name", "Report name", "Contact", "Link"};
private final static String[] SEARCH_OPTIONS = {"AAAAA", "BBBBB"};
Search() {
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), TITLE, TitledBorder.CENTER, TitledBorder.TOP, new Font("Arial", Font.PLAIN, 20), Color.RED));
JPanel topPanel = new JPanel();
JLabel searchLabel = new JLabel("Search:");
JComboBox<String> searchBox = new JComboBox<>(SEARCH_OPTIONS);
JButton submitButton = new JButton("Submit");
topPanel.add(searchLabel);
topPanel.add(searchBox);
topPanel.add(submitButton);
JTable table = new JTable(new String[34][4], COLUMN_HEADERS);
mainPanel.add(topPanel, BorderLayout.PAGE_START);
mainPanel.add(new JScrollPane(table));
setContentPane(mainPanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[]) {
new Search();
}
}
If you want the title as a label, you can put another panel for it.

make search result appear in the same page (Swing program)

So, this is a program in swing for implementing a search functionality. It runs perfectly well. No problems there. My requirement is to make the search results appear beneath the same page. In this code, I have made the results to appear in a new Jframe that opens a new window. I basically don't want this. I want to make the search result appear in the same page. So, should I modify the code ? Any form of help is appreciated. :) Thanks !
This is my code:-
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search_1 extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
Vector v = new Vector();
r_search_1()
{
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
setTitle("Search Executive Reports ");
setLayout(null);
//setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(l0);
add(l1);
add(b1);
try
{
File dbFile = new File("executive_db.accdb");
String path = dbFile.getAbsolutePath();
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
while (rs.next())
{
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setEditable(true);c1.setSelectedItem("");
c1.setBounds(150, 110, 150, 20);
add(c1);
st.close();
rs.close();
} catch (Exception e) {
}
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
String section_name = "";
String report_name = "";
String contact_name = "";
String link = "";
try
{
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
section_name = rs.getString("Section_Name");
report_name = rs.getString("Report_Name");
contact_name = rs.getString("Contact_Name");
link = rs.getString("Link");
model.addRow(new Object[]{section_name, report_name, contact_name, link});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(1000, 400);
}
public static void main(String args[]) {
new r_search_1();
}
}
Do not use Null layout. Use a BorderLayout.
All your search functionality should be in the center panel.
add(mySearchPanel, BorderLayout.CENTER);
Your results should be in the south panel. That way it will not shrink the center panel.
add(myResultsPanel, BorderLayout.SOUTH);
If there is nothing in the south panel, then it will shrink away making it seem like it is not there.
So, going into a little more detail, your l0,l1, and b1 components should go into a panel (say myTopPanel), and be added to the center. Your scroll component should be added to the bottom panel.
setTitle("Search Executive Reports ");
setLayout(new BorderLayout());
myTopPanel.add(l0);
myTopPanel.add(l1);
myTopPanel.add(b1);
add(myTopPanel, BorderLayout.CENTER)
add(scroll, BorderLayout.CENTER)

ActionListener not working with all of the objects

I have a problem that when I create a scrollpane with panels in them that are objects I want to add a button to every panel that when I click on it it will return the name of the product and put it in a variable. Problem is that it is only the last object panel in the scrollpane that gets connected to the Action Listener. Here is the code for the scrollpane and individual panels:
try{
System.out.println(sql);
ResultSet rs = data.SQL.executeQuery(sql);
String list = "";
int count=0;
while (rs.next()){
count++;
}
ResultSet result = data.SQL.executeQuery(sql);
ProductDisplayPanel.removeAll();
JPanel addPanel = new JPanel();
addPanel.setLayout(new GridLayout (count, 1));
JScrollPane scroll = new JScrollPane();
while (result.next()) {
searchDisplay = new SearchDisplay (result);
scroll.add(searchDisplay);
addPanel.add(searchDisplay);
}
scroll.setPreferredSize(new Dimension(425,390));
scroll.setViewportView(addPanel);
ProductDisplayPanel.add(scroll);
ProductDisplayPanel.revalidate();
ProductDisplayPanel.repaint();
System.out.println(list);
SearchDisplay.AddToCart.addActionListener(action);
frame.add(SearchDisplay.AddToCart);
} catch (Exception ae){
ae.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
Class that creates the actual panels:
public SearchDisplay(ResultSet result) throws Exception{
setPreferredSize(new Dimension(500, 156));
setVisible(true);
String link = result.getString("image");
System.out.println(link);
BufferedImage icecream = ImageIO.read( new URL( "file:///"+link));
JLabel lblImage = new JLabel(new ImageIcon (icecream));
name = result.getString("Name");
JLabel lblName = new JLabel(name);
String category = result.getString("Pieces");
JLabel lblFlavour = new JLabel("Pieces: "+category);
String productID = result.getString("ProductID");
JLabel lblPrice = new JLabel("Product ID: " + productID);
String price = result.getString("Price");
JLabel lblType = new JLabel("Price: "+ price +" kr");
String age= result.getString("Age");
JLabel lblBrand = new JLabel("Age: "+age);
AddToCart = new JButton("Add to cart");
I'm just not sure how you expected this to work...
You create a series of SearchDisplays and add them to the scroll pane (via the addPanel)
while (result.next()) {
searchDisplay = new SearchDisplay (result);
// nb- Bad idea
scroll.add(searchDisplay);
addPanel.add(searchDisplay);
}
// nb- Worrisome...
scroll.setPreferredSize(new Dimension(425,390));
scroll.setViewportView(addPanel);
Then you seem to add a single ActionListener to the some static object
SearchDisplay.AddToCart.addActionListener(action);
What's the connection? How does this AddToCart button know what it should be adding? Do you set some other static variable in the process??
I would imagin that every instance of SearchDisplay would have it's own AddToCart and it would have it's own ActionListener which knew which item it was associated with...

Categories

Resources