Update Gtk.Label dynamicall when time changes - gtk

I'm using this code to write the current time as a Gtk.Label in an app.
public bool update_time () {
var now = new GLib.DateTime.now_local ();
var settings = new GLib.Settings ("org.gnome.desktop.interface");
var time_format = Granite.DateTime.get_default_time_format (settings.get_enum ("clock-format") == 1, false);
time1_label = new Gtk.Label (now.format (time_format)) {
halign = Gtk.Align.CENTER,
valign = Gtk.Align.CENTER,
margin_top = 5
};
time1_label.get_style_context ().add_class (Granite.STYLE_CLASS_H3_LABEL);
time1_label.tooltip_text = time_format;
time1_label.xalign = 0;
return true;
}
The time shows correctly, but I want the label to update to the latest time when it changes. How can I do that?
Maybe use Timeout in some way, but I can't figure out how.

You'll have to create a Timeout, and in its callback change the text of time1_label. (Use Gdk.threads_add_timeout() to add the timeout callback in case any dependencies might be using deprecated GTK locking mechanisms.)

You can use the Timeout as in this example:
public class RefreshLabel : Gtk.Application {
private uint[] timeout_id;
private Gtk.Label label;
public RefreshLabel () {
Object (
application_id: "refreh.my.label",
flags: ApplicationFlags.FLAGS_NONE
);
}
protected override void activate () {
Gtk.ApplicationWindow window = new Gtk.ApplicationWindow (this);
window.set_default_size (100, 50);
window.window_position = Gtk.WindowPosition.CENTER;
window.set_border_width(10);
// create the timeout with your callback that update the label every 1 second
timeout_id += Timeout.add_seconds_full (GLib.Priority.DEFAULT, 1, update_time);
label = new Gtk.Label ("");
var now = new GLib.DateTime.now_local ();
label.set_markup ("<big>" + now.format ("%x %X") + "</big>");
Gtk.Box vbox = new Gtk.Box (Gtk.Orientation.VERTICAL, 0);
vbox.pack_start (label, false, false, 0);
window.add (vbox);
window.show_all ();
}
protected override void shutdown () {
// On close all instance of the timeout must be closed
foreach (var id in timeout_id)
GLib.Source.remove (id);
base.shutdown ();
}
public bool update_time () {
var now = new GLib.DateTime.now_local ();
label.set_markup ("<big>" + now.format ("%x %X") + "</big>");
return true;
}
public static int main (string[] args) {
RefreshLabel app = new RefreshLabel ();
return app.run (args);
}
}

Related

Auto resize row heights while sorting or filtering

I can not handle auto row heights resizing.
I tried to use AutomaticRowHeightExample, but without success.
Another inspiration was this question, but also did not worked (see my code example). If I sort/filter, in console output I can see numbers of painted rows i while creating PaintListener, but row heights are not updated.
Creating table:
public class NatTableFactory {
// another code
private NatTable createTable(Composite parent, List<TableLine> tLines, String[][] propertyNames,
PropertyToLabels[] propToLabels, TableParams params, TextMatcherEditor<TableLine>editor, boolean openableParts) {
BodyLayerStack bodyLayerStack =
new BodyLayerStack(
tLines,
tLines.get(0).getLength(),
params.getColumnIndicesForRowHeaders());
DataLayer bodyDataLayer = bodyLayerStack.getBodyDataLayer();
Integer[] rowHeights = getRowHeights(params);
if( rowHeights != null && rowHeights.length > 0 ) {
for( int i = 0; i < rowHeights.length; i++ ) {
if( rowHeights[i] != null )
bodyDataLayer.setRowHeightByPosition(i, (int) (rowHeights[i] * ApplicationSizeManager.getRowSizeCoefficient()));
}
}
Integer[] colWidths = getColumnWidths(params);
if( colWidths != null && colWidths.length > 0 ) {
for( int i = 0; i < colWidths.length; i++ )
if( colWidths[i] != null )
bodyDataLayer.setColumnWidthByPosition(i, colWidths[i]);
}
DataLayer columnHeaderDataLayer = null;
if( propertyNames != null ) {
IDataProvider columnHeaderDataProvider =
new DefaultColumnHeaderDataProvider(propertyNames[0], propToLabels[0].getPropertyToLabels());
columnHeaderDataLayer =
new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
}
//copy command: include table headers
bodyLayerStack.registerCommandHandler(new CustomCopyDataCommandHandler(bodyLayerStack.getSelectionLayer(), columnHeaderDataLayer, null, params.getColumnHeaderGroups()));
CompositeLayer composite = null;
if( propertyNames != null ) {
ColumnHeaderLayer columnHeaderLayer =
new ColumnHeaderLayer(
columnHeaderDataLayer,
bodyLayerStack,
(SelectionLayer)null);
columnHeaderLayer.addConfiguration(NatTableLayerConfigurations.getColumnHeaderLayerConfiguration(false));
SortHeaderLayer<TableLine> sortHeaderLayer =
new SortHeaderLayer<TableLine>(
columnHeaderLayer,
new GlazedListsSortModel<TableLine>(
bodyLayerStack.getSortedList(),
getSortingColumnPropAccessor(propertyNames[0]),
configRegistry,
columnHeaderDataLayer));
Integer[] hrHeights = params.getHeaderRowHeights();
if( hrHeights != null && hrHeights.length > 0 )
columnHeaderDataLayer.setRowHeightByPosition(0, (int) (hrHeights[0] * ApplicationSizeManager.getRowSizeCoefficient()));
composite = new CompositeLayer(1, 2);
composite.setChildLayer(GridRegion.COLUMN_HEADER, sortHeaderLayer, 0, 0);
composite.setChildLayer(GridRegion.BODY, bodyLayerStack, 0, 1);
} else {
composite = new CompositeLayer(1, 1);
composite.setChildLayer(GridRegion.BODY, bodyLayerStack, 0, 0);
}
composite.addConfiguration(NatTableLayerConfigurations.getCompoositeLayerConfiguration());
NatTable natTable = new NatTable(parent, composite, false);
if( params.getAutoFitColWidthIndices().size() > 0 )
registerAutoResizeColCmdHandler(natTable, composite, bodyLayerStack, params.getAutoFitColWidthIndices());
// register AutoResizeRowCommandHandler
// something wrong here?
registerAutoResizeRowCommandHandler(natTable, composite, bodyLayerStack, params.getAutoFitColWidthIndices());
setNatTableContentTooltip(natTable);
natTable.setConfigRegistry(configRegistry);
natTable.addConfiguration(new SingleClickSortConfiguration());
if(columnHeaderDataLayer!=null)
natTable.addConfiguration(NatTableLayerConfigurations.getCustomComparatorConfiguration(columnHeaderDataLayer));
natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
setNatTableContextMenu(natTable, openableParts);
natTable.addConfiguration(NatTableLayerConfigurations.getNatTableConfiguration());
//
/*
natTable.addConfiguration(new DefaultNatTableStyleConfiguration()
{
{
cellPainter = new LineBorderDecorator(new AutomaticRowHeightTextPainter(5));
}
});*/
natTable.configure();
editor.setFilterator(new TextFilterator<TableLine>() {
#Override
public void getFilterStrings(List<String> baseList, TableLine element) {
for( int i = 0; i < element.getLength(); i++ )
baseList.add("" + element.getObjectByColumnForFilter(i));
}
});
editor.setMode(TextMatcherEditor.REGULAR_EXPRESSION);
bodyLayerStack.getFilterList().setMatcherEditor(editor);
NatTableContentProvider.addNatTableData(natTable, bodyLayerStack.getSelectionLayer(), bodyLayerStack.getBodyDataProvider());
return natTable;
}
// another code
}
register AutoResizeRowCommandHandler:
// in class NatTableFactory
private void registerAutoResizeRowCommandHandler(NatTable natTable, ILayer commandLayer, ILayer positionLayer, List<Integer> colPositions)
{
natTable.registerCommandHandler(new AutoResizeRowCommandHandler(commandLayer, positionLayer));
PaintListener listener = new PaintListener()
{
#Override
public void paintControl(PaintEvent e)
{
System.out.println("paintControl");
for (int i = 0; i < natTable.getRowCount(); i++)
{
System.out.println(i);
InitializeAutoResizeRowsCommand rowCommand = new InitializeAutoResizeRowsCommand(natTable, i, natTable.getConfigRegistry(), new GCFactory(
natTable));
AutoResizeRowsCommand command = new AutoResizeRowsCommand(rowCommand);
natTable.doCommand(command);
}
}
};
natTable.addPaintListener(listener);
}
BodyLayerStack:
public BodyLayerStack(List<TableLine> values, int columnCount, Integer[] columnIndicesForRowHeaders)
{
EventList<TableLine> eventList = GlazedLists.eventList(values);
TransformedList<TableLine, TableLine> rowObjectsGlazedList = GlazedLists.threadSafeList(eventList);
// this.filterList = new FilterList<>(rowObjectsGlazedList); //changed to:
// use the SortedList constructor with 'null' for the Comparator
// because the Comparator will be set by configuration
sortedList = new SortedList<>(rowObjectsGlazedList, null);
// wrap the SortedList with the FilterList
filterList = new FilterList<>(sortedList);
bodyDataProvider = new ListDataProvider<TableLine>(filterList, getColumnAccessor(columnCount));
bodyDataLayer = new DataLayer(bodyDataProvider);
IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
#Override
public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) {
int columnIndex = bodyDataLayer.getColumnIndexByPosition(columnPosition);
int rowIndex = bodyDataLayer.getRowIndexByPosition(rowPosition);
if(isRowHeader(columnIndicesForRowHeaders, columnIndex))
configLabels.addLabel(NatTableFactory.RowHeaderLabel);
else
{
// get dataTypes at actual positions and add/refresh labels
String label = filterList.get(rowIndex).getObjectTypeByColumn(columnIndex);
// adjust label according to autoFitWitdh option
if(filterList.get(rowIndex).isAutoFitColWidth(columnIndex))
label += "_" + NatTableFactory.AutoFitWidthLabel;
else
label += "_" + NatTableFactory.NoAutoFitWidthLabel;
configLabels.addLabel(label);
}
}
};
bodyDataLayer.setConfigLabelAccumulator(cellLabelAccumulator);
GlazedListsEventLayer<TableLine> glazedListsEventLayer = new GlazedListsEventLayer<>(bodyDataLayer, filterList);
selectionLayer = new SelectionLayer(glazedListsEventLayer, false);
selectionLayer.setSelectionModel(getSelectionModel());
selectionLayer.addConfiguration(getSelectionConfiguration());
//
viewportLayer = new ViewportLayer(selectionLayer);
setUnderlyingLayer(new ViewportLayer(selectionLayer));
}
If I call natTable.doCommand(rowCommand) instead of natTable.doCommand(command) while registering handler, row heights are updated correctly, but table is painted repetitively, scroll bar blinks all the time.
I tried also:
private void registerAutoResizeRowCommandHandler(NatTable natTable, ILayer commandLayer, ILayer positionLayer, List<Integer> colPositions)
{
natTable.registerCommandHandler(new AutoResizeRowCommandHandler(commandLayer, positionLayer));
BodyLayerStack bodyLayerStack = (BodyLayerStack) positionLayer;
natTable.addPaintListener(
new AutoResizeRowPaintListener(
natTable,
bodyLayerStack.getViewportLayer(),
bodyLayerStack.getBodyDataLayer()));
}
Any idea what did I miss?
Well for a complete answer I would need quite some time to explain the internals of NatTable. Not sure if you are really interested in this. So I simply answer how to do it right.
With NatTable 1.6 the AutoResizeRowPaintListener was added to simplify the auto row resize task. Information about this can be found here: https://www.eclipse.org/nattable/nandn/nandn_160.php
I have got it:
in NatTableFactory:
private NatTable createTable(Composite parent, List<TableLine> tLines, String[][] propertyNames,
PropertyToLabels[] propToLabels, TableParams params, TextMatcherEditor<TableLine>editor,
boolean openableParts)
{
// another code
registerAutoResizeRowCommandHandler(natTable, composite, bodyLayerStack);
//another code
return natTable;
}
and:
private void registerAutoResizeRowCommandHandler(NatTable natTable,
CompositeLayer commandLayer, BodyLayerStack bodyLayerStack)
{
natTable.registerCommandHandler(new AutoResizeRowCommandHandler(commandLayer, bodyLayerStack));
natTable.addPaintListener(
new AutoResizeRowPaintListener(
natTable,
bodyLayerStack.getViewportLayer(),
bodyLayerStack.getBodyDataLayer()));
}
My mistake was in BodyLayerStack:
viewportLayer = new ViewportLayer(selectionLayer);
setUnderlyingLayer(new ViewportLayer(selectionLayer));
correct is:
viewportLayer = new ViewportLayer(selectionLayer);
setUnderlyingLayer(viewportLayer);
Thanks Dirk Fauth!

system theme won't apply to program

I'm training in Vala and everything was going ok until I applied a pkexec executable, now my system theme(dark) won't apply to the app
Here's my code:
public class Thinkfan : Gtk.Application {
public Thinkfan() {
Object (
application_id: "com.github.isa-pp.thinkfan-control-gui",
flags: ApplicationFlags.FLAGS_NONE
);
}
protected override void activate() {
settings();
build_window();
}
private void build_window () {
var window = new Gtk.ApplicationWindow(this);
window.title = "Thinkfan Control";
window.window_position = Gtk.WindowPosition.CENTER;
window.set_default_size (280,113);
window.show_all ();
}
private void settings (){
var granite_settings = Granite.Settings.get_default ();
var gtk_settings = Gtk.Settings.get_default ();
gtk_settings.gtk_application_prefer_dark_theme = granite_settings.prefers_color_scheme == Granite.Settings.ColorScheme.DARK;
granite_settings.notify["prefers-color-scheme"].connect (() => {
gtk_settings.gtk_application_prefer_dark_theme = granite_settings.prefers_color_scheme == Granite.Settings.ColorScheme.DARK;
});
}
public static int main(string[] args) {
var thinkfan = new Thinkfan();
return thinkfan.run(args);
}
}
and my pkexec is pretty simple, just
#!/bin/sh
pkexec "/home/azure/thinkfan-vala/thinkfan"

