JTable
To use JTable, take a look at this link:
This is demo code below, try it.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
//notice that I say implements actionlistener, this is to say that I will be listening for actions
public class TableExample extends JApplet implements ActionListener
{
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
JButton addRowButton= new JButton ("Add");
//init is a method that gets called automatically when the applet starts or initializes
//in init we are adding our swing components to the applet
public void init()
{
Container screen = getContentPane();
screen.setBackground(Color.green);
screen.setLayout (new FlowLayout() );
screen.add(addRowButton);
screen.add(table);
model.addColumn("Col1");
model.addColumn("Col2");
// Append a row
model.addRow(new Object[]{"v1", "v2"});
model.addRow(new Object[]{"v1", "v2"});
model.addRow(new Object[]{"v1", "v2"});
// there are now 2 rows with 2 columns
//for all components that i want to listen for an action [like a click of button]
//I add action listener saying Im going to be listening
addRowButton.addActionListener(this);
}
//in paint I tell it to paint the components and then draw a line
public void paint (Graphics g)
{
super.paint(g);
g.drawLine(5,200,400,200);
}
//now we have to have a method actionPerformed that will be called if an action happens
//we then see which component had the action on it
public void actionPerformed(ActionEvent thisEvent)
{
Object source = thisEvent.getSource();
if (source == addRowButton)
{
model.addRow(new Object[]{"v1", "v2"});
}
}
}
|