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.
Related
I have a database with tables. I passed the name of the tables into the buttons. When you click, you need a table with fields and filling to appear. The problem is that I have a new table added every time I click on the button.
Can someone please say me how to do it? Thanks in advance!
public class App extends JPanel {
static List<FieldElement> fields = new ArrayList<>();
static List<Map<String, Object>> data = new ArrayList<>();
static JTable jTable = new JTable();
public static void createGUI() throws SQLException {
TableContent tableContent = new TableContent();
JFrame frame = new JFrame();
MetadataHelper databaseMetadata = new MetadataHelper();
List<ButtonElement> elements = databaseMetadata.showTables();
JPanel panel = new JPanel();
JPanel buttons = new JPanel(new GridLayout(0, 1));
for (ButtonElement buttonElements : elements) {
JButton jButton = new JButton(buttonElements.getTablesInMigrateSchema());
buttons.add(jButton);
jButton.addActionListener(new ActionListener() {
#SneakyThrows
#Override
public void actionPerformed(ActionEvent e) {
fields = tableContent.getDatabaseMetadata().showFields(buttonElements.getTablesInMigrateSchema());
data = tableContent.getDatabaseMetadata().selectAll(buttonElements.getTablesInMigrateSchema());
Object[][] objectRows = data.stream().map(m -> m.values().toArray()).toArray(Object[][]::new);
jTable = new JTable(objectRows, fields.toArray());
panel.add(new JScrollPane(jTable));
frame.revalidate();
frame.repaint();
}
});
}
panel.add(buttons, BorderLayout.EAST);
frame.add(panel);
frame.setTitle("SwingSandbox");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#SneakyThrows
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
createGUI();
}
});
}
}
One easy possibility is to store the JScrollPane in a variable (which holds your table that you want to remove):
static JTable jTable = new JTable();
static JScrollPane jScrollPane;
And then in your actionPerformed method:
public void actionPerformed(ActionEvent e) {
...
if (jScrollPane != null) {
panel.remove(jScrollPane);
}
jTable = new JTable(objectRows, fields.toArray());
jScrollPane = new JScrollPane(jTable);
panel.add(jScrollPane);
frame.revalidate();
frame.repaint();
}
I am running a program with two frames. First one has a table, the second one has a form which allows adding a new user to the table. I think the problem is I didn't add a reference from the mainframe. I was trying different methods to refresh the mainframe programmatically, but it did not help so much. I read many articles on how to to it but I could find a solution. My table usually changes when I close my app and open it again. But I don't think is the right way to do it. I tried to delete elements from DefaultTableModel and populated jtable again, but did not get any results. Here is my code:
public Vector vector_jtable = new Vector();
public MainApp() {
initComponents();
Database b = new Database();
b.getAmountOfRows(getCount);
this.setLocationRelativeTo(null);
printResultDB();
}
//add function that is responsible for addding data to the table
public void postDataJtable() {
System.out.println("The vector is: " + vector_jtable);
Vector<String> header = new Vector<String>();
header.add("Number");
header.add("Name");
header.add("First Payment");
header.add("Next Payment");
header.add("Picture");
header.add("Phone");
header.add("Amount");
header.add("Age");
model = (DefaultTableModel)jTable2.getModel();
model.setDataVector(vector_jtable,header);
}
I created a vector that allows putting data from the second frame.
MainApp app;
public AddStudents(MainApp a) {
initComponents();
app = a;
this.setLocationRelativeTo(null);
jDateChooser1.setDateFormatString("yyyy-MM-dd");
jDateChooser2.setDateFormatString("yyyy-MM-dd");
}
After that, I push the button to send it out and update the mainframe, but nothing happened:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
app.vector_jtable.add(name);
app.vector_jtable.add(first_p);
app.vector_jtable.add(next_p);
app.vector_jtable.add(picture);
app.vector_jtable.add(phone);
app.vector_jtable.add(amount);
app.vector_jtable.add(age);
app.postDataJtable();
My question. How to add a row in jtable and refresh it. I really stuck in this topic. I need your help.
Don't update the Vector.
When you want to change the data in the table you need to change the data in the TableModel.
You can use the addRow(...) method of the DefaultTableModel to add a new row of data.
So the basic logic is:
Vector<Object> row = new Vector<Object>();
row.add( someVariable1 );
row.add( someVariable2 );
...
modal.addRow( row ):
The model will then tell the table to repaint itself.
Edit:
There is no trick all you need is a reference to the model. Then you update the model.
Here is a simple example to prove the concept works:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
private DefaultTableModel model;
SSCCE()
{
setLayout( new BorderLayout() );
model = new DefaultTableModel(0, 2);
JTable table = new JTable( model );
add(new JScrollPane( table ));
JButton button = new JButton( "Add Row" );
add(button, BorderLayout.PAGE_END);
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
Vector<Object> row = new Vector<Object>();
row.add( "" + model.getRowCount() );
row.add( new Date().toString() );
model.addRow( row );
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
If it doesn't work for you then you need to debug your code. Maybe you have two "model" variables? Maybe you have to "table" variables. Maybe your code isn't even executed. Did you add any debug statements to the code to make sure it is executed.
We can't solve your problem only point you in the right direction.
You can try some aspects from this example below. The example has two JFrame's - one with a JTable and the other the data entry fields. When the data is entered and the "UpdateTable" button is pressed (in the data entry class) the table is updated.
The example uses java.util.Observer and Observable to achieve this functionality.
The class with table:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.util.Observer;
import java.util.Observable;
public class TableUpdateTester implements Observer {
private JTable table;
private static final Object[] TABLE_COLUMNS = {"Book", "Author"};
private static final Object [][] TABLE_DATA = {
{"Book 1", "author 1"}, {"Book 2", "author 1"}
};
public static void main(String [] args) {
TableUpdateTester tester = new TableUpdateTester();
new DataEntryClass(tester);
}
public TableUpdateTester() {
JFrame frame = new JFrame("Table Update Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getTablePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel getTablePanel() {
table = new JTable(new DefaultTableModel(TABLE_DATA, TABLE_COLUMNS));
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setPreferredSize(new Dimension(400, 150));
scrollpane.setViewportView(table);
JPanel panel = new JPanel();
panel.add(scrollpane);
return panel;
}
// This is Observer's override method.
#Override public void update(Observable o, Object arg) {
String [] data = (String []) arg;
System.out.println("Data recieving: " + java.util.Arrays.toString(data));
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(data);
}
}
The data entry class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;
public class DataEntryClass {
public DataEntryClass(TableUpdateTester observer) {
final DataObservable observable = new DataObservable();
observable.addObserver(observer);
JLabel label = new JLabel("Book: ");
final JTextField text = new JTextField(15);
JLabel label2 = new JLabel("Author: ");
final JTextField text2 = new JTextField(15);
JButton button = new JButton("Update Table");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data1 = text.getText().isEmpty() ? "empty" : text.getText();
String data2 = text2.getText().isEmpty() ? "empty" : text2.getText();
String [] data = {data1, data2};
System.out.println("Data sent: " + java.util.Arrays.toString(data));
observable.changeData(data);
}
});
JPanel panel = new JPanel();
GridLayout grid = new GridLayout(3, 2);
panel.setLayout(grid);
panel.add(label);
panel.add(text);
panel.add(label2);
panel.add(text2);
panel.add(new JLabel(""));
panel.add(button);
JFrame frame = new JFrame();
frame.setTitle("Data Entry");
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.pack();
}
}
class DataObservable extends Observable {
DataObservable() {
super();
}
void changeData(Object data) {
// the two methods of Observable class
setChanged();
notifyObservers(data);
}
}
Finally, I found a solution to my problem. I will post my code here.
The Mainframe. I know the app with two frames is not a good option, because it's hard to fix the problem and it usually takes a lot of time to debug it.
/**
* Create the application.
*/
public MainApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 689, 345);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//add table in DefaultTableModel
model = new DefaultTableModel(0,2);
table = new JTable(model);
table.setBounds(58, 38, 524, 197);
frame.getContentPane().add(table);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 0, 4, 4);
frame.getContentPane().add(scrollPane);
JButton btnNewButton = new JButton("Add");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Call a second frame
//add reference for DefaultTableModel and send it to another frame
AddData frame = new AddData(model);
frame.setVisible(true);
}
});
btnNewButton.setBounds(239, 269, 117, 29);
frame.getContentPane().add(btnNewButton);
}
The second frame, that is responsible for adding a new row in a table.
/**
* Create the frame.
*/
public AddData(DefaultTableModel model) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(115, 71, 188, 41);
contentPane.add(dateChooser);
JButton btnNewButton = new JButton("Send");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//MainApp app = new MainApp();
Vector<Object> row = new Vector<Object>();
row.add(""+model.getRowCount());
row.add(dateChooser.getDate().toString());
model.addRow(row);
}
});
btnNewButton.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
btnNewButton.setBounds(165, 192, 117, 41);
contentPane.add(btnNewButton);
}
I found my mistake. I did not send a link of DefaultTableModel into the second frame. That's why it was null every time. It was a really painful experience, but I learned from my mistakes. Thanks, everyone for your help. I really appriciate.
I am new to java. And Most of my questions here are going unanswered, I don't know what is wrong with my question. I hope this question gets some answer.
So, Now I am creating a frame, this frame contains tabbedPane and tabbedPane contains two JPanels. All this is done in one function createAndShowGUI()
And there is another function which is creating buttons with for loop, and I want to add this new buttons to my JPanel panel. Here is my code. I want to add buttons creating in createButton() method to panel created in createAndShowGUI() method
public class Try extends JFrame {
static Connection conn;
//JPanel panel;
static JButton buttons;
static int totalRows;
static int recordPerPage = 1000000;
static int totalPages = 0;
private static JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGUI();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
protected static void createAndShowGUI() throws SQLException {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setBounds(30, 50, 1300, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
frame.setContentPane(contentPane);
UIManager.put("TabbedPane.selected", Color.lightGray);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBorder(new EmptyBorder(10, 10, 10, 10));
frame.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("TABLE", null, panel, null);
tabbedPane.setFont( new Font( "Dialog", Font.BOLD|Font.ITALIC, 16 ) );
panel.setBackground(Color.white);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("GRAPH", null, panel_1, null);
panel_1.setBackground(Color.white);
JTable table = new JTable();
panel.add(table);
table.setFillsViewportHeight(true);
createDBConnection();
}
private static void createDBConnection() throws SQLException {
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_temp/h2_db/test", "sa", "sa");
} catch (SQLException e) {
e.printStackTrace();
}
createPaginationButtons(conn);
}
private static void createPaginationButtons(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) FROM cdr");
while (rs.next()) {
JOptionPane.showMessageDialog(null, rs.getInt(1));
totalRows = rs.getInt(1);
}
int v = totalRows % recordPerPage == 0 ? 0 : 1;
totalPages = totalRows / recordPerPage + v;
createButton(totalPages);
}
private static void createButton(int totalPages) {
JOptionPane.showMessageDialog(null, totalPages);
for(int i = 0; i < totalPages;) {
buttons = new JButton(""+(i+1) );
//JOptionPane.showMessageDialog(null, buttons);
panel.add(buttons);
i++;
}
}
}
Any idea, how to do this ?
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.
For example I have a Table that I want to get text that's in the first column and store it in an ArrayList.
Java Tables often use the TableModel interface for storage.
You can get the a particular value via:
myJTable.getModel().getValueAt(rowIndex, columnIndex);
More on that: Sun's Swing Table Tutorial
public static void main(String[] args)
{
try
{
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
cp.setLayout(new FlowLayout());
final JTable tbl = new JTable(new String[][]{{"c1r1", "c2r1"}, {"c1r2", "c2r2"}}, new String[]{"col 1", "col 2"});
cp.add(tbl);
cp.add(new JButton(new AbstractAction("click")
{
#Override
public void actionPerformed(ActionEvent e)
{
List<String> colValues = new ArrayList<String>();
for (int i = 0; i < tbl.getRowCount(); i++)
colValues.add((String) tbl.getValueAt(0, i));
JOptionPane.showMessageDialog(frame, colValues.toString());
}
}));
frame.pack();
frame.setVisible(true);
}
catch (Throwable e)
{
e.printStackTrace();
}
}
You need to go through the JTable's TableModel, accessible through the getModel() method. That has all the information you need.