...

View Full Version : JTable



Scriptr
03-02-2012, 03:49 PM
I have made a table. How can I get the selected column? This is what I have thus far:



import java.awt.*;
import java.awt.print.*;
import javax.swing.*;

public class jtable{

private String[] thead = {"Select the time:", "7:00 AM - 10:00AM", "10:00 AM - 1:00 PM", "1:00 PM - 5:00 PM", "5:00 PM - 8:00 PM"};
private String[][] tbody = {{"Children < 3", "FREE", "FREE", "$2.00", "FREE"},{"Children < 14", "$2.00", "$2.00", "$5.00", "$3.00"},{"14+", "$3.00", "$5.00", "$8.00", "$6.00"},{"65+", "$2.00", "$2.00", "$5.00", "$3.00"}};
public JTable table = new JTable(tbody, thead);

public jtable(){
JFrame frame = new JFrame("Select a time");
frame.setLayout(new FlowLayout());
frame.setSize(650, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);

table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
table.getColumnSelectionAllowed();
ListSelectionModel colSM = table.getSelectionModel();
colSM.addListSelectionListener(new HC());

JScrollPane sp = new JScrollPane(table);
frame.getContentPane().add(sp, BorderLayout.CENTER);

frame.setVisible(true);
}
public static void main(String args[]){
jtable jt = new jtable();
}
}


Where class HC contains:


import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class HC implements ListSelectionListener{



public HC(){

}
public void valueChanged(ListSelectionEvent arg0) {
System.out.println(arg0);
}

}



I know several imports aren't used. I basically just add everything I might need and delete what still isn't used when I'm done.

Scriptr
03-05-2012, 05:09 PM
I reread the guide to tables and I have written this code, based on their listener, but it returns the number twice and it returns the row. I can debug it (I probably misplaced the print statement) to fix the former, but how do I make it return the column?



public void valueChanged(ListSelectionEvent e){

ListSelectionModel ll = (ListSelectionModel)e.getSource();
int index = 0;

if (ll.isSelectionEmpty()){
index = -1;
}else{
int min = ll.getMinSelectionIndex();
int max = ll.getMaxSelectionIndex();

for (int i = min; i <= max; i++){
if (ll.isSelectedIndex(i)){
index = i;
}
}
}
System.out.println(index);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum