Setting the Box's size - java

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

Related

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);

Checkbox in the beginning of jTable

I am new to Swing and seeking some help here. I need to show the data from an .xls file in a jTable. Below is my code which I followed from here :-
jbClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
jChooser.showOpenDialog(null);
File file = jChooser.getSelectedFile();
if(!file.getName().endsWith("xls")){
JOptionPane.showMessageDialog(null, "Please select only Excel file.", "Error",JOptionPane.ERROR_MESSAGE);
}
else {
fillData(file);
model = new DefaultTableModel(data, headers);
tableWidth = model.getColumnCount() * 150;
tableHeight = model.getRowCount() * 25;
table.setPreferredSize(new Dimension( tableWidth, tableHeight));
table.setModel(model);
jbClick.setVisible(false);
jbText.setVisible(true);
}
}
});
JPanel chooserPanel = new JPanel();
JPanel filterPanlel = new JPanel();
//filterPanlel.add(jbText,"OLa");
final Color alternate = new Color(186,246,244);
table = new JTable();
table.setAutoCreateRowSorter(true);
model = new DefaultTableModel(data, headers);
table.setModel(model);
table.setBackground(alternate);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setEnabled(false);
table.setRowHeight(25);
table.setRowMargin(4);
tableWidth = model.getColumnCount() * 200;
tableHeight = model.getRowCount() * 25;
table.setPreferredSize(new Dimension( tableWidth, tableHeight));
scroll = new JScrollPane(table);
scroll.setBackground(alternate);
scroll.setPreferredSize(new Dimension(500, 500));
scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(buttonPanel, BorderLayout.NORTH);
getContentPane().add(scroll, BorderLayout.CENTER);
//setSize(600, 600);
setResizable(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
//setUndecorated(true);
setVisible(true);
}
/** * Fill JTable with Excel file data. * * #param file * file :contains xls file to display in jTable */
#SuppressWarnings({ "unchecked", "rawtypes" })
void fillData(File file) {
Workbook workbook = null;
try {
try {
workbook = Workbook.getWorkbook(file);
}
catch (IOException ex) {
Logger.getLogger( excelTojTable.class. getName()).log(Level.SEVERE, null, ex);
}
Sheet sheet = workbook.getSheet(0);
headers.clear();
for (int i = 0; i < sheet.getColumns(); i++)
{
Cell cell1 = sheet.getCell(i, 0);
headers.add(cell1.getContents());
}
data.clear();
for (int j = 1; j < sheet.getRows(); j++)
{
Vector d = new Vector();
for (int i = 0; i < sheet.getColumns(); i++)
{
Cell cell = sheet.getCell(i, j);
d.add(cell.getContents());
}
d.add("\n");
data.add(d);
}
}
catch (BiffException e) {
e.printStackTrace();
}
}
Problem :- Now I need to add a editable checkbox in-front of each row in the table.
Please help.
I need to add a editable checkbox in-front of each row in the table.
Before your loops that create the "header" and "d" Vectors, you need to add your Boolean information.
So for the header you might do:
headers.clear();
header.add("Select");
and for each row:
Vector d = new Vector();
d.add( Boolean.FALSE );.
i got a new column in my table but its not a checkbox
Then you would need to set the default renderer for the first column of the table by updating the TableColumn of the TableColumnModel using the default renderer for the Boolean class:
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellRenderer( table.getDefaultRenderer( Boolean.class ) );
i am new to swing
Start with the Swing tutorial on [How to Use Table]
(http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) for the basics of renderers.
Edit:
A simple SSCCE that demonstrate the solution:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
Vector<String> header = new Vector<String>();
header.add("Select");
header.add("Column1");
header.add("Column2");
header.add("Column3");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
for (int row = 0; row < 5; row++)
{
Vector<Object> d = new Vector<Object>();
d.add( Boolean.FALSE );
for (int column = 0; column < 3; column++)
{
d.add(row + " : " + column);
}
data.add(d);
}
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable( model );
table.setPreferredScrollableViewportSize(table.getPreferredSize());
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellRenderer( table.getDefaultRenderer( Boolean.class ) );
tc.setCellEditor( table.getDefaultEditor( Boolean.class ) );
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

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

JTable columns wont show up

Im having an issue with JTable columns. I create the JTable but the columns wont show up.And yes, I tried the previously asked question about this issue saying about adding a JScrollPane but putting the ScrollPane inside destroyed completely my Table and the Table wasn't visible.
I tried frame.getContentPane.add(new JScrollPane(table)) from this link (JTable won't show column headers) but didnt have any effect as I said above.
Im not using a layout manager.
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
String[] cols = new String[columnCount];
for (i=1;i<= columnCount;i++)
{
cols[i-1] = md.getColumnName(i);
}
DefaultTableModel model = new DefaultTableModel(cols,0);
while (rs.next())
{
Object[] row = new Object[columnCount];
for (i = 1 ; i <= columnCount ; i++)
{
row[i-1] = rs.getObject(i);
}
model.addRow(row);
}
JTable table = new JTable(model);
model.fireTableDataChanged();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(146,59,763,360);
frame.getContentPane().add((table));
model.fireTableDataChanged();
}
JTable is designed to work with JScrollPane, it will automatically add the TableHeader to the scroll pane, for example
Instead of
frame.getContentPane().add((table));
Try using...
frame.getContentPane().add(new JScrollPane(table));
See How to Use Tables for more details
Beware, you should avoid using setBounds and instead use an appropriate layout manager, you should also void using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Updated...
You should never need to call fireTableDataChanged or any other event methods on a model, they are not meant for your use, but for use within the model.
Before adding the table/scroll pane to the content pane, try this...
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(table));
Let me demonstrate...
With a layout manager...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TableExample {
public static void main(String[] args) {
new TableExample();
}
public TableExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
int columnCount = 10;
String[] cols = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
cols[i - 1] = Integer.toString(i);
}
DefaultTableModel model = new DefaultTableModel(cols, 0);
JTable table = new JTable(model);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Without a layout manager...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TableExample {
public static void main(String[] args) {
new TableExample();
}
public TableExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
int columnCount = 10;
String[] cols = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
cols[i - 1] = Integer.toString(i);
}
DefaultTableModel model = new DefaultTableModel(cols, 0);
JTable table = new JTable(model);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
The problem isn't with the code you've shown us, the problem is with your choice to do away with one of the core concepts upon which the Swing API is built on...the layout manager
You can try to get the TableHeader from the Table and add this to the ContentPane:
JTableHeader tableHeader = table.getTableHeader();
frame.getContentPane().add(tableHeader);
Either you have to wrap your table in a JScrollPane like this:
frame.getContentPane().add(new JScrollPane(table));
Or you have to add the table header separatly:
frame.getContentPane().add(table.getTableHeader, BorderLayout.NORTH);
frame.getContentPane().add(table); // By default this adds to CENTER
This assumes the layout manager of the content pane is the default BorderLayout.

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)

Categories

Resources