drag and drop files from OS into JTable java - java

Can someone show me what I'm doing wrong? I was able to get drag and drop working with a regular panel but now trying with a table and I can't sort it out. I'm getting confused with the Points and DropTargets. Dont mind the "Add" button. I feel like I need to deal with the DnD first.
public class Table extends JFrame implements ActionListener {
private JTable table;
private JScrollPane scroll;
private JButton add;
private JFileChooser choose;
private JMenuBar menubar;
private JMenu menu;
private JMenuItem file;
private DefaultTableModel tm = new DefaultTableModel(new String[] { "File",
"File Type", "Size", "Status" }, 2);
public Table() {
// String column [] = {"Filename ","File Type", "Size", "Status" };
/*
* Object[][] data = { {"File1", ".jpg","32 MB", "Not Processed"},
* {"File2", ".txt"," 5 Kb", "Not Processed"}, {"File3", ".doc","3 Kb",
* "Not Processed"},
* };
*/
table = new JTable();
table.setModel(tm);
table.setFillsViewportHeight(true);
table.setPreferredSize(new Dimension(500, 300));
scroll = new JScrollPane(table);
table.setDropTarget(new DropTarget() {
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
Point point = dtde.getLocation();
int column = table.columnAtPoint(point);
int row = table.rowAtPoint(point);
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File f = (File) fileList.get(0);
table.setValueAt(f.getAbsolutePath(), row, column);
table.setValueAt(f.length(), row, column + 1);
super.drop(dtde);
}
});
scroll.setDropTarget(new DropTarget() {
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
Point point = dtde.getLocation();
int column = table.columnAtPoint(point);
int row = table.rowAtPoint(point);
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File f = (File) fileList.get(0);
table.setValueAt(f.getAbsolutePath(), row, column);
table.setValueAt(f.length(), row, column + 1);
// handle drop outside current table (e.g. add row)
super.drop(dtde);
}
});
add(scroll, BorderLayout.CENTER);
menubar = new JMenuBar();
menu = new JMenu("File");
file = new JMenuItem("file");
menu.add(file);
// menubar.add(menu);
add(menu, BorderLayout.NORTH);
ImageIcon icon = new ImageIcon("lock_icon.png");
add = new JButton("Add", icon);
add.addActionListener(this);
JFileChooser choose = new JFileChooser();
choose.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
int returnValue = 0;
if (clicked == add) {
choose = new JFileChooser();
choose.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = choose.getSelectedFile();
file.getAbsolutePath();
}
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Table t = new Table();
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.pack();
t.setSize(600, 200);
t.setVisible(true);
t.setTitle("ZipLock");
t.setIconImage(null);
}
});
}
}

