Java JTable changes when click on JButton - java

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

Related

Gui Interactions

This is my first time creating a Gui and I'm stumped on how to create interactions.
I'm trying to implement a single selection mode when the combobox is on single, and multiple when it's placed on multiple. I placed them on the multi line comment.
Any ideas?
//Interactions
//When “Single” is selected then the JList changes so only one item
can be selected.
//When “Multiple” is selected, the JList changes so multiple items can
be selected
//When a country, or multiple countries, is selected the JLabel
changes to reflect the new selections
public class GuiTest {
public static String[] Countries = {"Africa", "Haiti", "USA", "Poland", "Russia", "Canada", "Mexico", "Cuba"};
public static String[] Selection = {"Single", "Multiple"};
JPanel p = new JPanel();
JButton b = new JButton("Testing");
JComboBox jc = new JComboBox(Selection);
JList jl = new JList(Countries);
private static void constructGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
frame.setTitle("Countries Selection");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add a JLabel that says Welcome
JLabel label = new JLabel("Selected Items:");
frame.add(label);
frame.pack();
JComboBox jc = new JComboBox(Selection);
frame.add(jc);
frame.pack();
frame.setVisible(true);
JList jl = new JList(Countries);
frame.add(jl);
frame.pack();
JComponent panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JLabel("Choose Selection Mode:"));
panel.add(jc);
frame.add(panel, BorderLayout.NORTH);
frame.add(jl, BorderLayout.WEST);
frame.add(label, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
constructGUI();
}
});
}
}
you should start adding the modes to the ComboBox:
comboBoxCategoria.addItem("Single",0);
comboBoxCategoria.addItem("Multiple",1);
then add a ActionListener to your ComboBox to modify the list selection mode
jc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(jc.getSelectedItem().equals("Single")){
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}else{//must equals
jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
}
});
finally add a MouseListener on the list to detect changes on the list selections and change the JLabel to reflect the new selections
jl.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
label.setText(list.getSelectedValuesList().toString());
}
});
edit: you should also add a KeyListener to update the label since the selection can be changed via arrow keys
jl.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
label.setText(list.getSelectedValuesList().toString());
}
});
It would be something like this:
jc.addActionListener((evt) -> {
if ("Single".equals(jc.getSelectedItem())) {
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
int[] sel = jl.getSelectedIndices();
if (sel != null && sel.length > 1) {
jl.setSelectedIndex(sel[0]);
}
} else {
jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
});
jl.addListSelectionListener((evt) -> {
StringBuilder buf = new StringBuilder();
for (Object o: jl.getSelectedValuesList()) {
if (buf.length() > 0) {
buf.append(", ");
}
buf.append(o);
}
label.setText(buf.toString());
});
jc.setSelectedItem("Single");

populate DefaultTableModel after insert a row java

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.

JScrollPane does not work on JPanel

I have a frame that contains a mainPanel. This last will add other commandPanels (each one contains a button and a textField) Dynamically. the problem is that the JScrollPane does not appear to let me use the unseen commandPanels even if the mainPanel is full.
The below picture shows my case.
To initialize the window I wrote below code:
frame = new JFrame();
frame.setBounds(100, 100, 962, 639);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(264, 6, 692, 500);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
scroll = new JScrollPane();
scroll.getViewport().add(mainPanel);
frame.getContentPane().add(scroll);
and the method that add dynamically the new commandPanels is:
public void loadCommandPanel(String commandName)
{
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
mainPanel.add( scroll, BorderLayout.EAST);
frame.add( mainPanel);
...
}
Any help to get the scrollPane, will be much more than appreciated.
scroll.getViewport().add(mainPanel); is not how you use JViewport or JScrollPane; instead you should using something like this:
scroll.getViewport().setView(newCommandPanel);
or
scroll.setViewportView(newCommandPanel);
Take a look at How to Use Scroll Panes for more details.
Note also, this doesn't makes sense:
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
You add newCommandPanel to mainPanel, then promptly add it to another container (albeit incorrectly).
A component can only reside on a single parent; the moment you add it to another container, it is automatically removed from the previous container.
I have made some changes and it works perfectly now. For those who want the same thing here's my code:
import ...
public class mainUserInterface {
private JFrame frame;
private JPanel mainPanel;
private JPanel commandsPanel;
private JScrollPane commandsScrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainUserInterface window = new mainUserInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainUserInterface() {
initialize();
}
private void initialize() {
frame = new JFrame("CommandsExecutor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 700));
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.setBorder( new TitledBorder("") );
commandsPanel = new JPanel();
commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.Y_AXIS));
for(int i=0; i<15;i++){
commandsPanel.add(new CommandPanel());
}
commandsScrollPane = new JScrollPane(commandsPanel);
mainPanel.add(commandsScrollPane,BorderLayout.CENTER);
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
and Here's the commandPanel class:
import ...
public class CommandPanel extends JPanel {
private JTextField commandResult;
private JButton commandBtn;
public CommandPanel()
{
this.setLayout( new BorderLayout(10,10));
this.setBorder( new TitledBorder("Command:") );
this.setMaximumSize(new Dimension(692,60));
this.setMinimumSize(new Dimension(692,60));
commandBtn = new JButton("Execute");
commandBtn.setMaximumSize(new Dimension(137, 34));
commandBtn.setMinimumSize(new Dimension(137, 34));
this.add(commandBtn, BorderLayout.WEST);
commandResult = new JTextField();
commandResult.setMaximumSize(new Dimension(518, 34));
commandResult.setMinimumSize(new Dimension(518, 34));
this.add(commandResult, BorderLayout.CENTER);
}
public JTextField getCommandResult() {
return commandResult;
}
public JButton getCommandBtn() {
return commandBtn;
}
public void setCommandResult(JTextField commandResult) {
this.commandResult = commandResult;
}
public void setCommandBtn(JButton commandBtn) {
this.commandBtn = commandBtn;
}
}
Thanks for all who answered my question, it really helped.

How can I add JButtons in a DefaultListModel?

I am making a battleship game and I'm trying to figure out a way to control buttons in a pane so that I can drag drop them and keep track of their indexes with a default list model.If I add string or ImageIcons it works fine but with buttons I get something different.
Here's my code:
public class ListModelExample extends JPanel {
JList list;
DefaultListModel model;
int counter = 15;
public ListModelExample() {
setLayout(new BorderLayout());
model = new DefaultListModel();
list = new JList(model);
JScrollPane pane = new JScrollPane(list);
JButton addButton = new JButton("Add Element");
JButton removeButton = new JButton("Remove Element");
final JButton button = new JButton("button");
for (int i = 0; i < 5; i++)
model.addElement(button);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addElement(button);
counter++;
}
});
removeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (model.getSize() > 0)
model.removeElementAt(0);
}
});
add(pane, BorderLayout.NORTH);
add(addButton, BorderLayout.WEST);
add(removeButton, BorderLayout.EAST);
}
public static void main(String s[]) {
JFrame frame = new JFrame("List Model Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ListModelExample());
frame.setSize(260, 200);
frame.setVisible(true);
}
}
If I add Buttons I get this result:
So my question is: How is it possible to make buttons appear normally and not as text in a default list model?
this could be done only by Renderer, put only String value to the DefaultListModel
don't put any JComponents to the XxxModel
I'd be use JPanel with JButtons instead of JList as containers (required to change getScrollableBlockIncrement / getScrollableUnitIncrement for natural scrolling in compare with JList or JTable)
example about both a.m. ways
import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
public class ListButtons extends JFrame {
private static final long serialVersionUID = 1L;
public ListButtons() {
setLayout(new GridLayout(0, 2, 10, 10));
DefaultListModel model = new DefaultListModel();
model.addElement(createButtons("one"));
model.addElement(createButtons("two"));
model.addElement(createButtons("three"));
model.addElement(createButtons("four"));
model.addElement(createButtons("five"));
model.addElement(createButtons("six"));
model.addElement(createButtons("seven"));
model.addElement(createButtons("eight"));
model.addElement(createButtons("nine"));
model.addElement(createButtons("ten"));
model.addElement(createButtons("eleven"));
model.addElement(createButtons("twelwe"));
JList list = new JList(model);
list.setCellRenderer(new PanelRenderer());
JScrollPane scroll1 = new JScrollPane(list);
final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar.getValue());
}
});
add(scroll1);
JScrollPane scroll2 = new JScrollPane(createPanel());
add(scroll2);
final JScrollBar scrollBar1 = scroll2.getVerticalScrollBar();
scrollBar1.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar1.getValue());
}
});
}
public static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 1, 1));
panel.add(createButtons("one"));
panel.add(createButtons("two"));
panel.add(createButtons("three"));
panel.add(createButtons("four"));
panel.add(createButtons("five"));
panel.add(createButtons("six"));
panel.add(createButtons("seven"));
panel.add(createButtons("eight"));
panel.add(createButtons("nine"));
panel.add(createButtons("ten"));
panel.add(createButtons("eleven"));
panel.add(createButtons("twelwe"));
return panel;
}
public static JButton createButtons(String text) {
JButton button = new JButton(text);
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ListButtons frame = new ListButtons();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//frame.pack();
frame.setSize(270, 200);
frame.setVisible(true);
}
});
}
class PanelRenderer implements ListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JButton renderer = (JButton) value;
renderer.setBackground(isSelected ? Color.red : list.getBackground());
return renderer;
}
}
}

