Java: How do I get the text of two JLabels when copying JLabel's text with TransferHandler? - copy

How do I get the text of two JLabels when copying JLabel's text with TransferHandler?
Label1111111 How can I keep the text of both JLabels when copied to Label2222222.
For this reason, I will take control of two Jlabel's texts. This shape can only get the text of JLabel, which was first held. Thank you in advance for your help.
public class deneme2 extends JFrame {
private static final int COPY = 0;
private static final int NONE = 0;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
deneme2 frame = new deneme2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public deneme2() {
JPanel panel= new JPanel();
MouseListener listener = new DragMouseAdapter();
JLabel label1 = new JLabel("Label1111111", JLabel.CENTER);
handlerLabel(label1);
label1.addMouseListener(listener);
panel.add(label1);
JLabel label2 = new JLabel("Label2222222", JLabel.CENTER);
handlerLabel(label2);
label2.addMouseListener(listener);
panel.add(label2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.add(panel);
setContentPane(contentPane);
}
private void handlerLabel (JLabel lbl)
{
lbl.setTransferHandler(new TransferHandler("text") {
#Override
protected void exportDone(JComponent source, Transferable data, int action) {
if (action == COPY){
((JLabel)lbl.getDropTarget().getDropTargetContext().getComponent()).getText();
//((JLabel) source).setText("LabelEmpty");
}
}
});
}
private class DragMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
JComponent comp = (JComponent)e.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, e, TransferHandler.COPY);
}
}
}