How I count all the number of records in a RecordStore

I have a LWUIT app that should display the number of records in a LWUIT list.
To get all the records I use a method called getRecordData() that returns all records as a String array, it works fine.
But how do I count the number of these records?
import java.util.*;
import com.sun.lwuit.events.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.plaf.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms .*;
public class number_of_records extends MIDlet {
private RecordStore recordStore;
// Refresh2( ) method for getting the time now
public String Refresh2()
{
java.util.Calendar calendar = java.util.Calendar.getInstance();
Date myDate = new Date();
calendar.setTime(myDate);
StringBuffer time = new StringBuffer();
time.append(calendar.get(java.util.Calendar.HOUR_OF_DAY)).append(':');
time.append(calendar.get(java.util.Calendar.MINUTE)) ;
// time.append(calendar.get(java.util.Calendar.SECOND));
String tt = time.toString();
return tt;
}
// return all records of recordStore RecordStore
public String [] getRecordData( )
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords(null, null, false);
str = new String[recordStore.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch(javax.microedition.rms.RecordStoreException e)
{
}
}
}
catch(javax.microedition.rms.RecordStoreNotOpenException e)
{
}
catch(java.lang.NullPointerException n)
{
}
return str;
}
public void startApp()
{
com.sun.lwuit.Display.init(this);
final Button addition = new Button("add a goal");
final com.sun.lwuit.TextField tf = new com.sun.lwuit.TextField();
final com.sun.lwuit.List mylist = new com.sun.lwuit.List();
final Button All = new Button("All Goals");
final com.sun.lwuit.Form ff = new com.sun.lwuit.Form();
final com.sun.lwuit.Form g = new com.sun.lwuit.Form();
ff.getStyle().setBgColor(0X99CCFF);
All.getStyle().setBgColor(0X0066CC);
Style g_style5 = g.getSelectedStyle() ;
g.addComponent(tf);
g.addComponent(addition);
addition.getStyle().setBgColor(0X0066CC);
g.addComponent(All);
g.getStyle().setBgColor(0X99CCFF);
addition.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//
String s =tf.getText();
if( s!=null && s.length() > 0)
{
try
{
// Store the time in the String k
String k = Refresh2();
// The record and the time stored in KK String
String kk =tf.getText()+"-"+k;
// Add an item (the kk String) to mylist List.
mylist.addItem(kk);
byte bytestream[] = kk.getBytes() ;
// Add a record to recordStore.
int i = recordStore.addRecord(bytestream, 0, bytestream.length);
}
catch(Exception ex) { }
// Inform the User that he added the a record.
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("A goal has been added"+"" );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}
// Information to user that he/she didn’t add a record
else if((s==null || s.length()<= 0))
{
Dialog validDialo = new Dialog(" ");
validDialo.setScrollable(false);
validDialo.getDialogStyle().setBgColor(0x0066CC);
validDialo.setTimeout(5000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("please enter scorer name or number");
validDialo.addComponent(textArea);
validDialo.show(50, 50, 50, 50, true);
}
}
});
/*Action here for displaying all records of recordStore RecordStore in a new form */
All.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try
{
recordStore = RecordStore.openRecordStore("My Record Store", true);
}
catch(Exception ex) {}
try
{
com.sun.lwuit.Label l = new com.sun.lwuit.Label(" Team Goals") ;
ff.addComponent(l);
// Store the records of recordStore in string array
String [] record= getRecordData();
int j1;
String valueToBeInserted2="";
int k=getRecordData().length;
for( j1=0;j1< getRecordData().length;j1++)
{
valueToBeInserted2=valueToBeInserted2 + " " + record[j1];
if(j1==getRecordData().length)
{
mylist.addItem(record[j1]);
int m = getRecordData().length;
// Counting the number of records
String goals =""+getRecordData().length;
/* I tried to use for…loop to count them by length of the recordStore and render it.
This list also should display the number of records on the form.
But it didn’t !!!
*/
mylist.addItem(goals);
}
}
ff.addComponent(mylist);
}
catch(java.lang.IllegalArgumentException e)
{
}
finally
{
ff.show();
}
}
}
);
g.show();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional) {
}
}
I Wrote this code but it gives NullPointerException at recordStore.enumerateRecords (null, null,true);
So I think the problem here.
please help.
myButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvet av)
{
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true);
int o =recordStore.getNumRecords () ;
}
catch(Exception e)
{
}
}
});
what you need is enumeration.numRecords(); i reckon recordStore.getNumRecords() should work also, since this is what you are using the populate the array, you could even use the length of the array itself. These options are all in the code, it would be better to explore a bit more and also check the documentation to resolve trivial problems.
you could use the length of the array or set a RecordListener to your recordstore and increase a counter when added a record to recordstore.
here is the solution of my problem , I do a for loop to get the number of
elements of the array.
the counter should be the length of array
count.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent av)
{
try
{
recordStore = RecordStore.openRecordStore("recordStore", true);
}
catch(Exception e)
{ }
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true);
}
catch(Exception e)
{
}
String record[] = getRecordData();
int j;
j = record.length-1;
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("....");
textArea.setFocusable(false);
textArea.setText("Number Counted"+j );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}});