I personally would ditch the drop target on the scroll pane, it's going to cause you to many problems.
Your drop method is a little queezy...
This is a bad idea....
List fileList = null;
try {
fileList = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File f = (File) fileList.get(0);
table.setValueAt(f.getAbsolutePath(), row, column);
table.setValueAt(f.length(), row, column + 1);
Basically, you try and extract the file list from the transferable, and regardless of the success of the operation, you try and use it ?! You do no validation of the returned value at all...
Your drop code generally doesn't really care about what column the drop occurred on, as you have name and size columns already, so I'd actually ignore that altogether.
As for the row, now you have two choices. Either you add a new row when the user doesn't drop on an existing one or you reject the attempt.
Reject drag's "outside" of table
(Or reject drags that don't call over an existing row)
To reject the operation while the user is dragging, you need to override the dragOver method...
#Override
public synchronized void dragOver(DropTargetDragEvent dtde) {
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if (row < 0) {
dtde.rejectDrag();
table.clearSelection();
} else {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
table.setRowSelectionInterval(row, row);
}
}
Now, I'm been a little smart here (and not in the clever way). Basically, if the user has dragged over a row, I've highlighted it. This makes it a little more obvious where the drop is going.
In your drop method, I would also make some additional checks...
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if (row >= 0) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
if (fileList.size() > 0) {
table.clearSelection();
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setValueAt(f.getAbsolutePath(), row, 0);
model.setValueAt(f.length(), row, 2);
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}
Accept Drag's "outside" of the table
The process is relativly the same, except now we can throw away the conditions that would have otherwise caused us to reject the drag/drop (obviously)
#Override
public synchronized void dragOver(DropTargetDragEvent dtde) {
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if (row < 0) {
table.clearSelection();
} else {
table.setRowSelectionInterval(row, row);
}
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
And the drop method
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
if (fileList.size() > 0) {
table.clearSelection();
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model = (DefaultTableModel) table.getModel();
for (Object value : fileList) {
if (value instanceof File) {
File f = (File) value;
if (row < 0) {
System.out.println("addRow");
model.addRow(new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
} else {
System.out.println("insertRow " + row);
model.insertRow(row, new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
row++;
}
}
}
}
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}
Note. This will insert rows at the drop point, push all the existing rows down OR if not dropped on an existing row, will add them to the end...
TEST CODE
This a full running example I used to test the code...
public class DropTable {
public static void main(String[] args) {
new DropTable();
}
public DropTable() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DropPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DropPane extends JPanel {
private JTable table;
private JScrollPane scroll;
private DefaultTableModel tm = new DefaultTableModel(new String[]{"File", "File Type", "Size", "Status"}, 0);
public DropPane() {
table = new JTable();
table.setShowGrid(true);
table.setShowHorizontalLines(true);
table.setShowVerticalLines(true);
table.setGridColor(Color.GRAY);
table.setModel(tm);
table.setFillsViewportHeight(true);
table.setPreferredSize(new Dimension(500, 300));
scroll = new JScrollPane(table);
table.setDropTarget(new DropTarget() {
#Override
public synchronized void dragOver(DropTargetDragEvent dtde) {
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if (row < 0) {
table.clearSelection();
} else {
table.setRowSelectionInterval(row, row);
}
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
if (fileList.size() > 0) {
table.clearSelection();
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model = (DefaultTableModel) table.getModel();
for (Object value : fileList) {
if (value instanceof File) {
File f = (File) value;
if (row < 0) {
model.addRow(new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
} else {
model.insertRow(row, new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
row++;
}
}
}
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}
});
add(scroll, BorderLayout.CENTER);
}
}
}

Related

What is causing my java awt and swing browser's back button to not function properly?

The actionForward and actionBack functions are both throwing IndexOutofBounds exceptions and I cannot figure out why? I was tasked with making a very simple web browser with function back and forward buttons as well as a url address bar. When the ArrayList pageList has a size of 2 the buttons work as intended. However, once the pageList has a size of 3 or more they break.
class Proj03RunnerHtmlHandler extends JFrame implements HyperlinkListener{
JEditorPane html;
JButton backButton, forwardButton;
JTextField urlTextField;
ArrayList<String> pageList = new ArrayList<String>();
public Proj03RunnerHtmlHandler(String website) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Asg03");
pageList.add(website);
try{
if(website != null){
html = new JEditorPane(website);
html.setEditable(false);
html.addHyperlinkListener(this);
JPanel buttonPanel = new JPanel();
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionBack();
}
});
buttonPanel.add(backButton);
urlTextField = new JTextField("http://www.somesite.com");
urlTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
showPage(new URL(urlTextField.getText()), true);
} catch(Exception ey){
ey.printStackTrace();
}
}
}
});
buttonPanel.add(urlTextField);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionForward();
}
});
buttonPanel.add(forwardButton);
JScrollPane scroller = new JScrollPane();
JViewport vp = scroller.getViewport();
vp.add(html);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(scroller, BorderLayout.CENTER);
this.setSize(669,669);
this.setVisible(true);
}
} catch(Exception e){
e.printStackTrace();
}
}
public void hyperlinkUpdate(HyperlinkEvent e){
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED){
if (!(e instanceof HTMLFrameHyperlinkEvent)) {
try {
showPage(e.getURL(), true);
} catch(Exception ex){
ex.printStackTrace();
}
}
}
}
public void actionBack() {
try {
String currentUrl = html.getPage().toString();
int currentIndex = pageList.indexOf(currentUrl);
showPage(new URL(pageList.get(currentIndex - 1)), false);
} catch (Exception e){
e.printStackTrace();
}
}
public void actionForward() {
try {
String currentUrl = html.getPage().toString();
int currentIndex = pageList.indexOf(currentUrl);
showPage(new URL(pageList.get(currentIndex + 1)), false);
} catch (Exception e){
e.printStackTrace();
}
}
public void showPage(URL pageUrl, boolean addToList){
try {
URL currentUrl = html.getPage();
html.setPage(pageUrl);
if (addToList) {
int listSize = pageList.size();
if (listSize > 0) {
int pageIndex =
pageList.indexOf(currentUrl.toString());
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
}
pageList.add(pageUrl.toString());
}
urlTextField.setText(pageUrl.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
There's two obvious problems with this.
You should be removing only one page from the history.
If the page is at the end (pageIndex == listSize - 1), then you don't remove the page but do add a duplicate.

Refresh the JTable on updating the data

Below is my code:-
public class MainScreen extends javax.swing.JFrame {
private TableRowSorter<TableModel> sorter;
public MainScreen() {
initComponents();
this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
sorter = new TableRowSorter<>(tblCustomer.getModel());
tblCustomer.setRowSorter(sorter);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
System.out.println("I'm here "+findAll.size());
((DefaultTableModel) tblCustomer.getModel()).setDataVector(getDataVector(findAll), getVectorHeader());
tblCustomer.setAutoCreateRowSorter(true);
tblCustomer.getColumnModel().getColumn(0).setMinWidth(0);
tblCustomer.getColumnModel().getColumn(0).setMaxWidth(0);
}
public static Vector getDataVector(List<BasicDetailsDTO> listData) {
Vector dataVector = new Vector();
for (BasicDetailsDTO instance : listData) {
Vector row = new Vector();
row.add(instance.getId());
row.add(instance.getParticulars());
row.add(instance.getBookedBy());
row.add(instance.getContactPerson());
row.add(instance.getMobileNo());
row.add(instance.getEmail_id());
dataVector.add(row);
}
return dataVector;
}
public static Vector getVectorHeader() {
Vector header = new Vector();
header.add("ID");
header.add("Particulars");
header.add("BOOKED BY");
header.add("CONTACT PERSON");
header.add("MOBILE NO");
header.add("EMAIL ID");
return header;
}
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new HomePage(), "Details Of Customer", 1200, 800);
}
private void tblCustomerKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void tblCustomerMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please Select the Record");
return;
}
int option = displayConfirmDialog("Do you Really want to delete Record ?");
if (option == JOptionPane.YES_OPTION) {
String recordId = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordId));
instance.setDeleted(Boolean.TRUE);
UtilDAO.getDaoBasicDetails().remove(instance);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
getDataVector(findAll);
displayMessage(" Record Deleted ");
}
}
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1200, 1000);
}
private void tblCustomerMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() == 2) {
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1000, 1000);
}
}
private void btnViewHotelListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewHotelDetails(), "List Of Hotels", 800, 700);
}
private void btnViewAgencyListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewAgencyDetails(), "List Of Hotels", 800, 700);
}
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if (evt.getKeyCode() != KeyEvent.VK_ENTER && evt.getKeyCode() != KeyEvent.VK_DOWN) {
if (txtSearch.getText().trim().length() > 0) {
RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
#Override
public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
String search = txtSearch.getText().trim().toLowerCase();
// System.out.println(entry.getStringValue(1));
return (entry.getValue(1).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(2).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(3).toString().toLowerCase().indexOf(search) != -1);
}
};
sorter.setRowFilter(filter);
//sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
// System.out.println("New Row is " + filter);
} else {
sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
}
} else {
if (tblCustomer.getRowCount() > 0) {
tblCustomer.requestFocus();
tblCustomer.setRowSelectionInterval(0, 0);
} else {
txtSearch.requestFocus();
}
}
}
private void btnInvoiceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
InputStream in = MainScreen.class.getResourceAsStream("Passenger_Name.docx");
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
IContext context = report.createContext();
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
context.put("Customer", instance);
OutputStream out = new FileOutputStream(new File("Passenger Name_Out.docx"));
report.process(context, out);
Desktop desktop = Desktop.getDesktop();
File f = new File("Passenger Name_Out.docx");
desktop.open(f);
} catch (IOException | XDocReportException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
new MainScreen().setVisible(true);
}
});
}
public static void setlblMessageDetail(String msg) {
MainScreen.lblMessage.setHorizontalAlignment(JLabel.CENTER);
MainScreen.lblMessage.setText(msg);
}
// Variables declaration - do not modify
}
Whenever I update the data within the table, the updated data is not reflected. The updated data is reflected only when I reopen the window.
Kindly help me through.
Thanks in advance.
why voids for DefaultTableModel and JTableHeader are static
remove rows from DefaultTableModel
use DocumentListener instead of KeyListener for RowFilter
why is there initialized two different LookAndFeels
updates to DefaultTableModel must be done on EDT, more in Oracle tutorial Concurrency in Swing - The Event Dispatch Thread
search for ResultSetTableModel, TableFromDatabase, BeanTableModel
rest of issue is hidden in shadowing void or classes, note remove all static declare, there should be static only main class