Maybe in this way. I added inner class MyLabel and console output in your handlerLabel. Ctrl+v this under your main. It will print to console the original String property of each MyLabels.
public class MyLabel extends JLabel {
String original;
public MyLabel (String text)
{
super(text);
this.original=text;
}
public String getOriginal() {
return original;
}
public void setOriginal(String original) {
this.original = original;
}
}
public deneme2() {
JPanel panel= new JPanel();
MouseListener listener = (MouseListener) new DragMouseAdapter();
MyLabel label1 = new MyLabel("Label1111111");
handlerLabel(label1);
label1.addMouseListener(listener);
panel.add(label1);
MyLabel label2 = new MyLabel("Label2222222");
handlerLabel(label2);
label2.addMouseListener(listener);
panel.add(label2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.add(panel);
setContentPane(contentPane);
}
private void handlerLabel(MyLabel lbl) {
lbl.setTransferHandler(new TransferHandler("text") {
#Override
protected void exportDone(JComponent source, Transferable data, int action) {
if (action == COPY) {
System.out.println(((MyLabel) lbl.getDropTarget().getDropTargetContext().getComponent()).getOriginal());
}
}
});
}
Edit: check this out. Ctrl+V this under your main. It will print to console text of source label and text of target label, also the original property. Class MyLabel implements DropTargetListener , which is then registered by new DropTarget(this, this). Then we define what will happen in overriden drop method.
public class MyLabel extends JLabel implements DropTargetListener {
String original;
public MyLabel(String text) {
super(text);
this.original = text;
new DropTarget(this, this);
this.setTransferHandler(new TransferHandler("text"));
final MouseListener listener = new MouseAdapter() {
#Override
public void mousePressed(final MouseEvent me) {
final MyLabel label = (MyLabel) me.getSource();
final TransferHandler handler = label.getTransferHandler();
handler.exportAsDrag(label, me, TransferHandler.COPY);
}
};
this.addMouseListener(listener);
}
public String getOriginal() {
return original;
}
public void setOriginal(String original) {
this.original = original;
}
#Override
public void dragEnter(DropTargetDragEvent dtde) {
}
#Override
public void dragOver(DropTargetDragEvent dtde) {
}
#Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
#Override
public void dragExit(DropTargetEvent dte) {
}
#Override
public void drop(DropTargetDropEvent dtde) {
try {
final String sourceString = (String) dtde.getTransferable().getTransferData(new DataFlavor("application/x-java-jvm-local-objectref; class=java.lang.String"));
System.out.println("Source: " + sourceString + " target: " + this.getText());
this.setText(sourceString);
System.out.println("Original target: "+this.getOriginal());
} catch (final UnsupportedFlavorException | IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public deneme2() {
JPanel panel = new JPanel();
MyLabel label1 = new MyLabel("Label1111111a");
panel.add(label1);
MyLabel label2 = new MyLabel("Label2222222b");
panel.add(label2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.add(panel);
setContentPane(contentPane);
}
}
EDIT2: Following code generates this result see result at the end of this answer:
or
It also prints original property to console. Those could be organised differently (MyLabel, MyLabelTransferable, MyLabelDropTargetListener, MyLabelTransferHandler classes, just to give an idea for future refactoring) but it works in this way too. Consider it a quickfix for your use case.
So main class is this:
public class Deneme2 extends JFrame {
private static final int COPY = 0;
private static final int NONE = 0;
public static void main(String[] args) {
Deneme2 mainFrame = new Deneme2();
SwingUtilities.invokeLater(() -> {//let's get that frame on EDT rollin lambda style:)
mainFrame.setVisible(true);
});
}
public Deneme2() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
MyLabel label1 = new MyLabel("Label1111111a");
panel.add(label1, BorderLayout.WEST);
MyLabel label2 = new MyLabel("Label2222222b");
panel.add(label2, BorderLayout.EAST);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 450, 300);
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
this.add(panel);
}
}
Then MyLabel.java :
public class MyLabel extends JLabel implements DropTargetListener, Transferable {
String original;
protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=\"" + MyLabel.class.getCanonicalName() + "\"",
"MyLabel label");
protected static final DataFlavor[] SUPPORTED_FLAVORS = {MYLABEL_DATA_FLAVOR};
public MyLabel(String text) {
super(text);
this.original = text;
new DropTarget(this, this);
this.setTransferHandler(new MyLabelTransferHandler()); //here we use our custom TransferHandler
final MouseListener listener = new MouseAdapter() {
#Override
public void mousePressed(final MouseEvent me) {
final MyLabel label = (MyLabel) me.getSource();
final TransferHandler handler = label.getTransferHandler();
handler.exportAsDrag(label, me, TransferHandler.COPY);
}
};
this.addMouseListener(listener);
}
public String getOriginal() {
return original;
}
public void setOriginal(String original) {
this.original = original;
}
#Override
public void dragEnter(DropTargetDragEvent dtde) {
if (dtde.getTransferable().isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
System.out.println("Drop accept - MyLabel");
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
dtde.rejectDrag();
}
}
#Override
public void dragOver(DropTargetDragEvent dtde) {
//System.out.println("Drag over");
}
#Override
public void dropActionChanged(DropTargetDragEvent dtde) {
System.out.println("Action changed");
}
#Override
public void dragExit(DropTargetEvent dte) {
System.out.println("Exited");
}
#Override
public void drop(DropTargetDropEvent dtde) {
System.out.println("Drop detected");
if (dtde.getTransferable().isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
Transferable t = dtde.getTransferable();
if (t.isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
try {
Object transferData = t.getTransferData(MyLabel.MYLABEL_DATA_FLAVOR);
if (transferData instanceof MyLabel) {
MyLabel mySourceLabel = (MyLabel) transferData;
if (!(mySourceLabel.equals(this))) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
this.setText(mySourceLabel.getText());
mySourceLabel.setText("Empty");
System.out.println(mySourceLabel.getOriginal() + " " + this.getOriginal());
} else {
dtde.rejectDrop();
System.out.println("Drop rejected - the same MyLabel");
}
} else {
dtde.rejectDrop();
}
} catch (UnsupportedFlavorException | IOException ex) {
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}
}
#Override
public DataFlavor[] getTransferDataFlavors() {
return SUPPORTED_FLAVORS;
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(MYLABEL_DATA_FLAVOR) || flavor.equals(DataFlavor.stringFlavor);
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (flavor.equals(MYLABEL_DATA_FLAVOR)) {
return this;
} else if (flavor.equals(DataFlavor.stringFlavor)) {
return this.getText();
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
And then MyLabelTransferHandler.java :
public class MyLabelTransferHandler extends TransferHandler {
#Override
public boolean canImport(TransferHandler.TransferSupport support) {
return (support.getComponent() instanceof MyLabel) && support.isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR);
}
#Override
public boolean importData(JComponent src, Transferable transferable) {
return src instanceof MyLabel;
}
#Override
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_COPY;
}
#Override
protected Transferable createTransferable(JComponent c) {
Transferable t = (MyLabel)c;
return t;
}
#Override
protected void exportDone(JComponent source, Transferable data, int action) {
System.out.println("Export done.");
}
}
After final edit result looks like this:
Little clarification:
protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=\"" + MyLabel.class.getCanonicalName() + "\"",
"MyLabel label");
in MyLabel. That's important line. This will make getTransferData() return the same instance of MyLabel. If you would do it like:
protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(MyLabel.class, "MyLabel label");
you won't be able to change mySourceLabel text to "Empty" in overridden drop() method, since you would be given a copy of that object.
Also Why shouldn't you extend JFrame and other components? . And you can provide checking for "Empty" text (if getText() returns "Empty", then don't change text in target MyLabel).

Related

Can you Drag and Drop a JButton copy?

Found a neat sample that really helped with illustrating how DnD works when it drags a values from a list and places it on the panel.
This sample grabs a copy of the list value.
I have since modified the sample to add a JButton. I can DnD this onto the panel but it moves it instead of making a copy.
Is there something specific as to why the JButton was moved instead of copied?
What change is required to have the button copied instead of moved?
I even tried pressing the CTRL key as I dragged the button but it still moved it instead of copying.
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.io.IOException;
import javax.swing.*;
public class TestDnD {
public static void main(String[] args) {
new TestDnD();
}
public TestDnD() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JList list;
public TestPane() {
setLayout(new BorderLayout());
list = new JList();
DefaultListModel model = new DefaultListModel();
model.addElement(new User("Shaun"));
model.addElement(new User("Andy"));
model.addElement(new User("Luke"));
model.addElement(new User("Han"));
model.addElement(new User("Liea"));
model.addElement(new User("Yoda"));
list.setModel(model);
add(new JScrollPane(list), BorderLayout.WEST);
//Without this call, the application does NOT recognize a drag is happening on the LIST.
DragGestureRecognizer dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
list,
DnDConstants.ACTION_COPY_OR_MOVE,
new DragGestureHandler(list)); ///DragGestureHandler - is defined below
///and really just implements DragGestureListener
///and the implemented method defines what is being transferred.
JPanel panel = new JPanel(new GridBagLayout());
add(panel);
//This registers the Target (PANEL) where the Drop is to occur.
DropTarget dt = new DropTarget(
panel,
DnDConstants.ACTION_COPY_OR_MOVE,
new DropTargetHandler(panel), ////DropTargetHandler - is defined below
true); ///and really just implements DropTargetListener
setupButtonTest();
}
private void setupButtonTest()
{
JButton myButton = new JButton("Drag Drop Me");
add(myButton, BorderLayout.NORTH);
DragGestureRecognizer dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
myButton,
DnDConstants.ACTION_COPY, // ACTION_COPY_OR_MOVE,
new DragGestureHandler(myButton)); ///DragGestureHandler - is defined below
///and really just implements DragGestureListener
///and the implemented method defines what is being transferred.
}
}
public static class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
////This Class handles the actual item or data being transferred (dragged).
public static class UserTransferable implements Transferable {
public static final DataFlavor JIMS_DATA_FLAVOR = new DataFlavor(User.class, "User");
private User user;
private JButton jbutton;
public UserTransferable(User user) {
this.user = user;
}
public UserTransferable(JButton user) {
this.jbutton = user;
}
#Override
public DataFlavor[] getTransferDataFlavors() {
//Executed as soon as the User Object is dragged.
System.out.println("UserTransferable : getTransferDataFlavors()");
return new DataFlavor[]{JIMS_DATA_FLAVOR};
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
//This is what is executed once the item is dragged into a JComponent that can accept it.
System.out.println("UserTransferable : isDataFlavorSupported()");
return JIMS_DATA_FLAVOR.equals(flavor);
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
//Once a Drop is done then this method provides the data to actually drop.
System.out.println("UserTransferable : getTransferData()");
Object value = null;
if (JIMS_DATA_FLAVOR.equals(flavor)) {
if (user != null)
value = user;
else if (jbutton != null)
value = jbutton;
} else {
throw new UnsupportedFlavorException(flavor);
}
return value;
}
}
protected class DragGestureHandler implements DragGestureListener {
private JList list;
private JButton button;
public DragGestureHandler(JList list) {
this.list = list;
}
public DragGestureHandler(JButton list) {
this.button = list;
}
#Override
public void dragGestureRecognized(DragGestureEvent dge) {
//This executes once the dragging starts.
System.out.println("DragGestureHandler : dragGesturRecognized()");
if (dge.getComponent() instanceof JList)
{
Object selectedValue = list.getSelectedValue();
if (selectedValue instanceof User) {
User user = (User) selectedValue;
Transferable t = new UserTransferable(user); ////This is where you define what is being transferred.
DragSource ds = dge.getDragSource();
ds.startDrag(
dge,
null,
t,
new DragSourceHandler());
}
}
else if (dge.getComponent() instanceof JButton)
{
Object selectedValue = dge.getComponent();
if (selectedValue instanceof JButton) {
JButton jb = button;
Transferable t = new UserTransferable(jb); ////This is where you define what is being transferred.
DragSource ds = dge.getDragSource();
ds.startDrag(
dge,
null,
t,
new DragSourceHandler());
}
}
}
}
protected class DragSourceHandler implements DragSourceListener {
public void dragEnter(DragSourceDragEvent dsde) {
//This means you have entered a possible Target.
System.out.println("DragSourceHandler : DragEnter()");
}
public void dragOver(DragSourceDragEvent dsde) {
//Continually executes while the DRAG is hovering over an potential TARGET.
System.out.println("DragSourceHandler : DragOver()");
}
public void dropActionChanged(DragSourceDragEvent dsde) {
}
public void dragExit(DragSourceEvent dse) {
//Executes once the potential target has been exited.
System.out.println("DragSourceHandler : DragExit()");
}
public void dragDropEnd(DragSourceDropEvent dsde) {
//Once the mouse button is lifted to do the drop.
//Executes against any potential drop.
System.out.println("DragSourceHandler : dragDropEnd()");
}
}
protected class DropTargetHandler implements DropTargetListener {
////THESE ARE EXECUTED ONLY WHEN THE MOUSE AND DRAGGED ITEM IS OVER THE TARGET.
private JPanel panel;
public DropTargetHandler(JPanel panel) {
this.panel = panel;
}
public void dragEnter(DropTargetDragEvent dtde) {
System.out.println("DropTargetHandler : dragEnter()");
if (dtde.getTransferable().isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
//This shows the outline within the TARGET to indicate it will accept the DROP.
System.out.println(" Accept...");
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
//If an item is not registered to accept a certain drop this is executed.
System.out.println(" DropTargetHandler : DragEnter() - Else");
dtde.rejectDrag();
}
}
public void dragOver(DropTargetDragEvent dtde) {
//Active while the item is being Dragged over the Target
System.out.println("DropTargetHandler : dragOver()");
}
public void dropActionChanged(DropTargetDragEvent dtde) {
System.out.println("DropTargetHandler : dropActionChanged()");
}
public void dragExit(DropTargetEvent dte) {
//Once the dragged item is taken out of the Target area.
System.out.println("DropTargetHandler : dragExit()");
}
public void drop(DropTargetDropEvent dtde) {
//Once the mouse button is released to do the Drop then this is executed.
System.out.println("DropTargetHandler : drop()");
if (dtde.getTransferable().isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
Transferable t = dtde.getTransferable();
if (t.isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
try {
Object transferData = t.getTransferData(UserTransferable.JIMS_DATA_FLAVOR);
if (transferData instanceof User) {
User user = (User) transferData;
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
panel.add(new JLabel(user.getName()));
panel.revalidate();
panel.repaint();
}
else if (transferData instanceof JButton) {
JButton jb = (JButton) transferData;
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
panel.add(jb);
panel.revalidate();
panel.repaint();
}
else {
dtde.rejectDrop();
}
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
dtde.rejectDrop();
} catch (IOException ex) {
ex.printStackTrace();
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}
}
}
}

GWT/GWT Bootstrap - Pagination (SimplePager)

I have a celltable and I'm trying implement pagination, but it doesn't work. I looked for solutions but without any success. I click in next page, nothing happens. I forgot to implement something? Someone can help me? Thanks for attention! Below, my implementation:
Java:
public class TaskPanel extends Composite {
private static TaskPanelUiBinder uiBinder = GWT
.create(TaskPanelUiBinder.class);
interface TaskPanelUiBinder extends UiBinder<Widget, TaskPanel> {
}
public TaskPanel() {
this.tableTask = createTableTask();
//Populate celltable
preencheListaTask();
initWidget(uiBinder.createAndBindUi(this));
}
#UiField(provided = true)
CellTable<Task> tableTask;
#UiField
AccordionGroup accordionTable;
#UiField Button btnRefresh;
#UiField SimplePager pager;
#UiField FormTaskPanel formTask;
List<Task> listTasks = new ArrayList<Task>();
ListDataProvider<Task> tableTaskProvider;
public List<Task> getListTasks() {
return this.listTasks;
}
public void setListTasks(List<Task> lista) {
this.listTasks = lista;
}
public TaskPanel getTaskPanel() {
return this;
}
//Create celltable
public CellTable<Task> createTableTask() {
tableTask = new CellTable<Task>();
tableTask.setPageSize(2);
TextColumn<Task> dataInicioColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getDataInicial();
}
};
tableTask.addColumn(dataInicioColumn, "Data Inicio");
TextColumn<Task> dataFinalColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getDataFinal();
}
};
tableTask.addColumn(dataFinalColumn, "Data Final");
TextColumn<Task> descricaoColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getDescricao();
}
};
tableTask.addColumn(descricaoColumn, "Descricao");
TextColumn<Task> categoriaColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getCategoria();
}
};
tableTask.addColumn(categoriaColumn, "Categoria");
TextColumn<Task> prioridadeColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getPrioridade();
}
};
tableTask.addColumn(prioridadeColumn, "Prioridade");
return tableTask;
}
//Generate a JSON, and I parse for List<Task> to populate celltable
public List<Task> preencheListaTask() {
final List<Task> lista = new ArrayList<Task>();
String url = "http://127.0.0.1:8888/financecontrol/jsonTableTasks.json";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
System.out.println("Error to retrieve JSON");
}
#Override
public void onResponseReceived(Request arg0, Response response) {
if (200 == response.getStatusCode()) {
JSONValue value = JSONParser.parse(response.getText());
com.google.gwt.json.client.JSONObject taskObjs = value
.isObject();
JSONArray tasksArray = taskObjs.get("tasks").isArray();
if (tasksArray != null) {
for (int i = 0; i < tasksArray.size(); i++) {
com.google.gwt.json.client.JSONObject taskObj = tasksArray
.get(i).isObject();
String id = taskObj.get("ID").isNumber().toString();
String dataInicial = taskObj
.get("Data Inicial").isString()
.stringValue();
String dataFinal = taskObj.get("Data Final")
.isString().stringValue();
String descricao = taskObj.get("Descricao")
.isString().stringValue();
String categoria = taskObj.get("Categoria").isString().toString();
String prioridade = taskObj.get("Prioridade").isString().toString();
Task task = new Task(Integer.parseInt(id),
dataInicial, dataFinal,
descricao, categoria, prioridade);
lista.add(task);
}
setListTasks(lista);
System.out.println("JSON retrieve");
}
addLinhas();
} else {
System.out.println("Couldn't retrieve JSON ("
+ response.getStatusText() + ")");
}
}
});
} catch (RequestException e) {
System.err.println("Erro cath - " + e.getMessage());
}
return lista;
}
//add rows to celltable
public void addLinhas() {
this.tableTask.setRowCount(getListTasks().size(), true);
this.tableTask.setRowData(0, getListTasks());
tableTask.redraw();
tableTaskProvider = new ListDataProvider<Task>(getListTasks());
tableTaskProvider.addDataDisplay(tableTask);
//Pagination
SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true);
pager.setDisplay(tableTask);
}
#UiHandler("btnRefresh")
public void onClickRefresh(ClickEvent e) {
preencheListaTask();
}
}
UiBinder:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:style>
.formContent {
height: 70%;
}
</ui:style>
<b:Container addStyleNames="{style.formContent}">
<r:FormTaskPanel ui:field="formTask"/>
<b:AccordionGroup ui:field="accordionTable" defaultOpen="false" heading="Task List">
<b:CellTable ui:field="tableTask" />
<b:SimplePager ui:field="pager" location="CENTER"/>
<b:Button ui:field="btnRefresh" text="Refresh" icon="REFRESH"/>
</b:AccordionGroup>
</b:Container>
You have pager = new SimplePager(...), so you have to declare #uiField(provided = true) for pager, and move pager declaration/initialisation into your createTableTask function (pager must be set before initwidget).