Drag and drop for tableviewer in SWT

I need to Drag tableViewer cell value to another tableViewer cell in swt.
I need to remove that value where i dragged and add those value where i dropped in tableViewer i'm able to drag and drop but not able to drop where i want too and not able to remove and add value when i drag and drop in tableviewer. Here is the i have:Thank in advance for help.
public void DragandDrop(){
Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
DragSource source = new DragSource(table_2, DND.DROP_MOVE | DND.DROP_COPY);
source.setTransfer(types);
source.addDragListener(new DragSourceAdapter() {
public void dragSetData(DragSourceEvent event) {
DragSource ds = (DragSource) event.widget;
Table table = (Table) ds.getControl();
TableItem[] selection = table.getSelection();
StringBuffer buff = new StringBuffer();
for (int i = 0, n = selection.length; i < n; i++) {
buff.append(selection[i].getText());
}
event.data = buff.toString();
}
});
DropTarget target = new DropTarget(table_3, DND.DROP_MOVE | DND.DROP_COPY );
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
public void dragEnter(DropTargetEvent event) {
if (event.detail != DND.DROP_DEFAULT) {
event.detail = (event.operations & DND.DROP_COPY) != 0 ? DND.DROP_COPY : DND.DROP_NONE;
}
for (int i = 0, n = event.dataTypes.length; i < n; i++) {
if (TextTransfer.getInstance().isSupportedType(event.dataTypes[i])) {
event.currentDataType = event.dataTypes[i];
}
}
}
public void dragOver(DropTargetEvent event) {
event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL;
}
public void drop(DropTargetEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
DropTarget target = (DropTarget) event.widget;
Table table = (Table) target.getControl();
String data = (String) event.data;
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { data });
// table.redraw();
}
}
});
}
to remove the selected value you can use follows
public void drop(DropTargetEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
DropTarget target = (DropTarget) event.widget;
Table table = (Table) target.getControl();
String data = (String) event.data;
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { data });
//remove the tableitem you drag
table.remove(table.getSelectionIndex());
}
I was looking for Drag and Drop on TableViewer and found the solutions. Hope everyone understand easily. My case, I created two new Listener class inheritance from DragSourceListener & DropTargetListener. Because I want to use TableViewer functions. You need three things to do.
First save index of source item from void dragStart(DragSourceEvent event),
Seconds set data into event.data and
Then Last found target index from void drop(DropTargetEvent event).
public class TestClass extends TableViewer {
private int sourceIndex;
priavte class DragListener implements DragSourceListener {
private TableViewer viewer;
public ItemDragListener(TableViewer viewer) {
this.viewer = viewer;
}
public void dragStart(DragSourceEvent event) {
sourceIndex = viewer.getTable().getSelectionIndex();
}
public void dragSetData(DragSourceEvent event) {
// save data
ISelection select = viewer.getSelection();
if (select instanceof IStructuredSelection) {
Object item = (Object) ((IStructuredSelection)select).getFirstElement();
// save item to event.data
event.data = .........
}
:
}
private class ItemDropListener implements DropTargetListener {
TableViewer viewer;
public ItemDropListener(TableViewer viewer) {
this.viewer = viewer;
}
public void drop(DropTargetEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
TableItem item = (TableItem)event.item;
int targetIndex= -1;
if (item != null) {
Table table = item.getParent();
targetIndex= table.indexOf(item);
}
String data = (String) event.data;
// add an item
if (targetIndex >= 0)
viewer.insert((Object)data, targetIndex);
else
viewer.add((Object)data);
// remove an item
viewer.getTable().remove(sourceIndex); // Careful, it can be changed after add an item
}
}
public void init() {
Transfer[] transfers = new Transfer[] { TextTransfer.getInstance() };
this.addDragSupport(DND.DROP_COPY | DND.DROP_MOVE, transfers, new ItemDragListener(this));
this.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, transfers, new ItemDropListener(this));
}
}