Nimbus L & F: Setting different background colors of a Check-Boxes in a CheckBox List

I had a list of check-boxes and I want to set different colors on each check-box.
Following code does not change the background color
checkBox[i] = new JCheckBox();
checkBox[i].setEnabled(false);
checkBox[i].setBackground(Color.GREEN);
Kindly let me know way of setting background color
for example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.event.*;
public class JListDisabledItemDemo implements ItemListener, Runnable {
private JFrame f = new JFrame("Colors");
private static final String ITEMS[] = {" black ", " blue ", " green ",
" orange ", " purple ", " red ", " white ", " yellow "};
private JList jList;
private JCheckBox[] checkBoxes;
private boolean[] enabledFlags;
#Override
public void run() {
JPanel pnlEnablers = new JPanel(new GridLayout(0, 1));
pnlEnablers.setBorder(BorderFactory.createTitledBorder("Enabled Items"));
checkBoxes = new JCheckBox[ITEMS.length];
enabledFlags = new boolean[ITEMS.length];
for (int i = 0; i < ITEMS.length; i++) {
checkBoxes[i] = new JCheckBox(ITEMS[i]);
checkBoxes[i].setSelected(true);
checkBoxes[i].addItemListener(this);
enabledFlags[i] = true;
pnlEnablers.add(checkBoxes[i]);
}
jList = new JList(ITEMS);
jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jList.setSelectionModel(new DisabledItemSelectionModel());
jList.setCellRenderer(new DisabledItemListCellRenderer());
jList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println("selection");
}
}
});
JScrollPane scroll = new JScrollPane(jList);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(1, 2));
contentPane.add(pnlEnablers);
contentPane.add(scroll);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocation(240, 280);
UIManager.put("List.background", Color.lightGray);
UIManager.put("List.selectionBackground", Color.orange);
UIManager.put("List.selectionForeground", Color.blue);
UIManager.put("Label.disabledForeground", Color.magenta);
SwingUtilities.updateComponentTreeUI(f);
f.pack();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
f.setVisible(true);
}
});
}
#Override
public void itemStateChanged(ItemEvent event) {
JCheckBox checkBox = (JCheckBox) event.getSource();
int index = -1;
for (int i = 0; i < ITEMS.length; i++) {
if (ITEMS[i].equals(checkBox.getText())) {
index = i;
break;
}
}
if (index != -1) {
enabledFlags[index] = checkBox.isSelected();
jList.repaint();
}
}
public static void main(String args[]) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
System.out.println(info.getName());
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (ClassNotFoundException e) {
// handle exception
} catch (InstantiationException e) {
// handle exception
} catch (IllegalAccessException e) {
// handle exception
}
SwingUtilities.invokeLater(new JListDisabledItemDemo());
}
private class DisabledItemListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component comp = super.getListCellRendererComponent(list, value, index, false, false);
JComponent jc = (JComponent) comp;
if (enabledFlags[index]) {
if (isSelected & cellHasFocus) {
comp.setForeground(Color.black);
comp.setBackground(Color.red);
} else {
comp.setBackground(Color.white);
comp.setForeground(Color.black);
}
if (!isSelected) {
if ((value.toString()).trim().equals("yellow")) {
comp.setForeground(Color.blue);
comp.setBackground(Color.yellow);
} else if ((value.toString()).trim().equals("black")) {
comp.setForeground(Color.red);
comp.setBackground(Color.black);
}else if ((value.toString()).trim().equals("orange")) {
comp.setForeground(Color.blue);
comp.setBackground(Color.orange);
}
}
return comp;
}
comp.setEnabled(false);
return comp;
}
}
private class DisabledItemSelectionModel extends DefaultListSelectionModel {
private static final long serialVersionUID = 1L;
#Override
public void setSelectionInterval(int index0, int index1) {
if (enabledFlags[index0]) {
super.setSelectionInterval(index0, index0);
} else {
/*The previously selected index is before this one,
* so walk forward to find the next selectable item.*/
if (getAnchorSelectionIndex() < index0) {
for (int i = index0; i < enabledFlags.length; i++) {
if (enabledFlags[i]) {
super.setSelectionInterval(i, i);
return;
}
}
} /*
* Otherwise, walk backward to find the next selectable item.
*/ else {
for (int i = index0; i >= 0; i--) {
if (enabledFlags[i]) {
super.setSelectionInterval(i, i);
return;
}
}
}
}
}
}
}
Try setting your CheckBox Opacity to true.
myCheckBox.setOpaque(true);