Password Style TextCellEditor showing original characters in TableViewer

TextCellEditor passEdit has SWT.PASSWORD style. But when Add button was clicked original characters were shown instead of default * echo characters. Also focus listeners on passEdit were not working. i.e When user double clicks it should show original characters and on focus lost it should show password echo characters.
How to fix this?
public class UserAddSolution {
public static boolean flag = true;
private TextCellEditor userNameEdit;
private TextCellEditor passEdit;
class UserNamePassword {
private final String name;
private final String password;
public UserNamePassword(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
}
public UserAddSolution(final Shell shell) {
shell.setLayout(new GridLayout(2, false));
GridData layoutData = new GridData();
layoutData.heightHint = 300;
shell.setLayoutData(layoutData);
final TableViewer viewer = new TableViewer(shell, SWT.BORDER
| SWT.FULL_SELECTION | SWT.MULTI);
viewer.setContentProvider(ArrayContentProvider.getInstance());
Table table = viewer.getTable();
table.setLayout(new GridLayout());
table.setLayoutData(layoutData);
userNameEdit = new TextCellEditor(table);
passEdit = new TextCellEditor(table, SWT.PASSWORD);
final Text tex = (Text) passEdit.getControl();
final char echar = tex.getEchoChar();
tex.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
tex.setEchoChar(echar);
}
#Override
public void focusGained(FocusEvent e) {
tex.setEchoChar('\0');
}
});
viewer.setCellEditors(new CellEditor[] { userNameEdit, passEdit });
viewer.setCellModifier(new ICellModifier() {
#Override
public boolean canModify(Object element, String property) {
return true;
}
#Override
public Object getValue(Object element, String property) {
UserNamePassword ele = (UserNamePassword) element;
if (property.equals("1")) {
return ele.getName();
} else if (property.equals("2")) {
return ele.getPassword();
}
return "";
}
#Override
public void modify(Object element, String property, Object value) {
}
});
viewer.setColumnProperties(new String[] { "1", "2" });
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(
viewer) {
#Override
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
int feature = ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL
| ColumnViewerEditor.KEYBOARD_ACTIVATION;
TableViewerEditor.create(viewer, actSupport, feature);
TableViewerColumn userNameColumn;
userNameColumn = new TableViewerColumn(viewer, SWT.NONE);
userNameColumn.getColumn().setWidth(200);
userNameColumn.getColumn().setMoveable(true);
userNameColumn.getColumn().setText("Name");
userNameColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public Image getImage(Object element) {
return super.getImage(element);
}
#Override
public String getText(Object element) {
UserNamePassword fdf = (UserNamePassword) element;
return super.getText(fdf.getName());
}
});
TableViewerColumn passwordColumn;
passwordColumn = new TableViewerColumn(viewer, SWT.NONE);
passwordColumn.getColumn().setWidth(200);
passwordColumn.getColumn().setMoveable(true);
passwordColumn.getColumn().setText("Password");
passwordColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public Image getImage(Object element) {
return super.getImage(element);
}
#Override
public String getText(Object element) {
UserNamePassword fdf = (UserNamePassword) element;
return super.getText(fdf.getPassword());
}
#Override
public void update(ViewerCell cell) {
super.update(cell);
}
});
viewer.setInput(new ArrayList<UserNamePassword>());
table.setLinesVisible(true);
table.setHeaderVisible(true);
viewer.refresh();
Button add = new Button(shell, SWT.PUSH);
add.setText("Add");
add.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
viewer.add(new UserNamePassword("abc", "xyz"));
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new UserAddSolution(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
The ColumnLabelProvider is responsible for displaying the data in the table. The text widget appears only when you edit a cell. That's why you need to tell the label provider to mask characters and not to display the plain text.
As a consequence you don't need to set SWT.PASSWORD style to the passEdit since you want to display the password in the editor as plain text:
passEdit = new TextCellEditor(table, SWT.NONE);
You also don't need the FocusListener and you can set the echo char as a constant:
private static final String ECHARSTR = Character.toString((char)9679);
So you can remove 15 lines below the initialization of passEdit
I don't know if there is a solution for this in JFace (I think not) but you can easily solve this by modifying your existing label provider. My suggestion is to modify the getText() method of ColumnLabelProvider for passwordColumn as follows:
#Override
public String getText(Object element)
{
UserNamePassword fdf = (UserNamePassword)element;
return fdf.getPassword().replaceAll(".", ECHARSTR);
}

JList update freezes display but not JFrame setTitle

If I update a JList with a long number of html formatted items then the controls stop responding and indicators won't update. This makes sense, the event thread is busy. The title can still be set though. Why is this?
Here's some (long) code demonstrating this:
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.*;
public class JListTest extends JFrame {
class TestListModel extends AbstractListModel<String> {
private static final long serialVersionUID = JListTest.serialVersionUID;
private boolean useHtml;
private String[] formattedList = new String[] {};
public int getSize() {
return formattedList.length;
}
public String getElementAt(int index) {
return formattedList[index];
}
public void setUseHtml(boolean useHtml) {
this.useHtml = useHtml;
}
public String getNewListItem() {
if (useHtml) {
return "<html><div style='padding:2px"
+ ";background-color:#EDF5F4;color:black'><div style='padding:2px;font-weight:500;'>"
+ "Item " + (100 * Math.random())
+ "</div>"
+ "This will change!"
+ "</div></html>";
} else {
return "Item " + (100 * Math.random());
}
}
public void updateItems() {
formattedList = new String[] {"<html><h1>Loading!</h1></html>"};
fireContentsChanged(this, 0, 1);
Thread buildItems = new Thread() {
#Override
public void run() {
final String[] tempList = new String[3000];
for (int i=0; i<tempList.length; i++) {
tempList[i] = getNewListItem();
}
// Just show the string bashing's done
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
formattedList = new String[] {"<html><h1>Updating!</h1></html>"};
fireContentsChanged(TestListModel.this, 0, 1);
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update
SwingUtilities.invokeLater(new Runnable() {
public void run() {
formattedList = tempList;
fireContentsChanged(TestListModel.this, 0, formattedList.length);
}
});
}
};
buildItems.start();
}
}
protected static final long serialVersionUID = 1L;
public JListTest() {
JPanel controlPanel = new JPanel();
JButton updaterControl = new JButton("Add 3000");
final JCheckBox useHtmlControl = new JCheckBox("Use HTML");
final TestListModel model = new TestListModel();
JList<String> list = new JList<String>(model);
JScrollPane scrollPane = new JScrollPane(list);
final JLabel durationIndicator = new JLabel("0");
controlPanel.add(useHtmlControl, BorderLayout.WEST);
controlPanel.add(updaterControl, BorderLayout.EAST);
getContentPane().add(controlPanel, BorderLayout.PAGE_START);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(durationIndicator, BorderLayout.PAGE_END);
useHtmlControl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.setUseHtml(useHtmlControl.isSelected());
}
});
useHtmlControl.setSelected(false);
updaterControl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.updateItems();
}
});
Timer counter = new Timer();
counter.schedule(new TimerTask() {
#Override
public void run() {
String previousCounter = durationIndicator.getText();
String newCounter = Integer.toString(
Integer.parseInt(previousCounter) + 1);
durationIndicator.setText(newCounter);
setTitle(newCounter);
}
}, 0, 100);
}
public static void main(String args[]) {
JListTest jlt = new JListTest();
jlt.pack();
jlt.setSize(300, 300);
jlt.setVisible( true );
}
}
The answer is pretty obvious - because Window title is not a Swing component, it's OS native entity.
So changes don't have to go through Swing Event Queue, but go to XDecoratedPeer.updateWMName directly in case of Unix and to some other class in other OSes.
The more interesting question would be how to avoid that UI blocking, but I don't think that's possible with just Swing, you'll have to implement some lazy loading, or rendering in batches.

