Cannot show JTable in JFrame - java

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

Related

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

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:

How to add or remove a jtable if the GUI is defined in a constructor?

The Problem is that the GUI of the app is defined in the constructor and I'm unable to access the panel or the frame to, either add or delete the jtable. Here's the constructor code:
public FirstSwingApp(){
super();
jbtOK = new JButton("OK");
jbtOK.addActionListener(new BtnPress());
jbtAdd = new JButton("Add");
jbtAdd.addActionListener(new BtnAdd());
jbtView = new JButton("View Table");
jbtView.addActionListener(new BtnView());
lblName = new JLabel("Friend Name");
nameText = new JTextField(20);
lblNo = new JLabel("Friend Number");
noText = new JTextField(4);
lblBdate = new JLabel("Birth date");
bdateText = new JTextField(10);
lblSex = new JLabel("Sex");
sexText = new JTextField(1);
lblState = new JLabel("State");
stateText = new JTextField(20);
lblCity = new JLabel("City");
cityText = new JTextField(20);
panelBtn = new JButton("pbutton");
table = new JTable();
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.LEADING));
panel1.setSize(300,300);
panel1.add(lblName);
panel1.add(nameText);
panel1.add(lblNo);
panel1.add(noText);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.LEADING));
panel2.setSize(300,300);
panel2.add(lblBdate);
panel2.add(bdateText);
panel2.add(lblSex);
panel2.add(sexText);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout(FlowLayout.LEADING));
panel3.setSize(300,300);
panel3.add(lblState);
panel3.add(stateText);
panel3.add(lblCity);
panel3.add(cityText);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(FlowLayout.LEADING));
panel4.setSize(300,300);
panel4.add(jbtAdd);
JPanel panel5 = new JPanel();
panel5.setLayout(new FlowLayout(FlowLayout.LEADING));
panel5.setSize(300,300);
panel5.add(jbtView);
this.add(panel1);
this.add(panel2);
this.add(panel3);
this.add(panel4);
this.add(panel5);
this.setLayout(new FlowLayout(FlowLayout.LEADING));
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100,100,400,250);
this.setTitle("gotta get that swing");
this.setVisible(true);
this.setSize(700,400);
}
Here's the ActionListener Code:
private class BtnView implements ActionListener{
public void actionPerformed(ActionEvent e) {
CallableStatement dstmt = null;
ResultSet rs;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Contact_Manager?user=root");
String disQuery = "select * from FRIEND";
dstmt = conn.prepareCall(disQuery);
rs = dstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
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);
}
// It creates and displays the table
table = new JTable(data, columnNames);
add(new JScrollPane(table));
repaint();
revalidate();
} catch (SQLException ex) {
System.out.println("Error in connection: " + ex.getMessage());
}
}
}
The actionListener class of the button cannot access the panels in the constructor. I've used add() to add the table but I'm not sure if it's the right way. And Even if I've added a table, I cannot delete it when the button is pressed again.
It looks like there are a few things that are currently missing in your code, which prevent the table from updating. As camickr already pointed out, it is not necessary to replace the table component (or even the table model). If you update the model, the table should automatically detect the changes and refresh. Also, the table is currently created, but not added to the frame.
Creating a table with an explicit table model and adding it to the frame could be done like this:
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
JPanel panel6 = new JPanel();
panel6.setLayout(new FlowLayout(FlowLayout.LEADING));
panel6.setSize(300,300);
panel6.add(new JScrollPane(table));
this.add(panel6);
You could pass the tableModel to the BtnView class (for example as a parameter to its constructor) and update the model like this:
tableModel.setDataVector(data, columnNames);

Add button on top of JTable

How to add a Back button on top of JTable ? I tried but no luck.
public class viewMovie extends JPanel{
static JFrame frame = new JFrame("View Movie");
JTable table;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
createAndShowGui();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
static void createAndShowGui() throws Exception {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new viewMovie());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public viewMovie() throws Exception
{
String sql="Select * from movie";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmt= rs.getMetaData();
int c= rsmt.getColumnCount();
Vector column= new Vector(c);
for(int i=1;i<=c;i++)
{
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row=new Vector();
while(rs.next())
{
row=new Vector(c);
for(int i=1;i<=c;i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
JButton back= new JButton("Back");
JPanel topPanel = new JPanel(new GridLayout(1, 0, 3, 3));
topPanel.add(back);
JPanel panel= new JPanel();
table=new JTable(data,column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp,BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
}
}
This is the output I get.
You're forgetting one line of code, the line that adds the topPanel to the panel JPanel:
panel.add(topPanel, BorderLayout.PAGE_START);
Side note: for future questions, you will want to make your code compilable and runnable by us, meaning get rid of unnecessary dependencies, such as database. For your code above, the database stuff could be replaced by:
JPanel panel = new JPanel();
Integer[][] data = { { 1, 2, 3 }, { 4, 5, 6 } };
String[] column = { "A", "B", "C" };
table = new JTable(data, column);
But actually since it is just a simple layout question, even the JTable is not necessary.

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.

Setting the Box's size

This may seem like a stupid question, but I would like to change the size of a 'box' in my jFrame. I will include the code and a picture.
Here is the JTableResultSet class:
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.TableColumn;
public class JTableResultSet {
public static void main(String[] args) {
Vector columnNames = new Vector();
Vector data = new Vector();
JPanel panel = new JPanel(); //
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/exper482_social", "admin", "testing");
String sql = "Select username, forename, lastname, password from social_users";
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);
}
JTable table = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < table.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
column.setMaxWidth(250);//250
}
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
JFrame frame = new JFrame();
frame.add(panel);//adding panel to the frame
frame.setSize(600, 400); //setting frame size 600 400
frame.setVisible(true); //setting visibility true
}
}
And here is the photo:
http://i.stack.imgur.com/Wblfx.png
Can someone please tell me what i can do to make the box bigger? Thanks.
You can use BorderLayout which will make the JScrollPane occupy the full area of the JPanel
JPanel panel = new JPanel(new BorderLayout());
The default JPanel layout, FlowLayout, uses a component's preferred size which will not expand to fill the window.
Read Guide to Layout Managers

Categories

Resources