Need to identify SwingWorker completion to stop the current process?

My aim is to select all the files named with MANI.txt which is present in their respective folders and then load path of the MANI.txt files different location in table. After I load the path in the table,I used to select needed path and modifiying those.
To load the MANI.txt files taking more time,because it may present more than 30 times in my workspace or etc. until load the files I want to give alarm to the user with help of ProgessBar.Once the list size has been populated I need to disable ProgressBar.
i came up with this ProgressBar, but progress bar operation gets complete or not, if the background process(finding files and putting their path in the table) got completed means, the result getting displayed and hiding the progress bar? i want the presence of progress bar opertion gets complete 100% in either case? please give me some ideas?how to implement it?
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class JTableHeaderCheckBox extends JFrame implements ActionListener {
protected int counter = 0;
Object colNames[] = { "", "Path" };
Object[][] data = {};
DefaultTableModel dtm;
JTable table;
JButton but;
java.util.List list;
File folder;
JProgressBar current;
JFrame fr1, frame;
int num = 0;
JProgressBar pbar;
JTableHeaderCheckBox it;
public void buildGUI() throws InterruptedException {
dtm = new DefaultTableModel(data, colNames);
table = new JTable(dtm);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int width = 10;
col.setPreferredWidth(width);
int vColIndex1 = 1;
TableColumn col1 = table.getColumnModel().getColumn(vColIndex1);
int width1 = 500;
col1.setPreferredWidth(width1);
JFileChooser chooser = new JFileChooser();
// chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose workSpace Path");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
}
String path = chooser.getSelectedFile().getAbsolutePath();
folder = new File(path);
but = new JButton("REMOVE");
SwingWorker worker = new SwingWorker() {
#Override
public Object doInBackground() {
GatheringFiles ob = new GatheringFiles();
list = ob.returnlist(folder);
return list;
}
#Override
protected void done() {
// java.util.List list = (java.util.List)get();
for (int x = 0; x < list.size(); x++) {
dtm.addRow(new Object[] { new Boolean(false),
list.get(x).toString() });
}
try {
JPanel pan = new JPanel();
JScrollPane sp = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
tc.setHeaderRenderer(new CheckBoxHeader(
new MyItemListener()));
JFrame f = new JFrame();
pan.add(sp);
pan.add(but);
f.add(pan);
f.setSize(700, 100);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
if (list.size() >= 0) {
// hide the progress bar
frame.hide();
}
} catch (Exception ex) {
}
}
};
worker.execute();
but.addActionListener(this);
//calling progressbar
if(!path.isEmpty())
{
SwingProgressBar();
}
}
public void SwingProgressBar() {
UIManager.put("ProgressBar.selectionBackground", Color.black);
UIManager.put("ProgressBar.selectionForeground", Color.white);
UIManager.put("ProgressBar.foreground", new Color(8, 32, 128));
pbar = new JProgressBar();
pbar.setMinimum(0);
pbar.setMaximum(100);
pbar.setForeground(Color.RED);
pbar.setStringPainted(true);
it = new JTableHeaderCheckBox();
frame = new JFrame("Loading");
final JLabel lb = new JLabel("0");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setContentPane(it);
frame.add(pbar);
frame.pack();
frame.setVisible(true);
counter = 0;
Thread runner = new Thread() {
public void run() {
counter = 0;
while (counter <= 99) {
Runnable runme = new Runnable() {
public void run() {
pbar.setValue(counter);
}
};
SwingUtilities.invokeLater(runme);
counter++;
try {
Thread.sleep(1000);
} catch (Exception ex) {
}
}
}
};
runner.start();
}
public void updateBar(int newValue) {
pbar.setValue(newValue);
}
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
if (source instanceof AbstractButton == false)
return;
boolean checked = e.getStateChange() == ItemEvent.SELECTED;
for (int x = 0, y = table.getRowCount(); x < y; x++) {
table.setValueAt(new Boolean(checked), x, 0);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new JTableHeaderCheckBox().buildGUI();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (Exception ex) {
}
}
});
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == but) {
System.err.println("table.getRowCount()" + table.getRowCount());
for (int x = 0, y = table.getRowCount(); x < y; x++) {
if ("true".equals(table.getValueAt(x, 0).toString())) {
System.err.println(table.getValueAt(x, 0));
System.err.println(list.get(x).toString());
delete(list.get(x).toString());
}
}
}
}
public void delete(String a) {
String delete = "C:";
System.err.println(a);
try {
File inFile = new File(a);
if (!inFile.isFile()) {
return;
}
// Construct the new file that will later be renamed to the // filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
while ((line = br.readLine()) != null) {
System.err.println(line);
line = line.replace(delete, " ");
pw.println(line);
pw.flush();
}
pw.close();
br.close();
// Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class CheckBoxHeader extends JCheckBox implements TableCellRenderer,
MouseListener {
protected CheckBoxHeader rendererComponent;
protected int column;
protected boolean mousePressed = false;
public CheckBoxHeader(ItemListener itemListener) {
rendererComponent = this;
rendererComponent.addItemListener(itemListener);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (table != null) {
JTableHeader header = table.getTableHeader();
if (header != null) {
rendererComponent.setForeground(header.getForeground());
rendererComponent.setBackground(header.getBackground());
rendererComponent.setFont(header.getFont());
header.addMouseListener(rendererComponent);
}
}
setColumn(column);
rendererComponent.setText("Check All");
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return rendererComponent;
}
protected void setColumn(int column) {
this.column = column;
}
public int getColumn() {
return column;
}
protected void handleClickEvent(MouseEvent e) {
if (mousePressed) {
mousePressed = false;
JTableHeader header = (JTableHeader) (e.getSource());
JTable tableView = header.getTable();
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (viewColumn == this.column && e.getClickCount() == 1
&& column != -1) {
doClick();
}
}
}
public void mouseClicked(MouseEvent e) {
handleClickEvent(e);
((JTableHeader) e.getSource()).repaint();
}
public void mousePressed(MouseEvent e) {
mousePressed = true;
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
//
import java.io.File;
import java.util.*;
public class GatheringFiles {
public static List returnlist(File folder)
{
List<File> list = new ArrayList<File>();
List<File> list1 = new ArrayList<File>();
getFiles(folder, list);
return list;
}
private static void getFiles(File folder, List<File> list) {
folder.setReadOnly();
File[] files = folder.listFiles();
for(int j = 0; j < files.length; j++) {
if( "MANI.txt".equals(files[j].getName()))
{
list.add(files[j]);
}
if(files[j].isDirectory())
getFiles(files[j], list);
}
}
}

How can I make a suggestion List in my Autocomplete application?

I am making an autocomplete application and the list of my words are coming from my database. I have a textfield and now I want to make a suggestion list that will appear below the field everytime I type something. Could you give me some hint or idea how to do it? Thanks in advance.
Much better if you use JCombobox but if you are using Jtextfield, I would rather suggest to you to use Jlist and put in JWindow since you are using textfield, thats what I've tried in my Dictionary application.
EDIT :
public class MainMenu extends JPanel
{
private final Connection connection;
private final Application application;
private JTextField word = new JTextField(10);
private final JButton translate = new JButton();
private final JComboBox translators = new JComboBox();
private final JButton search = new JButton();
private JList speechPartAndDefinitionWidget;
private final DefaultListModel speechPartAndDefinitionWidgetModel = new DefaultListModel();
private Translator translator;
private Suggestor suggestor;
private DefaultListModel translatedWidgetModel;
private JList translatedWidget;
private final DefaultListModel suggestionWidgetModel = new DefaultListModel();
private final JList suggestionWidget = new JList(suggestionWidgetModel);
private JavaWindow javaWindow = new JavaWindow(suggestionWidget);
public MainMenu(Application application, Connection connection)
{
word.getDocument().addDocumentListener(new DocumentListener()
{
public void insertUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
public void removeUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
public void changedUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
this.application = application;
this.connection = connection;
translators.setFocusable(false);
word.grabFocus();
word.requestFocus();
word.setFocusable(true);
search.setText("<html><b><u>S</u>earch</b></html>");
translate.setText("<html><b><u>T</u>ranslate</b></html>");
translators.addItem(new EnglishBisayaTranslator(connection));
setToolTipText("English-Bisaya");
translators.addItem(new BisayaEnglishTranslator(connection));
setToolTipText("Bisaya-English");
setLayout(new BorderLayout());
JPanel formX = new JPanel();
formX.setLayout(new BorderLayout());
JPanel header = new JPanel();
header.setLayout(new GridBagLayout());
header.add(translators);
header.add(word);
header.add(search);
header.add(translate);
translators.setBorder(BorderFactory.createEtchedBorder(1));
translators.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
word.setBorder(BorderFactory.createEtchedBorder());
word.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
word.setFont(new Font("Garamond", Font.BOLD, 17));
suggestionWidget.setFont(new Font("Calibri", Font.BOLD, 17));
header.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 8));
formX.add(BorderLayout.PAGE_START, header);
formX.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 10));
add(header, BorderLayout.NORTH);
speechPartAndDefinitionWidget = new JList(speechPartAndDefinitionWidgetModel);
speechPartAndDefinitionWidget.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
speechPartAndDefinitionWidget.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent ev)
{
onDefinitionSelected(ev);
}
});
JPanel formBottom = new JPanel();
formBottom.setLayout(new GridBagLayout());
add(formBottom, BorderLayout.CENTER);
Component up = new JScrollPane(speechPartAndDefinitionWidget);
formBottom.setBorder(BorderFactory.createEmptyBorder(20, 10, 10, 10)); speechPartAndDefinitionWidget.setBorder(BorderFactory.createLineBorder(Color.black,1));
JPanel down = new JPanel();
down.setLayout(new BorderLayout());
down.setBorder(BorderFactory.createLineBorder(Color.black, 1));
down.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
down.add(translatedWidget = new JList(translatedWidgetModel = new DefaultListModel()));
add(down, BorderLayout.CENTER);
translatedWidget.setBorder(BorderFactory.createLineBorder(Color.black, 1));
translatedWidget.setFont(new Font("Calibri",Font.BOLD, 17));
speechPartAndDefinitionWidget.setFont(new Font("Calibri", Font.BOLD, 17));
add(BorderLayout.CENTER, new JSplitPane(JSplitPane.VERTICAL_SPLIT, up, down));
word.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
hideSuggestionWindowToBack();
}
else if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
int selectedIndex = suggestionWidget.getSelectedIndex();
if (selectedIndex == -1)
{
onSearchClick();
}
else
{
onSuggestionSelected(selectedIndex);
}
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
hideSuggestionWindowToBack();
onSearchClick();
}
}
});
translators.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent e)
{
onTranslatorsClick();
}
}
);
word.addKeyListener(new
KeyAdapter()
{
public void keyPressed
(KeyEvent
e)
{
if (suggestionWidgetModel.isEmpty())
{
return;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
final Point location = word.getLocationOnScreen();
javaWindow.setLocation(location.x, location.y + word.getHeight());
showSuggestionWindowToBack();
int currentSelectedItemIndex = suggestionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == suggestionWidgetModel.size() - 1)
{
suggestionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < suggestionWidgetModel.size() - 1)
{
suggestionWidget.setSelectedIndex(currentSelectedItemIndex + 1);
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
int currentSelectedItemIndex = suggestionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == suggestionWidgetModel.size() + 1)
{
suggestionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < suggestionWidgetModel.size() + 1)
{
suggestionWidget.setSelectedIndex(currentSelectedItemIndex - 1);
}
}
}
}
);
suggestionWidget.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
int selectedIndex = suggestionWidget.getSelectedIndex();
if (e.getClickCount() == 2)
{
if (selectedIndex < -1)
{
onSearchClick();
}
else
{
onSuggestionSelected(selectedIndex);
hideSuggestionWindowToBack();
}
}
}
public void mouseReleased(MouseEvent e)
{
if (e.getClickCount() == 2)
{
{
hideSuggestionWindowToBack();
}
}
}
});
speechPartAndDefinitionWidget.addKeyListener(new
KeyAdapter()
{
#Override
public void keyPressed
(KeyEvent
e)
{
if (speechPartAndDefinitionWidgetModel.isEmpty())
{
return;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
int currentSelectedItemIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == speechPartAndDefinitionWidgetModel.size() - 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < speechPartAndDefinitionWidgetModel.size() - 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(currentSelectedItemIndex + 1);
onTranslate();
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
int currentSelectedItemIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == speechPartAndDefinitionWidgetModel.size() + 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < speechPartAndDefinitionWidgetModel.size() + 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(currentSelectedItemIndex - 1);
}
}
}
}
);
speechPartAndDefinitionWidget.addMouseMotionListener(new MouseMotionAdapter()
{
#Override
public void mouseMoved(MouseEvent e)
{
final int x = e.getX();
final int y = e.getY();
final Rectangle cellBounds = speechPartAndDefinitionWidget.getCellBounds(0, speechPartAndDefinitionWidget.getModel().getSize() - 1);
if (cellBounds != null && cellBounds.contains(x, y))
{
speechPartAndDefinitionWidget.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
else
{
speechPartAndDefinitionWidget.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}
);
speechPartAndDefinitionWidget.setCellRenderer(new
DefaultListCellRenderer()
{
#Override
public Component getListCellRendererComponent
(JList
list, Object
value, int index,
boolean isSelected,
boolean cellHasFocus)
{
final String speechPart = ((DefinitionUiModel) value).getPart().getFriendlyName();
final String definition = ((DefinitionUiModel) value).getDefinition().toString();
Color bg = null;
Color fg = null;
final JLabel renderer = new JLabel(
"<html><font color=red>" + speechPart + "</font>) => <font color=black>" + definition + "</font></html>");
if (renderer.isEnabled())
{
if (isSelected)
{
renderer.setText("<html><font color=gray>" + speechPart + "</font><font color=blue><u><b>" + definition + "</b></u></font></html>");
renderer.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index)
{
bg = DefaultLookup.getColor(this, ui, "List.dropCellBackground");
fg = DefaultLookup.getColor(this, ui, "List.dropCellForeground");
isSelected = true;
}
if (isSelected)
{
renderer.setBackground(bg == null ? list.getSelectionBackground() : bg);
renderer.setForeground(fg == null ? list.getSelectionForeground() : fg);
}
Border border = null;
if (cellHasFocus)
{
if (isSelected)
{
border = DefaultLookup.getBorder(this, ui, "List.focusSelectedCellHighlightBorder");
}
if (border == null)
{
border = DefaultLookup.getBorder(this, ui, "List.focusCellHighlightBorder");
}
}
else
{
}
}
return renderer;
}
}
);
translatedWidget.setForeground(Color.black);
translate.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent
e)
{
onTranslate();
}
}
);
search.setToolTipText("find");
search.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent
e)
{
onSearchClick();
}
}
);
translators.setSelectedIndex(0);
suggestionWidget.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
onTranslatorsClick();
}
private void onSuggestionSelected(int selectedIndex)
{
String hold = (String) suggestionWidgetModel.getElementAt(selectedIndex);
word.setText(hold);
hideSuggestionWindowToBack();
suggestionWidgetModel.clear();
if (javaWindow == null)
{
javaWindow.dispose();
javaWindow = null;
}
}
public void onWordUpdated(final String toComplete) throws ClassNotFoundException, SQLException
{
new Thread(new Runnable()
{
public void run()
{
try
{
final List<Suggestion> suggestions = suggestor.getSuggestions(toComplete);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
speechPartAndDefinitionWidgetModel.clear();
translatedWidgetModel.clear();
suggestionWidgetModel.clear();
try
{
for (Suggestion suggestion : suggestions)
{
suggestionWidgetModel.addElement(suggestion.getCaption());
}
if (!suggestions.isEmpty())
{
suggestionWidget.setSelectedIndex(0);
if (javaWindow == null)
{
javaWindow = new JavaWindow(suggestionWidget);
}
else
{
final Point location = word.getLocationOnScreen();
javaWindow.setLocation(location.x, location.y + word.getHeight());
}
showSuggestionWindowToBack();
}
else
{
hideSuggestionWindowToBack();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
});
}
catch (SQLException e)
{
onSqlError(e);
}
}
}
, "onWordUpdated").
start();
}
private void onTranslate()
{
try
{
translatedWidgetModel.clear();
String lookupWord = word.getText();
if (lookupWord != null)
{
Collection<String> bisayaWords = this.translator.translateSimple(lookupWord);
for (String bisayaWord : bisayaWords)
{
translatedWidgetModel.addElement(bisayaWord.toUpperCase());
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onSqlError(SQLException ex)
{
JOptionPane.showMessageDialog(null, "SQL Error! :" + ex.getMessage());
}
private void onDefinitionSelected(ListSelectionEvent ev)
{
if (!ev.getValueIsAdjusting())
{
int selectedIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (selectedIndex != -1)
{
final DefinitionUiModel definitionUiModel = (DefinitionUiModel) speechPartAndDefinitionWidgetModel.get(selectedIndex);
translate(definitionUiModel.getDefinition());
}
}
}
private void translate(Definition definition)
{
try
{
translatedWidgetModel.clear();
Map<String, String> map = new HashMap<String, String>();
int definitionId = definition.getId();
String definitionName = definition.getValue();
int nameId = translator.getFromDictionary().getNameIdForDefinitionId(definitionId);
if (nameId > -1)
{
final Collection<String> translation = translator.translateSimple(nameId);
for (String transWord : translation)
{
map.put(transWord, definitionName);
for (Map.Entry<String, String> entry : map.entrySet())
{
String myValue = entry.getKey().toUpperCase() + " -- " + entry.getValue();
translatedWidgetModel.addElement(myValue);
}
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onSearchClick()
{
search.setEnabled(true);
hideSuggestionWindowToBack();
speechPartAndDefinitionWidgetModel.clear();
translatedWidgetModel.clear();
try
{
final String lookupWord = word.getText();
if (lookupWord != null)
{
final Dictionary fromDictionary = translator.getFromDictionary();
final WordDefinitions definitions = fromDictionary.getWordDefinitions(lookupWord);
final Iterator<Map.Entry<SpeechPart, List<Definition>>> items = definitions.iterator();
while (items.hasNext())
{
final Map.Entry<SpeechPart, List<Definition>> item = items.next();
for (Definition definition : item.getValue())
{
speechPartAndDefinitionWidgetModel.addElement(new DefinitionUiModel(item.getKey(), definition));
}
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onTranslatorsClick()
{
translator = (Translator) translators.getSelectedItem();
suggestor = new Suggestor(translator.getFromDictionary(), 10);
word.setEnabled(true);
application.setTitle(translator.toString());
translators.setToolTipText("tooltip : " + translator.toString());
speechPartAndDefinitionWidgetModel.clear();
}
private void hideSuggestionWindowToBack()
{
if (javaWindow == null)
{
return;
}
javaWindow.setVisible(false);
javaWindow.toBack();
}
private void showSuggestionWindowToBack()
{
if (javaWindow == null)
{
return;
}
javaWindow.setVisible(true);
javaWindow.toFront();
}
}
The algorithm (that I know of) behind the suggestions list is: Longest common substring problem. The problem is quite easy if you have stored the strings in the database in the form of a trie. Then the list of suggestions for the current prefix will be all those strings that start with the currently entered string. You will understand what I mean if you look at the Trie data structure.

Categories