Connecting to scroll_event in Vala

I've been struggling to connect to the scroll_event of a TextView widget. I can connect a lambda to it, and then run my method, but I'd like to understand why directly connecting doesn't work. I've been using the code below
using Gtk;
public class TextFileViewer : Gtk.Window {
private TextView text_view;
public TextFileViewer () {
this.title = "Text File Viewer";
this.position = WindowPosition.CENTER;
set_default_size (400, 300);
this.text_view = new TextView ();
this.text_view.editable = true;
this.text_view.cursor_visible = true;
var scroll = new ScrolledWindow (null, null);
scroll.set_policy (PolicyType.AUTOMATIC, PolicyType.AUTOMATIC);
scroll.add (this.text_view);
this.text_view.scroll_event.connect (on_scroll_event);
var vbox = new VBox (true, 0);
vbox.pack_start (this.text_view, true, true, 0);
add (vbox);
}
private void on_scroll_event () {
stderr.printf("We scrollin breds");
}
public static int main (string[] args) {
Gtk.init (ref args);
var window = new TextFileViewer ();
window.destroy.connect (Gtk.main_quit);
window.show_all ();
Gtk.main ();
return 0;
}
}
That code gives me the error:
gtkviewer.vala:20.46-20.60: error: Argument 1: Cannot convert from `TextFileViewer.on_scroll_event' to `Gtk.Widget.scroll_event'
scroll.scroll_event.connect (on_scroll_event);
vala is at version 0.12.0
Check the scroll-event signal arguments:
public virtual signal bool scroll_event (Gdk.EventScroll event);
private bool on_scroll_event (Gdk.EventScroll e) {
stderr.printf("We scrollin breds");
return true;
}