JTable Sorting... Please Help
Believe me when I say I have read the forums and the tutorials and the API and still I cannot
sort my JTable. Just a simple sort on the first column is all I want to do. I am using the default table model and I have the TableSorter and TableMap classes from the tutorial.
This is my set up:
tm = new DefaultTableModel(tc,th); //tc is a vector of rows, th is a vector of col headings
sorter = new TableSorter(tm);
addrTable = new JTable(sorter);
I think my biggest problem is how to call the TableSorter method. When I use: TableSorter.sortByColumn(0); I get the error... non-static method cannot be referenced from static context. When I try just sortByColumn(0); of course the compiler cannot resolve symbol.
What do I do?
not sure if this will work as i haven't tried it, but i think you'll need to make a call to the sorter.sortByColumn(int, boolean) method. retrive the column index the same way you placed the data in that cell or from a call to :
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
from the point where your cursor is.
if you do that right after your edit of the cell (where you should be able to get the column index) and also pass in the boolean ascending or descedning value it should sort post-edit.
again i haven't tried it, and thats just by looking over the code...
worth a try though... hope it makes sense...
Takis
Similar Messages
-
Remove the key listener from JTable problem please help
Hi
I�m trying to remove the key listener from my table, it doesn�t work,
I�m pressing the enter key it still goes to the next row from the table,
hear is my code
KeyListener[] mls = (KeyListener[])(table.getListeners(KeyListener.class));
for(int i = 0; i < mls.length; i++ )
table.removeKeyListener(mls);
Please help thanksHm ...
that should indeed remove all the KeyListeners from your table - the question is only, when does this happen?- Where in your code do you remove the KeyListeners?- I am quite sure, you remove them successfully, but after your have removed them, one or more KeyListeners are added to the table.
greetings Marsian -
How to use vector in JTable? Please help......
Hi there
I can use JTable using object array to manupulate data but it has a limitation of defining number of rows of the array. Alternatively i want to use vector. Anyone help me how to convert to using vector.
Regards.
mortoza, Dhakahi,
you could either use javax.swing.table.DefaultTableModel because this class uses a java.util.Vector for data storage or you could implements your own TableModel by extending javax.swing.table.AbstractTableModel.
best regards, Michael -
Ok my first question will be:
I have written a class containing two JTables which is below:
import javax.swing.JTable;
import java.awt.Dimension;
import javax.swing.table.AbstractTableModel;
public class TableSetup {
JTable wageTable;
JTable categoryTable;
public TableSetup()
String[] columnNames = {"Wage",
"Hours",
"Gross Pay",
"Taxes",
"Net Pay"};
Object[][] data = {
{new Float(14.12), new Integer(20),
new Float(282.40), new Float(84.72),new Float(197.68)},
{new Float(14.12), new Integer(40),
new Float(564.80), new Float(169.44),new Float(395.36)},
{new Float(14.12), new Integer(80),
new Float(1129.60), new Float(338.88),new Float(790.72)}
wageTable = new JTable(data,columnNames);
String[] columnNames2 = {"Categories",
"Percentage",
"Dollar Amount(20 Hours)",
"Dollar Amount(40 Hours)",
"Dollar Amount(80 Hours)",
"Net Pay"};
Object[][] data2 = {
{new String("Food"), new String(" "),
new String(" "), new String(" "),new String(" "), new String(" ")},
{new String("Gasoline"), new String(" "),
new String(" "), new String(" "), new String(" "), new String(" "), new String(" ")},
{new String("Savings"), new String(" "),
new String(" "), new String(" "),new String(" "), new String(" "), new String(" ")},
{new String("Entertainment"), new String(" "),
new String(" "), new String(" "),new String(" "), new String(" "), new String(" ")},
{new String("Miscellaneous"), new String(" "),
new String(" "), new String(" "),new String(" "), new String(" "), new String(" ")},
{new String("Misc Savings"), new String(" "),
new String(" "), new String(" "),new String(" "), new String(" "), new String(" ")}
categoryTable = new JTable(data2,columnNames2);
// wageTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
}I instantiate it globally in my graphic drawing class like this:
TableSetup setup = new TableSetup();Then I add a listener to them in the constructor like this:
setup.wageTable.getModel().addTableModelListener(this);
setup.categoryTable.getModel().addTableModelListener(this);And I want to use the tableChanged function:
public void tableChanged(TableModelEvent e) {
}What I want to do is have a separate things happen depending on which of the two table are being changed.
My question is how do I distinguish between whether the "setup.wageTable" is being changed or the "setup.categoryTable" is being changed so I can code the two separate conditions depending on which table is being changed.
Please continue to check this thread because I'm going to have more questions later.
Thanks in advanced.
Edited by: translore on Aug 22, 2008 11:24 PM
Edited by: translore on Aug 22, 2008 11:26 PMtranslore wrote:
My question is how do I distinguish between whether the "setup.wageTable" is being changed or the "setup.categoryTable" is being changed so I can code the two separate conditions depending on which table is being changed.
Have two separate listeners. You can use inner classes or anonymous classes for the listeners - https://java.sun.com/docs/books/tutorial/java/javaOO/nested.html . -
Sir,
I have a requirement.
Table :Price
Columns : Price_id
LOCK_EXPIRE_DATE
RELOCK_EXPIR_DATE
LOCK_EXTEN_EXPIR_DATE
I want to sort based on
LOCK_EXPIRE_DATE, RELOCK_EXPIR_DATE,
LOCK_EXTEN_EXPIR_DATE
eg:
Price_id | LOCK_EXPIRE_DATE | RELOCK_EXPIR_DATE | LOCK_EXTEN_EXPIR_DATE
19 | 12-12-2006 | NULL | NULL
15 | NULL | 15-12-2006 | NULL
14 | NULL | NULL | 11-12-2006
After sorting the above data should come like this,
14 | NULL | NULL | 11-12-2006
19 | 12-12-2006 | NULL | NULL
15 | NULL | 15-12-2006 | NULL
regards
MathewSuppose the table contans more than 1000 rows, this method will become difficult.I don't understand. Did you want to sort or not ?
1000 rows is nothing...
Here an example with my more 70000 objects... order with nvl or coalesce or without any function, oracle run a FTS.
SQL> drop table tbl_dt ;
Table dropped.
Elapsed: 00:00:00.02
SQL> create table tbl_dt (price_id number,LOCK_EXPIRE_DATE date,RELOCK_EXPIR_DATE date,LOCK_EXTEN_EXPIR_DATE date);
Table created.
Elapsed: 00:00:00.00
SQL> insert into tbl_dt
2 select rownum,
3 decode(sign(dbms_random.random),1,null,sysdate+rownum),
4 decode(sign(dbms_random.random),1,null,sysdate+rownum),
5 decode(sign(dbms_random.random),1,null,sysdate+rownum)
6 from dba_objects;
70882 rows created.
Elapsed: 00:00:16.05
SQL>
SQL> select price_id, LOCK_EXPIRE_DATE,RELOCK_EXPIR_DATE,LOCK_EXTEN_EXPIR_DATE
2 from tbl_dt
3 where rownum<15;
PRICE_ID LOCK_EXP RELOCK_E LOCK_EXT
1 20/01/07
2 21/01/07 21/01/07 21/01/07
3 22/01/07
4 23/01/07
5 24/01/07 24/01/07
6 25/01/07 25/01/07
7 26/01/07
8
9 28/01/07
10
11 30/01/07
12 31/01/07 31/01/07
13 01/02/07
14 02/02/07 02/02/07
14 rows selected.
Elapsed: 00:00:00.00
SQL>
SQL> set autot traceonly explain stat
SQL> select Price_id, LOCK_EXPIRE_DATE, RELOCK_EXPIR_DATE, LOCK_EXTEN_EXPIR_DATE
2 from tbl_dt
3 order by LOCK_EXPIRE_DATE,RELOCK_EXPIR_DATE,LOCK_EXTEN_EXPIR_DATE;
70882 rows selected.
Elapsed: 00:01:14.03
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 SORT (ORDER BY)
2 1 TABLE ACCESS (FULL) OF 'TBL_DT'
Statistics
135 recursive calls
137 db block gets
241 consistent gets
943 physical reads
0 redo size
1677989 bytes sent via SQL*Net to client
33351 bytes received via SQL*Net from client
4727 SQL*Net roundtrips to/from client
2 sorts (memory)
1 sorts (disk)
70882 rows processed
SQL> select Price_id, LOCK_EXPIRE_DATE, RELOCK_EXPIR_DATE, LOCK_EXTEN_EXPIR_DATE
2 from tbl_dt
3 order by nvl(LOCK_EXPIRE_DATE,nvl(RELOCK_EXPIR_DATE,LOCK_EXTEN_EXPIR_DATE));
70882 rows selected.
Elapsed: 00:01:14.06
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 SORT (ORDER BY)
2 1 TABLE ACCESS (FULL) OF 'TBL_DT'
Statistics
0 recursive calls
104 db block gets
228 consistent gets
1138 physical reads
0 redo size
1624623 bytes sent via SQL*Net to client
33351 bytes received via SQL*Net from client
4727 SQL*Net roundtrips to/from client
0 sorts (memory)
1 sorts (disk)
70882 rows processed
SQL>
SQL> select Price_id, LOCK_EXPIRE_DATE, RELOCK_EXPIR_DATE, LOCK_EXTEN_EXPIR_DATE
2 from tbl_dt
3 order by coalesce(LOCK_EXPIRE_DATE,RELOCK_EXPIR_DATE,LOCK_EXTEN_EXPIR_DATE);
70882 rows selected.
Elapsed: 00:01:14.05
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 SORT (ORDER BY)
2 1 TABLE ACCESS (FULL) OF 'TBL_DT'
Statistics
0 recursive calls
104 db block gets
228 consistent gets
1137 physical reads
0 redo size
1624624 bytes sent via SQL*Net to client
33351 bytes received via SQL*Net from client
4727 SQL*Net roundtrips to/from client
0 sorts (memory)
1 sorts (disk)
70882 rows processed
SQL> Nicolas. -
Swing: JTable. Please help me!
You will really make my day if you tell me how I do this.
I have a JTable. In my JTable there are 3 columns (String, Calendar, Calendar), and my problem is I need to write a pretty cute Date in the interface (11/11/07 00:00), and I need to get this pretty date as a Calendar to pass it to my Object Evento.
I know I have to implement a class extending DefaltTableCellRenderer, but how do I implement it? And how I associated the JTabel with this cellRenderer I made?
Here is my TableModel:
class TabelaDeEventos extends AbstractTableModel{
private List<Evento> listEventos;
public TabelaDeEventos(List<Evento> listEventos){
this.listEventos = listEventos;
private String[] colunas = {"Nome do Evento","Data inicial","Data Final"};
public int getColumnCount(){
return 3;
public int getRowCount(){
return this.listEventos.size();
public String getColumnName(int coluna){
return colunas[coluna];
public Object getValueAt(int rowIndex, int columnIndex) {
Evento evento = this.listEventos.get(rowIndex);
Format formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
switch(columnIndex){
case 0:
return evento.getNome();
case 1:
//Date data = evento.getDataInicio().getTime();
//return formatter.format(data);
return evento.getDataInicio().getTime();
case 2:
//Date data1 = evento.getDataFim().getTime();
//return formatter.format(data1);
return evento.getDataFim().getTime();
return null;
public List<Evento> getListEventos() {
return listEventos;
public void setListEventos(List<Evento> listaEventos) {
this.listEventos = listaEventos;
public Class<?> getColumnClass(int columnIndex) {
switch(columnIndex){
case 0: return String.class;
case 1: return Date.class;
case 2: return Date.class;
return null;
}obs: I know that in this code I puted column 1 and 2 as a Date, but actually supose to be a Calendar becase the atributes dataInicial e dataFim are Calendars.
Thanks a lot!A variation on that: once you see the code in the tutorial, it's easy to modify
it to define a FormatRenderer that implements TableCellRenderer and has
a java.text.Format property you can set to format the text appropriately.
It's handy for more that just dates! -
Working with files(please help:))
Hello ,
i am a beginner in java,
well, i am trying to write a program which will read data from a text file and output it in another text file. Actualiy i have done that. already:)
The problem is that the data of the input file need to be sorted in a descending order, my question is: can somebody please help and tell me if i should use arrays and how can i fetch the data to manipulate it..i have the copy of the input file in the output but i can not figure out the sorting:(
please help
(refering to a code by a profesor) the code i wrote until now without the sorting (which i guess has to come in the while part)is:
public static void main(String[] args) throws IOException
FileReader file1 = new FileReader("data.txt");
BufferedReader inputFile = new BufferedReader(file1);
FileWriter file2 = new FileWriter("output.txt");
PrintWriter outputFile = new PrintWriter(file2);
String dataLine;
dataLine = inputFile.readLine();
while (tdataLine != null)
outputFile.println(dataLine);
dataLine = inputFile.readLine();
thanks
p.s. the input file looks smth like this:
995.95
desktop comp
180.95
microwave oven
254.99
washing machine
130.90
freezer
25.25
flash driveSo it is a file containing sequences of:
price
item nameI'd suggest you read 2 lines at a time, and stuff the lines into properties of an object that you design, capable of holding (you guessed it) a price, and an item name.
Build a collection of such objects, then sort it, then output the sorted collection.
These are just hints. But surely you're not just looking for someone to just hand you the coded up solution are you? -
I followed this procedure to check my files:
Please read this whole message before doing anything.
The following procedure will help whether your system has been modified. Don’t be alarmed by the complexity of these instructions — they’re easy to carry out and won’t change anything on your Mac.
These steps are to be taken while booted in “normal” mode, not in safe mode. If you’re now running in safe mode, reboot as usual before continuing.
Below are instructions to enter some UNIX shell commands. The commands are harmless, but they must be entered exactly as given in order to work. If you have doubts about the safety of the procedure suggested here, search this site for other discussions in which it’s been followed without any report of ill effects.
Some of the commands will line-wrap or scroll in your browser, but each one is really just a single line, all of which must be selected. You can accomplish this easily by triple-clicking anywhere in the line. The whole line will highlight, and you can then either copy or drag it. The headings “Step 1” and so on are not part of the commands.
Note: If you have more than one user account, Step 2 must be taken as an administrator. Ordinarily that would be the user created automatically when you booted the system for the first time. The other steps should be taken as the user who has the problem, if different. Most personal Macs have only one user, and in that case this paragraph doesn’t apply.
Launch the Terminal application in any of the following ways:
☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
☞ Open LaunchPad. Click Utilities, then Terminal in the page that opens.
When you launch Terminal, a text window will open with a line already in it, ending either in a dollar sign (“$”) or a percent sign (“%”). If you get the percent sign, enter “sh” and press return. You should then get a new line ending in a dollar sign.
Step 1
Copy or drag — do not type — the line below into the Terminal window, then press return:
kextstat -kl | awk '!/com\.apple/{printf "%s %s\n", $6, $7}'
Post the lines of output (if any) that appear below what you just entered (the text, please, not a screenshot.) You can omit the final line ending in “$”.
Step 2
Repeat with this line:
sudo launchctl list | sed 1d | awk '!/0x|com\.(apple|openssh|vix)|edu\.mit|org\.(amavis|apache|cups|isc|ntp|postfix|x)/{print $3}'
This time, you'll be prompted for your login password, which won't be displayed when you type it. You may get a one-time warning not to screw up. You don't need to post the warning.
Note: If you don’t have a login password, you’ll need to set one before taking this step. If that’s not possible, skip to the next step.
Step 3
launchctl list | sed 1d | awk '!/0x|com\.apple|edu\.mit|org\.(x|openbsd)/{print $3}'
Step 4
ls -1A /e*/mach* {,/}L*/{Ad,Compon,Ex,Fram,In,Keyb,La,Mail/Bu,P*P,Priv,Qu,Scripti,Servi,Spo,Sta}* L*/Fonts 2> /dev/null
Step 5
osascript -e 'tell application "System Events" to get name of every login item' 2> /dev/null
Remember, steps 1-5 are all drag-and-drop or copy-and-paste, whichever you prefer — no typing, except your password. Also remember to post the output.
You can then quit Terminal.
I believe that I have a keylogger or some sort of spyware installed on my mac, please help!
POST YOUR OUTPUT FOR REVIEW/COMMENT.
After running these commands, here is the output. Can you please tell me if you see anything here. I would be so grateful.
com.oxsemi.driver.OxsemiDeviceType00 (1.28.13)
at.obdev.nke.LittleSnitch (4052)
Password:
com.wdc.WDSmartWareServer
com.wdc.WDDMservice
com.sierrawireless.SwitchTool
com.oracle.java.JavaUpdateHelper
com.oracle.java.Helper-Tool
com.microsoft.office.licensing.helper
com.lacie.desktopmanager.service
com.google.keystone.daemon
com.adobe.fpsaud
at.obdev.littlesnitchd
jp.buffalo.NASPower
com.oracle.java.Java-Updater
com.lacie.eventsactions.launcher.agent
com.hp.messagecenter.launcher
com.hp.devicemonitor
com.google.keystone.system.agent
at.obdev.LittleSnitchUIAgent
com.nds.pcshow.uninstall
com.nds.pcshow
com.facebook.videochat.thomasbrown.updater
com.adobe.ARM.202f4087f2bbde52e3ac2df389f53a4f123223c9cc56a8fd83a6f7ae
com.adobe.AAM.Scheduler-1.0
LaCie DiscRecording/LaCie DiscRecording.pkg:
Contents
/Library/Address Book Plug-Ins:
/Library/Components:
/Library/Extensions:
/Library/Frameworks:
AEProfiling.framework
AERegistration.framework
Adobe AIR.framework
AudioMixEngine.framework
EWSMac.framework
HPDeviceModel.framework
HPPml.framework
HPScan.framework
HPServicesInterface.framework
HPSmartPrint.framework
HPSmartX.framework
NyxAudioAnalysis.framework
PluginManager.framework
Snapfish.framework
iLifeFaceRecognition.framework
iLifeKit.framework
iLifePageLayout.framework
iLifeSQLAccess.framework
iLifeSlideshow.framework
iTunesLibrary.framework
/Library/Input Methods:
/Library/Internet Plug-Ins:
AdobePDFViewer.plugin
Flash Player.plugin
JavaAppletPlugin.plugin
Quartz Composer.webplugin
QuickTime Plugin.plugin
SharePointBrowserPlugin.plugin
SharePointWebKitPlugin.webplugin
Silverlight.plugin
flashplayer.xpt
googletalkbrowserplugin.plugin
iPhotoPhotocast.plugin
npgtpo3dautoplugin.plugin
nsIQTScriptablePlugin.xpt
o1dbrowserplugin.plugin
/Library/Keyboard Layouts:
/Library/LaunchAgents:
at.obdev.LittleSnitchUIAgent.plist
com.adobe.AAM.Updater-1.0.plist
com.google.keystone.agent.plist
com.hp.devicemonitor.plist
com.hp.messagecenter.launcher.plist
com.lacie.eventsactions.launcher.agent.plist
com.oracle.java.Java-Updater.plist
jp.buffalo.NASPower.plist
jp.buffalo.NASPower_pla.plist
/Library/LaunchDaemons:
at.obdev.littlesnitchd.plist
com.adobe.fpsaud.plist
com.apple.remotepairtool.plist
com.google.keystone.daemon.plist
com.lacie.desktopmanager.service.plist
com.microsoft.office.licensing.helper.plist
com.oracle.java.Helper-Tool.plist
com.oracle.java.JavaUpdateHelper.plist
com.sierrawireless.SwitchTool.plist
com.wdc.WDDMservice.plist
com.wdc.WDSmartWareServer.plist
/Library/PreferencePanes:
Flash Player.prefPane
HP Scanjet.prefPane
JavaControlPanel.prefPane
/Library/PrivilegedHelperTools:
.DS_Store
NasNavigator2.app
com.microsoft.office.licensing.helper
com.oracle.java.JavaUpdateHelper
/Library/QuickLook:
GBQLGenerator.qlgenerator
iWork.qlgenerator
/Library/QuickTime:
AppleIntermediateCodec.component
AppleMPEG2Codec.component
/Library/ScriptingAdditions:
/Library/Spotlight:
GBSpotlightImporter.mdimporter
Microsoft Entourage.mdimporter
Microsoft Office.mdimporter
iWeb.mdimporter
iWork.mdimporter
/Library/StartupItems:
ChmodBPF
HP IO
LocSvc
/etc/mach_init.d:
/etc/mach_init_per_login_session.d:
/etc/mach_init_per_user.d:
Library/Address Book Plug-Ins:
SkypeABDialer.bundle
SkypeABSMS.bundle
Library/Fonts:
04b-08.suit
Arial
Brush Script
Times New Roman
Verdana
Wingdings
Wingdings 2
Wingdings 3
encodings.dir
fonts.dir
fonts.list
fonts.scale
Library/Frameworks:
EWSMac.framework
Library/Internet Plug-Ins:
FacebookVideoCalling.bundle
Move-Media-Player.plugin
PlayerPlugin.bundle
fbplugin_1_0_3.plugin
Library/Keyboard Layouts:
Library/LaunchAgents:
com.adobe.AAM.Updater-1.0.plist
com.adobe.ARM.202f4087f2bbde52e3ac2df389f53a4f123223c9cc56a8fd83a6f7ae.plist
com.facebook.videochat.thomasbrown.plist
com.nds.pcshow.plist
com.nds.pcshow.uninstall.plist
Library/PreferencePanes:
Opera Preferences
TomTomHOMERunner, LDMStatusItem, apple-scc-20130209-112927
thank you much for helping...sincerely. tlenbro.I followed this procedure to check my files:
Please read this whole message before doing anything.
The following procedure will help whether your system has been modified. Don’t be alarmed by the complexity of these instructions — they’re easy to carry out and won’t change anything on your Mac.
These steps are to be taken while booted in “normal” mode, not in safe mode. If you’re now running in safe mode, reboot as usual before continuing.
Below are instructions to enter some UNIX shell commands. The commands are harmless, but they must be entered exactly as given in order to work. If you have doubts about the safety of the procedure suggested here, search this site for other discussions in which it’s been followed without any report of ill effects.
Some of the commands will line-wrap or scroll in your browser, but each one is really just a single line, all of which must be selected. You can accomplish this easily by triple-clicking anywhere in the line. The whole line will highlight, and you can then either copy or drag it. The headings “Step 1” and so on are not part of the commands.
Note: If you have more than one user account, Step 2 must be taken as an administrator. Ordinarily that would be the user created automatically when you booted the system for the first time. The other steps should be taken as the user who has the problem, if different. Most personal Macs have only one user, and in that case this paragraph doesn’t apply.
Launch the Terminal application in any of the following ways:
☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
☞ Open LaunchPad. Click Utilities, then Terminal in the page that opens.
When you launch Terminal, a text window will open with a line already in it, ending either in a dollar sign (“$”) or a percent sign (“%”). If you get the percent sign, enter “sh” and press return. You should then get a new line ending in a dollar sign.
Step 1
Copy or drag — do not type — the line below into the Terminal window, then press return:
kextstat -kl | awk '!/com\.apple/{printf "%s %s\n", $6, $7}'
Post the lines of output (if any) that appear below what you just entered (the text, please, not a screenshot.) You can omit the final line ending in “$”.
Step 2
Repeat with this line:
sudo launchctl list | sed 1d | awk '!/0x|com\.(apple|openssh|vix)|edu\.mit|org\.(amavis|apache|cups|isc|ntp|postfix|x)/{print $3}'
This time, you'll be prompted for your login password, which won't be displayed when you type it. You may get a one-time warning not to screw up. You don't need to post the warning.
Note: If you don’t have a login password, you’ll need to set one before taking this step. If that’s not possible, skip to the next step.
Step 3
launchctl list | sed 1d | awk '!/0x|com\.apple|edu\.mit|org\.(x|openbsd)/{print $3}'
Step 4
ls -1A /e*/mach* {,/}L*/{Ad,Compon,Ex,Fram,In,Keyb,La,Mail/Bu,P*P,Priv,Qu,Scripti,Servi,Spo,Sta}* L*/Fonts 2> /dev/null
Step 5
osascript -e 'tell application "System Events" to get name of every login item' 2> /dev/null
Remember, steps 1-5 are all drag-and-drop or copy-and-paste, whichever you prefer — no typing, except your password. Also remember to post the output.
You can then quit Terminal.
I believe that I have a keylogger or some sort of spyware installed on my mac, please help!
POST YOUR OUTPUT FOR REVIEW/COMMENT.
After running these commands, here is the output. Can you please tell me if you see anything here. I would be so grateful.
com.oxsemi.driver.OxsemiDeviceType00 (1.28.13)
at.obdev.nke.LittleSnitch (4052)
Password:
com.wdc.WDSmartWareServer
com.wdc.WDDMservice
com.sierrawireless.SwitchTool
com.oracle.java.JavaUpdateHelper
com.oracle.java.Helper-Tool
com.microsoft.office.licensing.helper
com.lacie.desktopmanager.service
com.google.keystone.daemon
com.adobe.fpsaud
at.obdev.littlesnitchd
jp.buffalo.NASPower
com.oracle.java.Java-Updater
com.lacie.eventsactions.launcher.agent
com.hp.messagecenter.launcher
com.hp.devicemonitor
com.google.keystone.system.agent
at.obdev.LittleSnitchUIAgent
com.nds.pcshow.uninstall
com.nds.pcshow
com.facebook.videochat.thomasbrown.updater
com.adobe.ARM.202f4087f2bbde52e3ac2df389f53a4f123223c9cc56a8fd83a6f7ae
com.adobe.AAM.Scheduler-1.0
LaCie DiscRecording/LaCie DiscRecording.pkg:
Contents
/Library/Address Book Plug-Ins:
/Library/Components:
/Library/Extensions:
/Library/Frameworks:
AEProfiling.framework
AERegistration.framework
Adobe AIR.framework
AudioMixEngine.framework
EWSMac.framework
HPDeviceModel.framework
HPPml.framework
HPScan.framework
HPServicesInterface.framework
HPSmartPrint.framework
HPSmartX.framework
NyxAudioAnalysis.framework
PluginManager.framework
Snapfish.framework
iLifeFaceRecognition.framework
iLifeKit.framework
iLifePageLayout.framework
iLifeSQLAccess.framework
iLifeSlideshow.framework
iTunesLibrary.framework
/Library/Input Methods:
/Library/Internet Plug-Ins:
AdobePDFViewer.plugin
Flash Player.plugin
JavaAppletPlugin.plugin
Quartz Composer.webplugin
QuickTime Plugin.plugin
SharePointBrowserPlugin.plugin
SharePointWebKitPlugin.webplugin
Silverlight.plugin
flashplayer.xpt
googletalkbrowserplugin.plugin
iPhotoPhotocast.plugin
npgtpo3dautoplugin.plugin
nsIQTScriptablePlugin.xpt
o1dbrowserplugin.plugin
/Library/Keyboard Layouts:
/Library/LaunchAgents:
at.obdev.LittleSnitchUIAgent.plist
com.adobe.AAM.Updater-1.0.plist
com.google.keystone.agent.plist
com.hp.devicemonitor.plist
com.hp.messagecenter.launcher.plist
com.lacie.eventsactions.launcher.agent.plist
com.oracle.java.Java-Updater.plist
jp.buffalo.NASPower.plist
jp.buffalo.NASPower_pla.plist
/Library/LaunchDaemons:
at.obdev.littlesnitchd.plist
com.adobe.fpsaud.plist
com.apple.remotepairtool.plist
com.google.keystone.daemon.plist
com.lacie.desktopmanager.service.plist
com.microsoft.office.licensing.helper.plist
com.oracle.java.Helper-Tool.plist
com.oracle.java.JavaUpdateHelper.plist
com.sierrawireless.SwitchTool.plist
com.wdc.WDDMservice.plist
com.wdc.WDSmartWareServer.plist
/Library/PreferencePanes:
Flash Player.prefPane
HP Scanjet.prefPane
JavaControlPanel.prefPane
/Library/PrivilegedHelperTools:
.DS_Store
NasNavigator2.app
com.microsoft.office.licensing.helper
com.oracle.java.JavaUpdateHelper
/Library/QuickLook:
GBQLGenerator.qlgenerator
iWork.qlgenerator
/Library/QuickTime:
AppleIntermediateCodec.component
AppleMPEG2Codec.component
/Library/ScriptingAdditions:
/Library/Spotlight:
GBSpotlightImporter.mdimporter
Microsoft Entourage.mdimporter
Microsoft Office.mdimporter
iWeb.mdimporter
iWork.mdimporter
/Library/StartupItems:
ChmodBPF
HP IO
LocSvc
/etc/mach_init.d:
/etc/mach_init_per_login_session.d:
/etc/mach_init_per_user.d:
Library/Address Book Plug-Ins:
SkypeABDialer.bundle
SkypeABSMS.bundle
Library/Fonts:
04b-08.suit
Arial
Brush Script
Times New Roman
Verdana
Wingdings
Wingdings 2
Wingdings 3
encodings.dir
fonts.dir
fonts.list
fonts.scale
Library/Frameworks:
EWSMac.framework
Library/Internet Plug-Ins:
FacebookVideoCalling.bundle
Move-Media-Player.plugin
PlayerPlugin.bundle
fbplugin_1_0_3.plugin
Library/Keyboard Layouts:
Library/LaunchAgents:
com.adobe.AAM.Updater-1.0.plist
com.adobe.ARM.202f4087f2bbde52e3ac2df389f53a4f123223c9cc56a8fd83a6f7ae.plist
com.facebook.videochat.thomasbrown.plist
com.nds.pcshow.plist
com.nds.pcshow.uninstall.plist
Library/PreferencePanes:
Opera Preferences
TomTomHOMERunner, LDMStatusItem, apple-scc-20130209-112927
thank you much for helping...sincerely. tlenbro. -
Need to sort two vectors at the same time! please help!
I have
vectorA: 2 4 9 1 7 6 8
vectorB: two four nine one seven six eight
i want to sort these two vectors in parallel
what is the best way?
i could just do Collection.sort(vectorA) and get
1 2 4 6 7 8 9
but i want the vectorB to have a corresponding order
please help!!
thankspublic class Pair implements Comparable {
private int value;
private String name;
public int getValue() {
return this.value;
public void setValue(int value) {
this.value = value;
public String getName() {
return this.name;
public void setName(String name) {
this.name = name;
public int compareTo(Object o) {
Pair that = (Pair) o;
return this.value - that.value;
place both in a Collection (vector is a bad choice if you are going to do sorting LinkedList is better) the Collections.sort method will sort
according to the compareTo method. -
Please Help.JTable insert styled text
Hi all java guru,
on post http://forum.java.sun.com/thread.jsp?forum=57&thread=485469 i've depicted my scenario in which i have a JTable where i want to add styled text.
i've implemented a CustomTableModel that maintains information about text style, in such way that when renderer cell, i can rebuild exact text with its style....same method is adopted for CellEditor.
It is possible to have more than one JTable in my application....then to correctly handle all JTables ' put them in a vector and during editing and rendering i find current focusable/selected JTable and edit/render it.
Clearly i maintain information about style of text when i insert it, that is when i insert text, i update my CustomTableModel...same thing must be done when i delete text from JTable...that is, i must update CustomTableModel too in this case.
Because my CellEditor is a JEditorPane component (extend it) i've registered document associated to it to a DocumentListener that notify every time that a remove operation is happens.
What is the problem now???problem is that when i finish to edit a cell and click on another cell i've got a removeUpdate(DocumenEvent e) event, and i can't distinguish it.....it seems a real remove event....
In this case(when i change cell) the code that is executes returns wrong result and invalidate all the rest.
I think error is where i register celleditor , now i do it in CustomCellRenderer class that extend JEditorPane and implements TableCellRenderer.
Please help me...this is a great trouble that invalidate all my work :(
Any new idea is welcome.
regards,
anti-shockHi stanislav, of course i can...you're a myth :)
public class CustomCellEditor extends AbstractCellEditor implements TableCellEditor {
CellEditor cellArea;
JTable table;
public CustomCellEditor(JTable ta) {
super();
table = ta;
// this component relies on having this renderer for the String class
MultiLineCellRenderer renderer = new MultiLineCellRenderer();
table.setDefaultRenderer(String.class,renderer);
public Object getCellEditorValue() {
return cellArea.getText();
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
int start = 0;
int end = 0;
// Get current selected table
TableEditor tb = (TableEditor) TableEditor.getSelectedTable();
TableModel model = (TableModel) tb.getModel();
Vector fontInfo = model.getFontFor(row,column);
CellEditor cellArea = (CellEditor) ((CustomCellEditor)tb.getCellEditor (row,column)).getCellEditor();
Document doc = cellArea.getDocument();
String content = tb.getValueAt(row,column).toString();
if (doc!=null && fontInfo.size()>0 && !content.equals("")) {
// This method reads from model and get right style info
// for current text, and restore them
restoreFontWithAttributes(doc,fontInfo,content);
else
cellArea.setText(tb.getValueAt(row,column).toString());
cellArea.rowEditing = row;
cellArea.columnEditing = column;
cellArea.lastPreferredHeight = cellArea.getPreferredSize().height;
return cellArea;
* @return
public CellEditor getCellEditor() {
return cellArea;
public class CellEditor extends JEditorPane {
private CellStyledEditorKit k;
public CellEditor() {
super("text/plain","");
k = new CellStyledEditorKit();
setEditorKit(k);
// I tried to add document here, but i have had wrong behavior
doc = new DocumentListener() {
public void removeUpdate(DocumentEvent e) {
// Get current selected table
TableEditor tb = (TableEditor) TableEditor.getSelectedTable();
TableModel model = (TableModel) tb.getModel();
model.updateFontInfo();
getDocument().addDocumentListener(doc);
}Ok, stan...this is my CustomCellRenderer class....as i have already said, i have some style text info mainteined by CustomTableModel associated with JTable.
I update CustomTableModel every time that an insert and remove operation happens.
If i add a DocumentListener to CellEditor (that rapresents editor cell of my table) happens that, if i remove some character from an editing cell, i got a removeUpdate event.....and this is right!!! But if i change cell (e.g. supposing editing cell(1,1), click on cell(2,1) then stop edit cell(1,1) and start edit cell(2,1)) i got a removeUpdate event, that I don't wait for to me..
Look at this:
empty cell | some text
cell 0 ------- cell1
supposing you're in cell1 and you have finished to insert "some text".Then click on cell0, that is empty....then document associated with CellArea(extend JEditorPane) before of the click on cell0 had some text, but after click have no text, then for it a removeUpdate is happens.....and is that one i got..
it's as if an unique document is associated to all cells, while should be one document for each cell (i hope this is right).
Clearly, i've same code for renderer, in such way that i can restore style of text on rendering.
Hope is clear....if U have any idea or suggestion please give to me.
Tnx a lot Stanislav..
regards,
anti-shock -
Sort Not working - Please help
Hello,
I have design2003 parameter. Im displaying table with following logic. Problem is it is not activating SORT icon thats comes in table header text line which sorts the column. What could be wrong? Please help.
<htmlb:tableView id = "table_prod_cat"
design = "alternating"
fillUpEmptyRows = "true"
headerText = "Category_List"
headerVisible = "true"
onRowSelection = "prod_cat_rowselection"
selectionMode = "none"
table = "<%= lt_prod_cat_list %>"
visibleRowCount = "<%= l_sprec_display %>"
width = "100%" >
<htmlb:tableViewColumns>
<%-- Product Category ID --%>
<htmlb:tableViewColumn columnName = "product_cat"
onItemClick = "prod_cat_id_itemclick"
width = "80"
sort = "X"
title = "<B>Category</>"
type = "link" />
<%-- Product Category Description --%>
<htmlb:tableViewColumn columnName = "CATEGORY_TEXT"
title = "<B> Category Text</>"
sort = "X"
width = "200" />
<htmlb:tableViewColumn columnName = "PRODUCT_GRP"
title = "<B>Product Group</>"
sort = "X"
width = "200" />
<htmlb:tableViewColumn columnName = "PRODUCT_SGRP"
title = "<B>Product Sub-Group</>"
sort = "X"
width = "200" />
</htmlb:tableViewColumns>
</htmlb:tableView>Ajay,
You should use sort = "server" or sort = "none" .
sort - Use this attribute to activate sorting for the
individual rows and to determine who is responsible for the sorting.
NONE (default, there is no sorting), SERVER (HTMLB carries out the
sorting) and APPLICATION (the application carries out the sorting) If
you specify SERVER, you should also set the attributes keyColumn and
onHeaderClick.
I have changed your code..use this code and let me know if you get any issue.
<htmlb:tableView id = "table_prod_cat"
design = "alternating"
fillUpEmptyRows = "true"
headerText = "Category_List"
headerVisible = "true"
onRowSelection = "prod_cat_rowselection"
selectionMode = "none"
<b>sort = "server"</b>
table = "<%= lt_prod_cat_list %>"
visibleRowCount = "<%= l_sprec_display %>"
width = "100%" >
<htmlb:tableViewColumns>
<%-- Product Category ID --%>
<htmlb:tableViewColumn columnName = "product_cat"
onItemClick = "prod_cat_id_itemclick"
width = "80"
<b>sort = "true"</b>
title = "<B>Category</>"
type = "link" />
<%-- Product Category Description --%>
<htmlb:tableViewColumn columnName = "CATEGORY_TEXT"
title = "<B> Category Text</>"
<b>sort = "true"</b>
width = "200" />
<htmlb:tableViewColumn columnName = "PRODUCT_GRP"
title = "<B>Product Group</>"
<b>sort = "true"</b>
width = "200" />
<htmlb:tableViewColumn columnName = "PRODUCT_SGRP"
title = "<B>Product Sub-Group</>"
<b>sort = "true"</b>
width = "200" />
</htmlb:tableViewColumns>
</htmlb:tableView>
Thanks!
Lakshmikandh<b></b>
Message was edited by:
Lakshmikandh Chinnasamy -
I had to restore my iPod because I forgot the password, like how santa forgot about me. And I didn't set up a Backup. SO I sort of lost everything. But I'm wondering if I can somehow get my pictures back from somewhere. PLEASE HELP ME. Thanks
- If you used PhotoStream then try getting some of them from your PhotoStream. See that topic of:
iOS: Importing personal photos and videos from iOS devices to your computer
- Maybe from the restored iPod via
How to perform iPad recovery for photos, videos
Wondershare Dr.Fone for iOS: iPhone Data Recovery - Wondershare Official
http://www.amacsoft.com/ipod-data-recovery.html -
Apple Senior tech lady deleted all my external drive data while sorting out other problem. How can I restore all my photos , music etc back to my Mac Pro?(I am so scared, I haven't connected iPhone to sync! Please help)
It was tele tech. I couldn't open my Page Numbers etc. Frist tech chat idiot - following dumping few things in bin, asked me yo upgrade to Yosemite. But the problem still persists. This morning I was asked to do it via telephone and like yesterday, after wasting 20 min, I was put to this apparent Tech Queen ( my foot!). She eventually decided to reinstall Yosemite asked me to connect my external drive while I connected to her. She was moving cursor asking me to move files and delete and I followed her like a dummy. It took 3/4 hours and she called me 3 times once the lengthy process was completed. I suspected from the beginng for the fact that why should be asking me to click all my backup from the very beginning! Eventually she said I deleted... Or someone else or may be my children ! It was a blatant lie. I run my small business from home and I was simply staying in front of the Mac whole day! Children were at school. Then she said I must have used another computer! I only have laptop and the iPad. I will talk to their manager first thing in the morning. In the mean time please let me know as to how can I transfer photos, music etc back to my laptop from my Iphone and IPad .? I am will connect to laptop as I am worried the new BLANK iPhoto may supersede iphone/iPad stuff? Will it? Please let me know. I am not a very tech savvy person. My son who could help me, is in Manchester Uni and Inam in London.
-
Please help me..about JTable ..Please please
I have a JTable and tried to set the width for its columns..but I dont
know why it doesnt work..here's my codes:
Please help me..thanks..
import javax.swing.table.TableColumn;
import javax.swing.table.*;
JTable table = new JTable();
//a method{
DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
public boolean isCellEditable(int row, int col){ return false; }
table.setModel(model);
TableColumn column = tblEntryList.getColumnModel().getColumn(0);
column.setPreferredWidth(25);
column = tblEntryList.getColumnModel().getColumn(1);
column.setPreferredWidth(100);I did feed the data into the table..you can tell by looking at my codes..
please show me..dont know why it doesnt work.
I just have my tlbEntrylist declared as
String[][] rowData = new String[0][];
String[] columnNames = {"Cnt","Name","Text"};
JTable tblEntryList = new JTable(rowData, columnNames);
//then whenever I click a a button , will call loadTableEntries()
to remove all row data and refresh with new data..so I have to
set new new model for this table.
private void loadTableEntries()
tblEntryList.removeAll(); // Remove old entries
Object[][] rowData = new Object[entries.length][3];
//feed the table of new data
for(int i=0;i<rowData.length;i++)
rowData[0] =new Integer(entries[i].getTimesUsed());
rowData[i][1] = entries[i].getName();
rowData[i][2] = entries[i].getText();
String[] columnNames = {"Cnt","Name","Text"};
// Create a new model and load it with new values
DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
public boolean isCellEditable(int row, int col){ return false; }
tblEntryList.setModel(model);
TableColumn col = tblEntryList.getColumn(tblEntryList.getModel().getColumnName(0));
col.setPreferredWidth(10);
col = tblEntryList.getColumn(tblEntryList.getModel().getColumnName(1));
col.setPreferredWidth(25);
I dont know what i'm doing wrong here but it ddint work.. -
Jtable Update problem .. Please help !!!!!!!!
Hi ,
I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
Here is the code .... Please see it and tell me if it is possible :
package newpackage;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.text.*;
import newpackage.ExcelExporter;
import java.awt.Dimension;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import java.awt.print.*;
import java.awt.*;
import java.io.*;
import java.util.Random.*;
import javax.swing.*;
import java.text.*;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class tab7le extends javax.swing.JFrame {
Vector columnNames = new Vector();
Vector data = new Vector();
Connection con;
Statement stat;
ResultSet rs;
int li_cols = 0;
Vector allRows;
Vector row;
Vector newRow;
Vector colNames;
String dbColNames[];
String pkValues[];
String tableName;
ResultSetMetaData myM;
String pKeyCol;
Vector deletedKeys;
Vector newRows;
boolean ibRowNew = false;
boolean ibRowInserted = false;
private Map<String, Color> colormap = new HashMap<String, Color>();
/** Creates new form tab7le */
public tab7le() {
populate();
initComponents();
public void updateDB(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException e){
System.out.println("Cannot Load Driver!");
try{
String url = "jdbc:odbc:FAMS";
con = DriverManager.getConnection(url);
stat = con.createStatement();
rs = stat.executeQuery("Select * from SubAllot");
deletedKeys = new Vector();
newRows = new Vector();
myM = rs.getMetaData();
tableName = myM.getTableName(1);
li_cols = myM.getColumnCount();
dbColNames = new String[li_cols];
for(int col = 0; col < li_cols; col ++){
dbColNames[col] = myM.getColumnName(col + 1);
allRows = new Vector();
while(rs.next()){
newRow = new Vector();
for(int i = 1; i <= li_cols; i++){
newRow.addElement(rs.getObject(i));
} // for
allRows.addElement(newRow);
} // while
catch(SQLException e){
System.out.println(e.getMessage());
String updateLine[] = new String[dbColNames.length];
try{
DatabaseMetaData dbData = con.getMetaData();
String catalog;
// Get the name of all of the columns for this table
String curCol;
colNames = new Vector();
ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
while (rset1.next()) {
curCol = rset1.getString(4);
colNames.addElement(curCol);
rset1.close();
pKeyCol = colNames.firstElement().toString();
// Go through the rows and perform INSERTS/UPDATES/DELETES
int totalrows;
totalrows = allRows.size();
String dbValues[];
Vector currentRow = new Vector();
pkValues = new String[allRows.size()];
// Get column names and values
for(int i=0;i < totalrows;i++){
currentRow = (Vector) allRows.elementAt(i);
int numElements = currentRow.size();
dbValues = new String[numElements];
for(int x = 0; x < numElements; x++){
String classType = currentRow.elementAt(x).getClass().toString();
int pos = classType.indexOf("String");
if(pos > 0){ // we have a String
dbValues[x] = "'" + currentRow.elementAt(x) + "'";
updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString() ;
pos = classType.indexOf("Integer");
if(pos > 0){ // we have an Integer
dbValues[x] = currentRow.elementAt(x).toString();
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString();
else{
updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
pos = classType.indexOf("Boolean");
if(pos > 0){ // we have a Boolean
dbValues[x] = currentRow.elementAt(x).toString();
updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString() ;
} // For Loop
// If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
int numNewRows = newRows.size();
int insertRow = 0;
boolean newRowFound;
for (int z = 0;z < numNewRows;z++){
insertRow = ((Integer) newRows.get(z)).intValue();
if(insertRow == i+1){
StringBuffer InsertSQL = new StringBuffer();
InsertSQL.append("INSERT INTO " + tableName + " (");
for(int zz=0;zz<=dbColNames.length-1;zz++){
if (dbColNames[zz] != null){
InsertSQL.append(dbColNames[zz] + ",");
// Strip out last comma
InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
InsertSQL.append(" VALUES(" + pkValues[i] + ",");
for(int c=1;c < dbValues.length;c++){
InsertSQL.append(dbValues[c] + ",");
InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
System.out.println(InsertSQL.toString());
stat.executeUpdate(InsertSQL.toString());
ibRowInserted=true;
} // End of INSERT Logic
// If row has not been INSERTED perform an UPDATE
if(ibRowInserted == false){
StringBuffer updateSQL = new StringBuffer();
updateSQL.append("UPDATE " + tableName + " SET ");
for(int z=0;z<=updateLine.length-1;z++){
if (updateLine[z] != null){
updateSQL.append(updateLine[z]);
// Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
System.out.println(updateSQL.toString());
stat.executeUpdate(updateSQL.toString());
} //for
catch(Exception ex){
System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
// Delete records from the DB
try{
int numDeletes = deletedKeys.size();
String deleteSQL;
for(int i = 0; i < numDeletes;i++){
deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
((Integer) deletedKeys.get(i)).toString();
System.out.println(deleteSQL);
stat.executeUpdate(deleteSQL);
// Assume deletes where successful. Recreate Vector holding PK Keys
deletedKeys = new Vector();
catch(Exception ex){
System.out.println(ex.getMessage());
public void populate()
try
// Connect to the Database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
System.out.println("ok1");
// Read data from a table
String sql;
sql = "Select * from SubAllot";
System.out.println("ok1");
Statement stmt = con.createStatement();
System.out.println("ok1");
ResultSet rs = stmt.executeQuery( sql );
System.out.println("ok1");
ResultSetMetaData md = rs.getMetaData();
System.out.println("ok1");
int columns = md.getColumnCount();
for(int i = 0;i<columns;i++){
columnNames.addElement(md.getColumnName(i+1));
System.out.println("ok2");
while (rs.next())
Vector row = new Vector(columns);
for (int i = 1; i <columns+1; i++)
row.addElement( rs.getObject(i) );
data.addElement( row );
catch(Exception e){
e.printStackTrace();
public void dropmenu(JTable table,TableColumn subpref1) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
for (int i = 0;i<=20;i++)
comboBox.addItem(i);
subpref1.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
subpref1.setCellRenderer(renderer);
abstract class StringTransferHandler extends TransferHandler {
public int dropAction;
protected abstract String exportString(final JComponent c);
protected abstract void importString(final JComponent c, final String str);
@Override
protected Transferable createTransferable(final JComponent c) {
return new StringSelection(exportString(c));
@Override
public int getSourceActions(final JComponent c) {
return MOVE;
@Override
public boolean importData(final JComponent c, final Transferable t) {
if (canImport(c, t.getTransferDataFlavors())) {
try {
String str = (String) t.getTransferData(DataFlavor.stringFlavor);
importString(c, str);
return true;
} catch (UnsupportedFlavorException ufe) {
} catch (IOException ioe) {
return false;
@Override
public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
for (int ndx = 0; ndx < flavors.length; ndx++) {
if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
return true;
return false;
class TableTransferHandler extends StringTransferHandler {
private int dragRow;
private int[] dragColumns;
private BufferedImage[] image;
private int row;
private int[] columns;
public JTable target;
private Map<String, Color> colormap;
private TableTransferHandler(final Map<String, Color> colormap) {
this.colormap = colormap;
@Override
protected Transferable createTransferable(final JComponent c) {
JTable table = (JTable) c;
dragRow = table.getSelectedRow();
dragColumns = table.getSelectedColumns();
createDragImage(table);
return new StringSelection(exportString(c));
protected String exportString(final JComponent c) {
JTable table = (JTable) c;
row = table.getSelectedRow();
columns = table.getSelectedColumns();
StringBuffer buff = new StringBuffer();
colormap.clear();
for (int j = 0; j < columns.length; j++) {
Object val = table.getValueAt(row, columns[j]);
buff.append(val == null ? "" : val.toString());
if (j != columns.length - 1) {
buff.append(",");
colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
table.repaint();
return buff.toString();
protected void importString(final JComponent c, final String str) {
target = (JTable) c;
DefaultTableModel model = (DefaultTableModel) target.getModel();
String[] values = str.split("\n");
int colCount = target.getSelectedColumn();
int max = target.getColumnCount();
for (int ndx = 0; ndx < values.length; ndx++) {
String[] data = values[ndx].split(",");
for (int i = 0; i < data.length; i++) {
String string = data;
if(colCount < max){
Object val = model.getValueAt(target.getSelectedRow(), colCount);
model.setValueAt(string, target.getSelectedRow(), colCount);
model.setValueAt(val, dragRow, dragColumns[i]);
colCount++;
public BufferedImage[] getDragImage() {
return image;
private void createDragImage(final JTable table) {
if (dragColumns != null) {
try {
image = new BufferedImage[dragColumns.length];
for (int i = 0; i < dragColumns.length; i++) {
Rectangle cellBounds = table.getCellRect(dragRow, i, true);
TableCellRenderer r = table.getCellRenderer(dragRow, i);
DefaultTableModel m = (DefaultTableModel) table.getModel();
JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
lbl.setBounds(cellBounds);
BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D graphics = img.createGraphics();
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
lbl.paint(graphics);
graphics.dispose();
image[i] = img;
} catch (RuntimeException re) {
class TableDropTarget extends DropTarget {
private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
private Rectangle rect2D = new Rectangle();
private TableTransferHandler handler;
public TableDropTarget(final TableTransferHandler h) {
super();
this.handler = h;
@Override
public void dragOver(final DropTargetDragEvent dtde) {
handler.dropAction = dtde.getDropAction();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
Point location = dtde.getLocation();
int row = table.rowAtPoint(location);
int column = table.columnAtPoint(location);
table.changeSelection(row, column, false, false);
paintImage(table, location);
autoscroll(table, location);
super.dragOver(dtde);
public void dragExit(final DropTargetDragEvent dtde) {
clearImage((JTable) dtde.getDropTargetContext().getComponent());
super.dragExit(dtde);
@Override
public void drop(final DropTargetDropEvent dtde) {
Transferable data = dtde.getTransferable();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
clearImage(table);
handler.importData(table, data);
super.drop(dtde);
private final void paintImage(final JTable table, final Point location) {
Point pt = new Point(location);
BufferedImage[] image = handler.getDragImage();
if (image != null) {
table.paintImmediately(rect2D.getBounds());
rect2D.setLocation(pt.x - 15, pt.y - 15);
int wRect2D = 0;
int hRect2D = 0;
for (int i = 0; i < image.length; i++) {
table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
pt.x += image[i].getWidth();
if (hRect2D < image[i].getHeight()) {
hRect2D = image[i].getHeight();
wRect2D += image[i].getWidth();
rect2D.setSize(wRect2D, hRect2D);
private final void clearImage(final JTable table) {
table.paintImmediately(rect2D.getBounds());
private Insets getAutoscrollInsets() {
return autoscrollInsets;
private void autoscroll(final JTable table, final Point cursorLocation) {
Insets insets = getAutoscrollInsets();
Rectangle outer = table.getVisibleRect();
Rectangle inner = new Rectangle(outer.x + insets.left,
outer.y + insets.top,
outer.width - (insets.left + insets.right),
outer.height - (insets.top + insets.bottom));
if (!inner.contains(cursorLocation)) {
Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
cursorLocation.y - insets.top,
insets.left + insets.right,
insets.top + insets.bottom);
table.scrollRectToVisible(scrollRect);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
table.setModel(new javax.swing.table.DefaultTableModel(
data, columnNames
jScrollPane1.setViewportView(table);
//populate();
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(true);
table.setDragEnabled(true);
TableTransferHandler th = new TableTransferHandler(colormap);
table.setTransferHandler(th);
table.setDropTarget(new TableDropTarget(th));
dropmenu(table, table.getColumnModel().getColumn(11));
jButton1.setText("Update");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jButton2.setText("Ex");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(347, 347, 347)
.addComponent(jButton1)
.addGap(115, 115, 115)
.addComponent(jButton2)))
.addContainerGap(73, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jButton1)
.addContainerGap(83, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addGap(65, 65, 65))))
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
updateDB(); // TODO add your handling code here:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
pathToDesktop = pathToDesktop + "//Final Allotment.xls";
ExcelExporter exp = new ExcelExporter();
exp.exportTable(table, new File(pathToDesktop));
JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
} // TODO add your handling code here:
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new tab7le().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table;
// End of variables declaration
Please help !!!!!!!!
Thanks in advance.....Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
Why post code with access to a database? We can't access the database.
Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
Maybe you are looking for
-
I have spent all morning trying to get locations to add to events on my iMac this now works and has synced with my phone but when I open the event in my phone it has the address but doesn't show a map and doesnt give an option to get directions. I ha
-
ITunes not allowed in the Enterprise!
Ok so I want to sync data but iTunes is forbidden on our machines. I don't think we are the only company with this policy so how then is the iPad ready for enterprise use?
-
Add Progress Bar to a query component (ViewCriteria)
Hi, I would like to add a progress bar (or any relevant component to show the process is going on) to QueryComponent (ViewCriteria). Please guide me how to achieve this. Thanks.
-
PayloadSwapBean with a .doc attachment
Hi everyone. I'm receiving a webservice with a .doc document as attachment. The only thing i want is to save that file into a folder. In the sender SOAP adapter, i make the payloadswapbean, so the attachment is the main payload now. Problem is that
-
Hi, Do anyone can explain to me why MiniDV tape recording always facing the issue of Drop Frame??no way to solve it?