Google Maps API v3 - Buttons and TextBoxes inside InfoWindow?

I'm using the new maps v3 API from gwt-google-apis.
Is it possible to capture events from GWT widgets that are inside InfoWindow? Am I missing something?
Tried code above (button.addClickHandler) and it doesn't show the alert:
Marker m = Marker.create();
m.setIcon(MarkerImage.create(icone));
m.setPosition(LatLng.create(posicao.lat(), posicao.lng()));
m.setMap(map);
m.addClickHandler(new ClickHandler() {
#Override
public void handle(MouseEvent event) {
InfoWindow info = InfoWindow.create();
Button button = new Button("Desativar");
button.addClickHandler(new com.google.gwt.event.dom.client.ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert("click");
}
});
final HTMLPanel html = new HTMLPanel(("<div id='button'></div>"));
html.add(button, "button");
info.setContent(html.getElement());
info.setPosition(posicao);
info.open(map);
}
});
Thanks.
The problem is result of a broken hierarchy between the widgets, the normal way to do it is by attach / detach widget. You do it by setting of the widget's element. This is also matter of Google Maps API.
This can be resolved by using fake panel which will be part of the InfoWindow, so when you make setContent(Widget widget) the fake panel will be updated and the element of the widget will be set to the content (as previous).
Please take a look at this class:
public class MyInfoWindow extends InfoWindow {
static class FakePanel extends ComplexPanel {
public FakePanel(Widget w) {
w.removeFromParent();
getChildren().add(w);
adopt(w);
}
#Override
public boolean isAttached() {
return true;
}
public void detachWidget() {
this.remove(0);
}
}
private IsWidget widgetContent = null;
FakePanel widgetAttacher;
public MyInfoWindow() {
super(InfoWindowImpl.impl.construct());
}
private void detachWidget() {
if (this.widgetAttacher != null) {
this.widgetAttacher.detachWidget();
this.widgetAttacher = null;
}
}
public void close() {
super.close();
detachWidget();
}
public void setContent(String content) {
this.widgetContent = null;
this.detachWidget();
super.setContent(content);
}
/** */
public void setContent(Widget value) {
this.widgetContent = value;
setContent(value.getElement());
if (this.widgetAttacher == null) {
addListener(getJso(), "closeclick", new Runnable() {
#Override
public void run() {
detachWidget();
}
});
this.widgetAttacher = new FakePanel(value);
} else if (this.widgetAttacher.getWidget(0) != value) {
this.widgetAttacher.detachWidget();
this.widgetAttacher = new FakePanel(value);
}
}
private void setContent(Element element) {
InfoWindowImpl.impl.setContent(getJso(), element);
}
public IsWidget getContentWidget() {
return widgetContent;
}
public final native void addListener(JavaScriptObject jso, String whichEvent, Runnable handler)
/*-{
var that = jso;
$wnd.google.maps.event.addListener(jso, whichEvent, function() {
handler.#java.lang.Runnable::run()();
});
}-*/;
}
I had to build a wrapper over InfoWindow to make it work.
public class NXInfoWindow {
static class FakePanel extends ComplexPanel {
public FakePanel(Widget w) {
w.removeFromParent();
getChildren().add(w);
adopt(w);
}
#Override
public boolean isAttached() {
return true;
}
public void detachWidget() {
this.remove(0);
}
}
private InfoWindow info;
private IsWidget widgetContent = null;
private Long id;
FakePanel widgetAttacher;
public static NXInfoWindow create(Long id){
NXInfoWindow myInfo = new NXInfoWindow();
myInfo.info = InfoWindow.create();
myInfo.id = id;
return myInfo;
};
private void detachWidget() {
if (this.widgetAttacher != null) {
this.widgetAttacher.detachWidget();
this.widgetAttacher = null;
}
}
public void close() {
info.close();
detachWidget();
}
public void setPosition(LatLng posicao) {
info.setPosition(posicao);
}
public void open(GoogleMap map) {
info.open(map);
}
public void setContent(Widget value) {
this.widgetContent = value;
info.setContent(value.getElement());
if (this.widgetAttacher == null) {
addListener(info, "closeclick", new Runnable() {
#Override
public void run() {
detachWidget();
}
});
this.widgetAttacher = new FakePanel(value);
} else if (this.widgetAttacher.getWidget(0) != value) {
this.widgetAttacher.detachWidget();
this.widgetAttacher = new FakePanel(value);
}
}
private void setContent(Element element) {
this.setContent(element);
}
public IsWidget getContentWidget() {
return widgetContent;
}
public final native void addListener(JavaScriptObject jso, String whichEvent, Runnable handler)
/*-{
var that = jso;
$wnd.google.maps.event.addListener(jso, whichEvent, function() {
handler.#java.lang.Runnable::run()();
});
}-*/;
}