Adding a component to jPanel java

i'm trying to add a jtable component to my jPanel but i am unable to see it. What am i doing wrong?.
table gui = new table(data,colum);
mainPanel.add(gui.table);
class table extends JFrame
{
public JTable table;
public table(Vector data, Vector colum)
{
setLayout(new FlowLayout());
table = new JTable(data,colum);
table.setPreferredScrollableViewportSize(new Dimension(900,10));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Extending JFrame seems odd; you don't use any of the top level container capabilities. Here's an example that extends JPanel, with a main() that drops the panel into a JFrame.
--Edited to accept an existing JPanel
public class TablePanel
{
public static void addTableToPanel(JPanel jPanel, Vector rowData, Vector columnNames)
{
JTable jTable = new JTable(rowData, columnNames);
jTable.setFillsViewportHeight(true);
JScrollPane jScrollPane = new JScrollPane(jTable);
jScrollPane.setPreferredSize(new Dimension(300, 50));
jPanel.add(jScrollPane);
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeAndWait(new Runnable()
{
#Override
public void run()
{
Vector cols = new Vector();
Vector rows = new Vector();
Vector row1 = new Vector();
cols.add("A");
cols.add("B");
cols.add("C");
row1.add("1");
row1.add("2");
row1.add("3");
rows.add(row1);
rows.add(row1.clone());
rows.add(row1.clone());
rows.add(row1.clone());
JFrame frame = new JFrame("TableTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout(0, 0));
TablePanel.addTableToPanel(jPanel, rows, cols);
frame.getContentPane().add(jPanel);
frame.pack();
frame.setVisible(true);
}
});
}
}

Categories

Resources