Blackberry 1 picture extreme left and 1 button extreme right - layout

I'm making a blackberry app, I just want to know how can I align the buttons in such a way that 1 is extreme right and the picture is extreme left. I have tried horizontal manager but it's not supporting Field.Field_RIGHT and Field.Field_Left.

try this-
HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
ButtonField left=new ButtonField("Left");
ButtonField right=new ButtonField("Right");
JustifiedHorizontalFieldManager j=new JustifiedHorizontalFieldManager(left,right, true);
hfm.add(j);
add(hfm);
The JustifiedHorizontalFieldManager class is given below -
public class JustifiedHorizontalFieldManager extends Manager
{
private static final int SYSTEM_STYLE_SHIFT = 32;
public Field _leftField;
public Field _rightField;
private boolean _giveLeftFieldPriority;
public JustifiedHorizontalFieldManager( Field leftField, Field rightField, boolean giveLeftFieldPriority )
{
this( leftField, rightField, giveLeftFieldPriority, Field.USE_ALL_WIDTH );
}
public JustifiedHorizontalFieldManager( Field leftField, Field rightField, boolean giveLeftFieldPriority, long style )
{
super( style );
_leftField = leftField;
_rightField = rightField;
add( _leftField );
add( _rightField );
_giveLeftFieldPriority = giveLeftFieldPriority;
}
public JustifiedHorizontalFieldManager( boolean giveLeftFieldPriority, long style )
{
super( style );
_giveLeftFieldPriority = giveLeftFieldPriority;
}
public void addLeftField( Field field )
{
if( _leftField != null ) {
throw new IllegalStateException();
}
_leftField = field;
add( _leftField );
}
public void addRightField( Field field )
{
if( _rightField != null ) {
throw new IllegalStateException();
}
_rightField = field;
add( _rightField );
}
public int getPreferredWidth()
{
return _leftField.getPreferredWidth() + _rightField.getPreferredWidth();
}
public int getPreferredHeight()
{
return Math.max( _leftField.getPreferredHeight(), _rightField.getPreferredHeight() );
}
protected void sublayout( int width, int height )
{
Field firstField;
Field secondField;
if( _giveLeftFieldPriority ) {
firstField = _leftField;
secondField = _rightField;
} else {
firstField = _rightField;
secondField = _leftField;
}
int maxHeight = 0;
int availableWidth = width;
availableWidth -= _leftField.getMarginLeft();
availableWidth -= Math.max( _leftField.getMarginRight(), _rightField.getMarginLeft() );
availableWidth -= _rightField.getMarginRight();
layoutChild( firstField, availableWidth, height - firstField.getMarginTop() - firstField.getMarginBottom() );
maxHeight = Math.max( maxHeight, firstField.getMarginTop() + firstField.getHeight() + firstField.getMarginBottom() );
availableWidth -= firstField.getWidth();
layoutChild( secondField, availableWidth, height - secondField.getMarginTop() - secondField.getMarginBottom() );
maxHeight = Math.max( maxHeight, secondField.getMarginTop() + secondField.getHeight() + secondField.getMarginBottom() );
availableWidth -= secondField.getWidth();
if( !isStyle( Field.USE_ALL_HEIGHT ) ) {
height = maxHeight;
}
if( !isStyle( Field.USE_ALL_WIDTH ) ) {
width -= availableWidth;
}
setPositionChild( _leftField, _leftField.getMarginLeft(), getFieldY( _leftField, height ) );
setPositionChild( _rightField, width - _rightField.getWidth() - _rightField.getMarginRight(), getFieldY( _rightField, height ) );
setExtent( width, height );
}
private int getFieldY( Field field, int height )
{
switch( (int)( ( field.getStyle() & FIELD_VALIGN_MASK ) >> SYSTEM_STYLE_SHIFT ) ) {
case (int)( FIELD_BOTTOM >> SYSTEM_STYLE_SHIFT ):
return height - field.getHeight() - field.getMarginBottom();
case (int)( FIELD_VCENTER >> SYSTEM_STYLE_SHIFT ):
return field.getMarginTop() + ( height - field.getMarginTop() - field.getHeight() - field.getMarginBottom() ) / 2;
default:
return field.getMarginTop();
}
}
public Field getLeftField()
{
return _leftField;
}
public Field getRightField()
{
return _rightField;
}
public void replace( Field oldField, Field newField )
{
if( oldField == newField ) {
// Nothing to do
return;
}
if( oldField == _leftField ) {
_leftField = newField;
} else if( oldField == _rightField ) {
_rightField = newField;
}
add( newField );
delete( oldField );
}
}

Even simpler if you want:
yourHorizontalFieldManager.add(leftButton);
rightButton.setPosition(Display.getWidth()-leftButton.getPrefferedWidth()-rightButton.getPreferredWidth());
yourHorizontalFieldManager.add(rightButton);
See also this

Related

REVIT Transfer floor sketch to Void Extrusion in Family

Struggling with some Revit code to copy the profile of a floor and use it as the sketch profile for a void extrusion in a family.
Here is the Full Sharp Development Code. It half works in my custom project template, when I try to use it in an out of the box project generated from revit default template it gives the error "a managed exception was thrown by revit or by one of its external applications"
In my template it cannot properly split the curves into a secondary array. It says the array elements are being changed but when the loop runs again the element i is back to it's original content??? The TaskDialog clearly says the elements have changed, until the loop iterates again.
Full code: To work it requires a generic family with the name "Void - Custom" to be in the project. The "If found" near the bottom last page and a half of code, is where the for loop is not behaving as expected.
/*
* Created by SharpDevelop.
* User: arautio
* Date: 4/30/2019
* Time: 11:10 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace ARC
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.DB.Macros.AddInId("3411F411-6FC1-4A4D-9CFD-37ABB2028A15")]
public partial class ThisApplication
{
private void Module_Startup(object sender, EventArgs e)
{
}
private void Module_Shutdown(object sender, EventArgs e)
{
}
#region Revit Macros generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(Module_Startup);
this.Shutdown += new System.EventHandler(Module_Shutdown);
}
#endregion
public void FloorGrating()
{
StringBuilder sb = new StringBuilder();
Dictionary<Floor, List<ModelCurve>> dict_SketchLines = new Dictionary<Floor, List<ModelCurve>>();
UIDocument uidoc = this.ActiveUIDocument;
Document document = uidoc.Document;
View activev = document.ActiveView;
ElementId levelId = null;
levelId = activev.LevelId;
Element levelem = document.GetElement( levelId );
Level lev = document.ActiveView.GenLevel;
Reference refsel = uidoc.Selection.PickObject(ObjectType.Element, "Select Floor to Add Grating To");
Element elem = document.GetElement(refsel.ElementId);
Floor f = elem as Floor;
List<ElementId> _deleted = null;
using (Transaction t = new Transaction(document, "temp"))
{
t.Start();
document.Regenerate();
_deleted = document.Delete(elem.Id).ToList();
t.RollBack();
}
bool SketchLinesFound = false;
List<ModelCurve> _sketchCurves = new List<ModelCurve>();
foreach (var id in _deleted)
{
ModelCurve mc = document.GetElement(id) as ModelCurve;
if (mc != null)
{
_sketchCurves.Add(mc);
SketchLinesFound = true;
}
else
{
if (SketchLinesFound) break;
}
}
dict_SketchLines.Add(f, _sketchCurves);
foreach (Floor key in dict_SketchLines.Keys)
{
List<ModelCurve> _curves = dict_SketchLines[key];
sb.AppendLine(string.Format("floor {0} has sketchlines:", key.Id));
foreach (ModelCurve mc in _curves)
{
sb.AppendLine(string.Format("{0} <{1}>", mc.GetType(), mc.Id));
sb.AppendLine(string.Format("<{0}>", mc.GeometryCurve.IsBound.ToString()));
if (mc.GetType().ToString() == "Autodesk.Revit.DB.ModelArc" && mc.GeometryCurve.IsBound == false)
{
TaskDialog.Show("Revit", "Circle Found");
}
try
{
sb.AppendLine(string.Format("<{0} -- {1}>", mc.GeometryCurve.GetEndPoint(0), mc.GeometryCurve.GetEndPoint(1)));
}
catch
{
}
}
sb.AppendLine();
}
//TaskDialog.Show("debug", sb.ToString());
Document docfamily;
Family fam;
string ftitle = document.Title;
string fpath = document.PathName;
int ftitlelen = ftitle.Length + 4;
int fpathlen = fpath.Length;
int finpathlen = fpathlen - ftitlelen;
string sfinpath = fpath.Substring(0,finpathlen);
string famname = "GratingVoid";
string fext = ".rfa";
int counter = 1;
while (counter < 100)
{
famname = ("GratingVoid" + counter as String);
Family family = FindElementByName(document,typeof(Family),famname)as Family;
if( null == family )
{
sfinpath = (sfinpath + famname + fext);
counter = 1000;
}
counter += 1;
}
FilteredElementCollector collector0 = new FilteredElementCollector(document);
ICollection<Element> collection0 = collector0.WhereElementIsNotElementType().ToElements();
List<FamilySymbol> fsym0 = new FilteredElementCollector(document).OfClass(typeof(FamilySymbol)).Cast<FamilySymbol>().ToList();
FamilySymbol famsymb0 = null;
foreach (FamilySymbol symb in fsym0)
{
if (symb.Name == "Void - Custom")
{
famsymb0 = symb as FamilySymbol;
}
}
fam = famsymb0.Family;
docfamily = document.EditFamily(fam);
try
{
docfamily.SaveAs(#sfinpath);
}
catch
{
TaskDialog.Show("Revit", "Could Not Save Void Family");
}
using (Transaction trans = new Transaction(docfamily))
{
trans.Start("family");
bool circleflag = false;
ElementId delid = null;
FilteredElementCollector collector = new FilteredElementCollector( docfamily );
foreach(Element element in collector.OfClass(typeof(GenericForm)))
{
delid = element.Id;
}
docfamily.Delete(delid);
CurveArray loccurva = new CurveArray();
foreach (Floor key in dict_SketchLines.Keys)
{
List<ModelCurve> _curves = dict_SketchLines[key];
foreach (ModelCurve mc in _curves)
{
if (mc.GetType().ToString() == "Autodesk.Revit.DB.ModelArc" && mc.GeometryCurve.IsBound == false)
{
circleflag = true;
}
LocationCurve lcurve = mc.Location as LocationCurve;
Curve c = lcurve.Curve as Curve;
loccurva.Append(c);
}
}
try
{
if (circleflag == true && loccurva.Size == 2)
{
Curve tempc;
if (loccurva.get_Item(0).GetType().ToString() == "Autodesk.Revit.DB.Arc")
{
tempc = loccurva.get_Item(0);
}
else
{
tempc = loccurva.get_Item(1);
}
loccurva.Clear();
loccurva.Append(tempc);
}
CurveArrArray newcurarr = new CurveArrArray();
newcurarr.Append(loccurva);
SortCurvesContiguousArray(newcurarr);
TaskDialog.Show("Revit CurveArray Array Size" , newcurarr.Size.ToString());
foreach (CurveArray ca in newcurarr)
{
TaskDialog.Show("Revit CurveArray within Array Size" , ca.Size.ToString());
}
// Below is edited for error control - leaving out the secondary loops for now
CurveArrArray switcharr = new CurveArrArray();
//switcharr.Append(newcurarr.get_Item(1));
switcharr.Append(newcurarr.get_Item(0));
//SortCurvesContiguousArray(loccurva);
//CurveArrArray newcurarr = new CurveArrArray();
//newcurarr.Append(loccurva);
double end = 1;
SketchPlane sketch = FindElementByName( docfamily,typeof( SketchPlane ), "Ref. Level" ) as SketchPlane;
docfamily.FamilyCreate.NewExtrusion(false, switcharr, sketch, end);
}
catch
{
TaskDialog.Show("Revit", "Could Not Write to Curve Array or Create Extrusion");
}
trans.Commit();
}
docfamily.Save();
docfamily.LoadFamily(document, new CustomFamilyLoadOption());
docfamily.Close();
File.Delete(sfinpath);
Family familynew = FindElementByName(document,typeof(Family),famname)as Family;
if( null == familynew )
{
TaskDialog.Show("Revit", "Family Does Not Exist");
}
FilteredElementCollector collector1 = new FilteredElementCollector(document);
ICollection<Element> collection = collector1.WhereElementIsNotElementType().ToElements();
List<FamilySymbol> fsym = new FilteredElementCollector(document).OfClass(typeof(FamilySymbol)).Cast<FamilySymbol>().ToList();
FamilySymbol famsymb = null;
foreach (FamilySymbol symb in fsym)
{
if (symb.Name == famname)
{
famsymb = symb as FamilySymbol;
}
}
using (Transaction trans = new Transaction(document))
{
trans.Start("PlaceVoid");
if( ! famsymb.IsActive )
{
famsymb.Activate();
}
XYZ p = new XYZ(0,0,0);
FamilyInstance gratingvoid = document.Create.NewFamilyInstance( p, famsymb, lev, lev, StructuralType.NonStructural );
document.Regenerate();
trans.Commit();
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
static public Element FindElementByName(Document doc,Type targetType,string targetName)
{
return new FilteredElementCollector( doc ).OfClass( targetType ).FirstOrDefault<Element>(e => e.Name.Equals( targetName ) );
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public class CustomFamilyLoadOption : IFamilyLoadOptions
{
public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues)
{
overwriteParameterValues = true;
return true;
}
public bool OnSharedFamilyFound(Family sharedFamily,bool familyInUse,out FamilySource source, out bool overwriteParameterValues)
{
source = FamilySource.Family;
overwriteParameterValues = true;
return true;
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
const double _inch = 1.0 / 12.0;
const double _sixteenth = _inch / 16.0;
static Curve CreateReversedCurve(Curve orig )
{
//if( !IsSupported( orig ) )
//{
// throw new NotImplementedException("CreateReversedCurve for type " + orig.GetType().Name );
//}
if( orig is Line )
{
//return creapp.NewLineBound(orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ) );
return Line.CreateBound(orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ) );
}
else if( orig is Arc )
{
// return creapp.NewArc( orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ), orig.Evaluate( 0.5, true ) );
return Arc.Create( orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ), orig.Evaluate( 0.5, true ) );
}
else
{
throw new Exception(
"CreateReversedCurve - Unreachable" );
}
}
public static void SortCurvesContiguousArray(CurveArrArray curvesarr)
{
double _precision1 = 1.0 / 12.0 / 16.0; // around 0.00520833
double _precision2 = 0.001; // limit for CurveLoop.Create(...)
int cn = curvesarr.Size;
int ci = 0;
while (ci < cn)
{
CurveArray curves = curvesarr.get_Item(ci);
ci +=1;
// account for multiple curve loops with secondary array
CurveArray loop1 = new CurveArray();
CurveArray loop2 = new CurveArray();
int n = curves.Size;
int split = 1;
// Walk through each curve (after the first)
// to match up the curves in order
for (int i = 0; i < n; ++i)
{
TaskDialog.Show("Revit I Loop Run", i.ToString());
Curve curve = curves.get_Item(i);
if (curve.GetType().ToString() == "Autodesk.Revit.DB.Arc" && curve.IsBound == false)
{
break;
}
XYZ beginPoint = curve.GetEndPoint(0);
XYZ endPoint = curve.GetEndPoint(1);
XYZ p,q;
// Find curve with start point = end point
bool found = (i + 1 >= n);
for (int j = i + 1; j < n; ++j)
{
p = curves.get_Item(j).GetEndPoint(0);
q = curves.get_Item(j).GetEndPoint(1);
// If there is a match end->start,
// this is the next curve
if (p.DistanceTo(endPoint) < _precision1)
{
if (p.DistanceTo(endPoint) > _precision2)
{
XYZ intermediate = new XYZ((endPoint.X + p.X) / 2.0, (endPoint.Y + p.Y) / 2.0, (endPoint.Z + p.Z) / 2.0);
curves.set_Item(i, Line.CreateBound(beginPoint, intermediate));
curves.set_Item(j, Line.CreateBound(intermediate, q));
}
if (i + 1 != j)
{
Curve tmp = curves.get_Item(i + 1);
curves.set_Item(i + 1, curves.get_Item(j));
curves.set_Item(j, tmp);
}
found = true;
break;
}
// If there is a match end->end,
// reverse the next curve
if (q.DistanceTo(endPoint) < _precision1)
{
if (q.DistanceTo(endPoint) > _precision2)
{
XYZ intermediate = new XYZ((endPoint.X + q.X) / 2.0, (endPoint.Y + q.Y) / 2.0, (endPoint.Z + q.Z) / 2.0);
curves.set_Item(i, Line.CreateBound(beginPoint, intermediate));
curves.set_Item(j, Line.CreateBound(p, intermediate));
}
if (i + 1 == j)
{
curves.set_Item(i + 1, CreateReversedCurve(curves.get_Item(j)));
}
else
{
Curve tmp = curves.get_Item(i + 1);
curves.set_Item(i + 1, CreateReversedCurve(curves.get_Item(j)));
curves.set_Item(j, tmp);
}
found = true;
break;
}
}
if (!found)
{
// if not found, must be part of a new loop - move it to the back and keep going and add to second array
TaskDialog.Show("Revit No Match Found for item", i.ToString());
TaskDialog.Show("Revit", "Moveing it to back of list");
Curve tmp1 = curves.get_Item(i);
TaskDialog.Show("Revit tmp1 Current i item endpt", tmp1.GetEndPoint(0).ToString());
loop2.Append(tmp1);
Curve tmp2 = curves.get_Item(n - split);
TaskDialog.Show("Revit tmp2 Back of list item endpt", tmp2.GetEndPoint(0).ToString());
// set current item to rear
curves.set_Item(i, tmp2);
// set rear item to current
curves.set_Item(n - split, tmp1);
TaskDialog.Show("Revit new item i endpt", curves.get_Item(i).GetEndPoint(0).ToString());
TaskDialog.Show("Revit moved item endpt", curves.get_Item(n - split).GetEndPoint(0).ToString());
// error testing - try to append in a different manner and check values
//curves.set_Item(i, Line.CreateBound(curves.get_Item(i).GetEndPoint(0), curves.get_Item(i).GetEndPoint(1)));
//curves.set_Item(n - split, Line.CreateBound(curves.get_Item(n - split).GetEndPoint(0), curves.get_Item(n - split).GetEndPoint(1)));
//Curve ncurve = Line.CreateBound(curves.get_Item(n - split).GetEndPoint(0), curves.get_Item(n - split).GetEndPoint(1));
//TaskDialog.Show("Revit Appended to Loop2 Endpoint", ncurve.GetEndPoint(0).ToString());
//loop2.Append(ncurve);
//set the split off counter so items not fitting in first loop can be split to new array.
split += 1;
//reset the counter back so item moved from rear can be checked in next run of for loop
i -= 2;
}
//set counter to end for loop when all items that do not fit in first loop are processed
if (i >= n - (split + 1))
{
TaskDialog.Show("Revit", "End Of Looping");
TaskDialog.Show("Revit - The Split Number", split.ToString());
i = n;
}
}
int counter = 0;
// recreate array with only items from first loop found
while (counter <= (n - split))
{
loop1.Append(curves.get_Item(counter));
counter += 1;
}
TaskDialog.Show("Revit loop1 Size", loop1.Size.ToString());
curvesarr.Clear();
curvesarr.Append(loop1);
if (loop2.Size > 0)
{
string stringinfo = "";
// run the loop detection on a second array that was split from the first
TaskDialog.Show("Revit loop2 Size", loop2.Size.ToString());
CurveArrArray tmpcurvesarr = new CurveArrArray();
tmpcurvesarr.Append(loop2);
SortCurvesContiguousArray(tmpcurvesarr);
loop2.Clear();
loop2 = tmpcurvesarr.get_Item(0);
curvesarr.Append(loop2);
foreach (Curve ccc in loop2)
{
stringinfo = (stringinfo + " " + ccc.GetEndPoint(0).ToString() + " - " + ccc.GetEndPoint(1).ToString());
}
TaskDialog.Show("Revit", stringinfo);
}
}
}
}
}
Thanks for any and all help.
Shane

How to select multiple items in treewidget and delete those items?

When I am selecting items in treewidget and then clicked on delete button then is is just deleting top most item only from treewidget
Can you correct this code?
This function is calling in connect statement while clicking on button
void TableDockWidget::deleteGroup() {
QTreeWidgetItem *item = treeWidget->currentItem();
QTreeWidgetItem* nextItem = treeWidget->itemBelow(item);
if ( item == NULL ) return;
PeakGroup* group = getSelectedGroup(); //this function is using to //select items from treewidget
if ( group == NULL ) return;
PeakGroup* parentGroup = group->parent;
if ( parentGroup == NULL ) { //top level item
deleteGroup(group); //this is using to delete group
} else if ( parentGroup && parentGroup->childCount() ) { //this a child item
if ( parentGroup->deleteChild(group) ) {
QTreeWidgetItem* parentItem = item->parent();
if ( parentItem ) {
parentItem->removeChild(item);
delete(item);
}
}
}
//show NextItem
if(nextItem) treeWidget->setCurrentItem(nextItem,0);
return;
}
//here, code of function which is selecting items.
PeakGroup* TableDockWidget::getSelectedGroup() {
QTreeWidgetItem *item = treeWidget->currentItem();
if (!item) return NULL;
QVariant v = item->data(0,Qt::UserRole);
PeakGroup* group = v.value<PeakGroup*>();
if ( group != NULL ) { return group; }
return NULL;
}
// code of function which is deleting group
void TableDockWidget::deleteGroup(PeakGroup *groupX) {
qDebug() << "TableDockWidget::deleteGroup()";
if(!groupX) return;
int pos=-1;
for(int i=0; i < allgroups.size(); i++) {
if ( &allgroups[i] == groupX ) {
pos=i; break;
}
}
if (pos == -1) return;
//qDebug() << "Delete pos=" << pos;
QTreeWidgetItemIterator it(treeWidget);
while (*it) {
QTreeWidgetItem* item = (*it);
if (item->isHidden()) { ++it; continue; }
QVariant v = item->data(0,Qt::UserRole);
PeakGroup* group = v.value<PeakGroup*>();
if ( group != NULL and group == groupX) {
item->setHidden(true);
//Deleteing
allgroups.erase(allgroups.begin()+pos);
int posTree = treeWidget->indexOfTopLevelItem(item);
if (posTree != -1) treeWidget->takeTopLevelItem(posTree);
break;
}
++it;
}
for(unsigned int i = 0; i < allgroups.size(); i++) {
allgroups[i].groupId = i + 1;
}
updateTable();
_mainwindow->getEicWidget()->replotForced();
}
PeakGroup* TableDockWidget::getSelectedGroup() {
PeakGroup* group;
QList<QTreeWidgetItem*>selected = treeWidget->selectedItems();
if(selected.size() == 0) return NULL;
Q_FOREACH (QTreeWidgetItem* item, selected) {
QVariant v = item->data(0,Qt::UserRole);
group = v.value<PeakGroup*>();
item->setHidden(true);
}
if ( group != NULL ) { return group; }
else
return NULL;
}

How to make CMFCToolBarComboBoxButton able to works in vertical mode?

The MFC Feature Pack toolbar combo-button (class CMFCToolBarComboBoxButton) works perfectly in horizontal toolbar mode. But in vertical layout mode it is the simple press button without combobox feature.
How to make CMFCToolBarComboBoxButton able to works in vertical mode?
This my solution. I overwrote the behavior of the buttons in vertical mode. And now the button shows combobox drop down window when it is pressed in vertical mode.
You should use class CVerticalableToolBarComboBoxButton instead of CMFCToolBarComboBoxButton in ReplaceButton() method when you add combobox button to your toolbar.
Example: In the images below you can see the behavior of the buttons in the horizontal and vertical modes.
Horizontal mode
Vertical mode
Class code:
class CVerticalableToolBarComboBoxButton
: public CMFCToolBarComboBoxButton
{
DECLARE_SERIAL(CVerticalableToolBarComboBoxButton)
public:
typedef CMFCToolBarComboBoxButton TBase;
protected:
bool m_bDoVerticalMode;
public:
CVerticalableToolBarComboBoxButton(bool bDoVerticalMode = true);
CVerticalableToolBarComboBoxButton(UINT uiID, int iImage, DWORD dwStyle = CBS_DROPDOWNLIST, int iWidth = 0, bool bDoVerticalMode = true);
virtual ~CVerticalableToolBarComboBoxButton();
virtual void Serialize(CArchive& ar);
virtual BOOL OnClick(CWnd* pWnd, BOOL bDelay = TRUE);
virtual void OnChangeParentWnd(CWnd* pWndParent);
virtual void OnMove();
virtual void OnSize(int iSize);
protected:
void AdjustVerticalRect();
};
/////////////////////////////////////////////////////////////////////////////
// CVerticalableToolBarComboBoxButton
IMPLEMENT_SERIAL(CVerticalableToolBarComboBoxButton, CVerticalableToolBarComboBoxButton::TBase, VERSIONABLE_SCHEMA | 1)
CVerticalableToolBarComboBoxButton::CVerticalableToolBarComboBoxButton(bool bDoVerticalMode /*= true*/)
: m_bDoVerticalMode(bDoVerticalMode)
{}
CVerticalableToolBarComboBoxButton::CVerticalableToolBarComboBoxButton(UINT uiID, int iImage, DWORD dwStyle /*= CBS_DROPDOWNLIST*/, int iWidth /*= 0*/, bool bDoVerticalMode /*= true*/)
: TBase(uiID, iImage, dwStyle, iWidth)
, m_bDoVerticalMode(bDoVerticalMode)
{}
CVerticalableToolBarComboBoxButton::~CVerticalableToolBarComboBoxButton()
{}
void CVerticalableToolBarComboBoxButton::Serialize(CArchive& ar)
{
TBase::Serialize(ar);
if (ar.IsLoading()) {
ar >> m_bDoVerticalMode;
}
else {
ar << m_bDoVerticalMode;
}
}
BOOL CVerticalableToolBarComboBoxButton::OnClick(CWnd* pWnd, BOOL bDelay /*= TRUE*/)
{
BOOL bRes = FALSE;
bool bDefault = m_bHorz || !m_bDoVerticalMode;
if (!bDefault) {
if (IsFlatMode()) {
if (m_pWndEdit == NULL) {
m_pWndCombo->SetFocus();
}
else {
m_pWndEdit->SetFocus();
}
m_pWndCombo->ShowDropDown();
if (pWnd != NULL) {
pWnd->InvalidateRect(m_rectCombo);
}
bRes = TRUE;
}
}
if (bDefault) {
bRes = TBase::OnClick(pWnd, bDelay);
}
return bRes;
}
void CVerticalableToolBarComboBoxButton::OnChangeParentWnd(CWnd* pWndParent)
{
TBase::OnChangeParentWnd(pWndParent);
if (!m_bHorz & m_bDoVerticalMode) {
AdjustVerticalRect();
}
}
void CVerticalableToolBarComboBoxButton::OnMove()
{
TBase::OnMove();
if (!m_bHorz & m_bDoVerticalMode) {
AdjustVerticalRect();
}
}
void CVerticalableToolBarComboBoxButton::OnSize(int iSize)
{
TBase::OnSize(iSize);
if (!m_bHorz & m_bDoVerticalMode) {
AdjustVerticalRect();
}
}
void CVerticalableToolBarComboBoxButton::AdjustVerticalRect()
{
ASSERT(m_bDoVerticalMode);
ASSERT(!m_bHorz);
if (m_pWndCombo->GetSafeHwnd() == NULL || m_rect.IsRectEmpty()) {
m_rectCombo.SetRectEmpty();
m_rectButton.SetRectEmpty();
return;
}
CMFCToolBar* pParentBar = nullptr;
{
CWnd* pNextBar = m_pWndCombo->GetParent();
while (pParentBar == nullptr && pNextBar != nullptr) {
pParentBar = DYNAMIC_DOWNCAST(CMFCToolBar, pNextBar);
pNextBar = pNextBar->GetParent();
}
}
if (IsCenterVert() && (!m_bTextBelow || m_strText.IsEmpty()) && (pParentBar != nullptr))
{
const int nRowHeight = pParentBar->GetRowHeight();
const int yOffset = std::max<>(0, (nRowHeight - m_rect.Height()) / 2);
m_rect.OffsetRect(0, yOffset);
}
{
CRect rect;
m_pWndCombo->GetWindowRect(&rect);
const int nWidth = std::max<>(rect.Width(), m_iWidth);
rect.left = m_rect.left;
rect.top = m_rect.top;
rect.right = m_rect.left + nWidth;
rect.bottom = m_rect.top + m_nDropDownHeight;
if ((pParentBar != nullptr) && pParentBar->IsDocked()) {
const UINT nID = pParentBar->GetParentDockSite()->GetDockSiteID();
if (nID == AFX_IDW_DOCKBAR_RIGHT) {
rect.left = m_rect.right - nWidth;
rect.right = m_rect.right;
}
}
m_pWndCombo->SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_NOZORDER | SWP_NOACTIVATE);
m_pWndCombo->SetEditSel(-1, 0);
}
{
m_pWndCombo->GetWindowRect(&m_rectCombo);
m_pWndCombo->ScreenToClient(&m_rectCombo);
m_pWndCombo->MapWindowPoints(m_pWndCombo->GetParent(), &m_rectCombo);
}
if (m_bFlat) {
m_rectButton = m_rectCombo;
}
else {
m_rectButton.SetRectEmpty();
}
}
// CVerticalableToolBarComboBoxButton
/////////////////////////////////////////////////////////////////////////////

How To Convert C# Code into Android (Motion Detection )

public class MotionDetector1 : IMotionDetector
{
private IFilter grayscaleFilter = new GrayscaleBT709( );
private Difference differenceFilter = new Difference( );
private Threshold thresholdFilter = new Threshold( 15 );
private IFilter erosionFilter = new Erosion( );
private Merge mergeFilter = new Merge( );
private IFilter extrachChannel = new ExtractChannel( RGB.R );
private ReplaceChannel replaceChannel = new ReplaceChannel( RGB.R, null );
private Bitmap backgroundFrame;
private BitmapData bitmapData;
private bool calculateMotionLevel = false;
private int width; // image width
private int height; // image height
private int pixelsChanged;
// Motion level calculation - calculate or not motion level
public bool MotionLevelCalculation
{
get { return calculateMotionLevel; }
set { calculateMotionLevel = value; }
}
// Motion level - amount of changes in percents
public double MotionLevel
{
get { return (double) pixelsChanged / ( width * height ); }
}
// Constructor
public MotionDetector1( )
{
}
// Reset detector to initial state
public void Reset( )
{
if ( backgroundFrame != null )
{
backgroundFrame.Dispose( );
backgroundFrame = null;
}
}
// Process new frame
public void ProcessFrame( ref Bitmap image )
{
if ( backgroundFrame == null )
{
// create initial backgroung image
backgroundFrame = grayscaleFilter.Apply( image );
// get image dimension
width = image.Width;
height = image.Height;
// just return for the first time
return;
}
Bitmap tmpImage;
// apply the grayscale file
tmpImage = grayscaleFilter.Apply( image );
// set backgroud frame as an overlay for difference filter
differenceFilter.OverlayImage = backgroundFrame;
// apply difference filter
Bitmap tmpImage2 = differenceFilter.Apply( tmpImage );
// lock the temporary image and apply some filters on the locked data
bitmapData = tmpImage2.LockBits( new Rectangle( 0, 0, width, height ),
ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed );
// threshold filter
thresholdFilter.ApplyInPlace( bitmapData );
// erosion filter
Bitmap tmpImage3 = erosionFilter.Apply( bitmapData );
// unlock temporary image
tmpImage2.UnlockBits( bitmapData );
tmpImage2.Dispose( );
// calculate amount of changed pixels
pixelsChanged = ( calculateMotionLevel ) ?
CalculateWhitePixels( tmpImage3 ) : 0;
// dispose old background
backgroundFrame.Dispose( );
// set backgound to current
backgroundFrame = tmpImage;
// extract red channel from the original image
Bitmap redChannel = extrachChannel.Apply( image );
// merge red channel with moving object
mergeFilter.OverlayImage = tmpImage3;
Bitmap tmpImage4 = mergeFilter.Apply( redChannel );
redChannel.Dispose( );
tmpImage3.Dispose( );
// replace red channel in the original image
replaceChannel.ChannelImage = tmpImage4;
Bitmap tmpImage5 = replaceChannel.Apply( image );
tmpImage4.Dispose( );
image.Dispose( );
image = tmpImage5;
}
// Calculate white pixels
private int CalculateWhitePixels( Bitmap image )
{
int count = 0;
// lock difference image
BitmapData data = image.LockBits( new Rectangle( 0, 0, width, height ),
ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed );
int offset = data.Stride - width;
unsafe
{
byte * ptr = (byte *) data.Scan0.ToPointer( );
for ( int y = 0; y < height; y++ )
{
for ( int x = 0; x < width; x++, ptr++ )
{
count += ( (*ptr) >> 7 );
}
ptr += offset;
}
}
// unlock image
image.UnlockBits( data );
return count;
}
}
}

Why does this Dialog immediately dispose in this situation?

There is a user defined component , derived from Container, inside my Form. It has a pointerPressed method implemented in its class code. In the code of that method I show a Dialog containing a List , and in the class code of the derived Dialog ( in the constructor ) I set the setDisposeWhenPointerOutOfBounds method with the argument value to true.
The problem is that in run time when I click the user defined component ( ListBox ) in my Form then the Dialog is shown , of course , but immediately it closes ( disposes ) , although I don't click outside the boundary of the Dialog !
So why does it have such a behavior ?
Codes :
public class ListBox extends Container
{
private Form containerForm;
private Container cListBox = new Container(new BorderLayout());
private Label[] tLabel;
private int[] tLabelW;
private int largestLabelW;
private Label libelle = new Label();
private Label arrow = new Label((MenuPrincipalForm.r).getImage("listboxarrow"));
private int preferredWidth, preferredHeight, screenWidth, screenHeight;
private Vector vData = new Vector();
private final int leftPadding = 3;
private int listW;
private List list;
private DialogListBox dialog;
private String selectedData;
public ListBox(Form containingForm, String[] lData, int prefHeight, int formWidth, int formHeight, int topMargin, int bottomMargin)
{
super(new FlowLayout(Component.CENTER));
setFocusable(true);
containerForm = containingForm;
screenWidth = formWidth;
screenHeight = formHeight;
tLabel = new Label[lData.length + 1];
tLabelW = new int[lData.length + 1];
if (lData.length > 0)
{
for (int i = 0 ; i < lData.length + 1 ; i++)
{
if (i < lData.length)
{
vData.addElement(new String(lData[i]));
tLabel[i] = new Label(lData[i]);
tLabelW[i] = tLabel[i].getPreferredW();
}
else
{
vData.addElement(new String(""));
tLabel[i] = new Label("");
tLabelW[i] = 0;
}
}
}
else
{
vData.addElement(new String(""));
tLabel[0] = new Label("");
tLabelW[0] = 0;
}
largestLabelW = Comparator.max(tLabelW);
preferredWidth = leftPadding + largestLabelW + arrow.getPreferredW();
preferredHeight = prefHeight - 2 ;
selectedData = String.valueOf(vData.lastElement());
libelle.setText(String.valueOf(vData.lastElement()));
libelle.setTextPosition(Label.LEFT);
libelle.setPreferredW(preferredWidth);
libelle.setPreferredH(preferredHeight);
arrow.setAlignment(Label.CENTER);
arrow.setPreferredH(preferredHeight);
dialog = new DialogListBox(leftPadding, this);
list = dialog.getList();
cListBox.addComponent(BorderLayout.WEST, libelle);
cListBox.addComponent(BorderLayout.EAST, arrow);
cListBox.setPreferredH(preferredHeight);
getUnselectedStyle().setPadding(Component.LEFT, leftPadding);
getSelectedStyle().setPadding(Component.LEFT, leftPadding);
getUnselectedStyle().setBorder(Border.createLineBorder(1));
getSelectedStyle().setBorder(Border.createLineBorder(1));
addComponent(cListBox);
setPreferredH(preferredHeight);
getUnselectedStyle().setMargin(Component.TOP, topMargin);
getSelectedStyle().setMargin(Component.TOP, topMargin);
getUnselectedStyle().setMargin(Component.BOTTOM, bottomMargin);
getSelectedStyle().setMargin(Component.BOTTOM, bottomMargin);
}
public void setSelectedIndex(int idx)
{
list.setSelectedIndex(idx);
selectedData = String.valueOf(vData.elementAt(idx));
libelle.setText(String.valueOf(vData.elementAt(idx)));
repaint();
}
public void setSelectedData(String data)
{
selectedData = data;
libelle.setText(selectedData);
repaint();
}
public String getSelectedData()
{
return selectedData;
}
public int getLastIndex()
{
return vData.indexOf(vData.lastElement());
}
public Vector getListBoxDataSource()
{
return vData;
}
private void showListBoxDialog()
{
int espaceVertRestant, top, bottom, left, right;
espaceVertRestant = screenHeight - ( libelle.getAbsoluteY() + preferredHeight );
if (espaceVertRestant > list.getPreferredH())
{
top = getAbsoluteY() + preferredHeight - 1 ;
bottom = screenHeight - ( getAbsoluteY() + preferredHeight + list.getPreferredH() ) ;
}
else
{
top = screenHeight - ( list.getPreferredH() + preferredHeight + espaceVertRestant ) ;
bottom = getAbsoluteY() - 1 ;
}
left = getAbsoluteX() ;
right = screenWidth - ( getAbsoluteX() + getPreferredW() );
listW = screenWidth - left - right ;
containerForm.setTintColor(containerForm.getSelectedStyle().getBgColor());
dialog.setListW(listW);
dialog.show(top, bottom, left, right, false, false);
}
public void keyPressed(int keyCode)
{
int gameAction = (Display.getInstance()).getGameAction(keyCode);
if (gameAction == Display.GAME_FIRE)
showListBoxDialog();
else
super.keyPressed(keyCode);
}
public void pointerPressed(int x, int y)
{
showListBoxDialog();
}
}
public class DialogListBox extends Dialog implements ActionListener
{
private Vector vData;
private CListCellListBox listRenderer;
private List list;
private ListBox theListBox;
public DialogListBox(int leftPadding, ListBox listBox)
{
super();
setFocusable(true);
setDisposeWhenPointerOutOfBounds(true);
getContentPane().getSelectedStyle().setPadding(0, 0, 0, 0);
getContentPane().getUnselectedStyle().setPadding(0, 0, 0, 0);
getContentPane().getStyle().setPadding(0, 0, 0, 0);
theListBox = listBox;
listRenderer = new CListCellListBox(false);
vData = listBox.getListBoxDataSource();
list = (new CList(vData, false)).createList(listRenderer, this);
list.setItemGap(0);
list.setSelectedIndex(vData.indexOf(vData.lastElement()));
list.getSelectedStyle().setPadding(0, 0, leftPadding, 0);
list.getUnselectedStyle().setPadding(0, 0, leftPadding, 0);
list.getUnselectedStyle().setBorder(Border.createLineBorder(1), false);
list.getSelectedStyle().setBorder(Border.createLineBorder(1), false);
list.setIsScrollVisible(false);
addComponent(list);
}
protected void onShow()
{
list.requestFocus();
repaint();
}
public void setListW(int prefW)
{
list.setPreferredW(prefW);
}
public List getList()
{
return list;
}
private void refreshListBox()
{
dispose();
if (list.getSelectedItem() instanceof Content)
{
Content valeur = (Content)list.getSelectedItem();
theListBox.setSelectedData(valeur.getEnreg());
}
}
public void keyPressed(int keyCode)
{
int gameAction = (Display.getInstance()).getGameAction(keyCode);
if (gameAction == Display.GAME_FIRE)
refreshListBox();
else
super.keyPressed(keyCode);
}
public void actionPerformed(ActionEvent ae) {
if ( (ae.getSource() instanceof List) && ((List)ae.getSource()).equals(list) )
refreshListBox();
}
}
public class CList {
private Vector data = new Vector();
private boolean showPhoto;
private Content[] contents;
public CList(Vector vData, boolean displayPhoto)
{
data = vData;
showPhoto = displayPhoto;
contents = new Content[vData.size()];
}
public List createList(CListCell renderer, ActionListener listener)
{
List theList;
if (showPhoto)
{
for(int i = 0; i < data.size(); i++)
{
Image img = getFirstImage(Formatage.getColumnValueAt(String.valueOf(data.elementAt(i)), 0));
contents[i] = new Content(img, String.valueOf(data.elementAt(i)));
}
}
else
{
for(int i = 0; i < data.size(); i++)
{
contents[i] = new Content(String.valueOf(data.elementAt(i)));
}
}
theList = new List(contents);
theList.setListCellRenderer(renderer);
theList.setFixedSelection(List.FIXED_NONE_CYCLIC);
theList.addActionListener(listener);
return theList;
}
// ... other methods
}
You should always use pointerReleased/keyReleased for navigation to different forms/dialogs.
Otherwise the pointer/key released will be sent to the next form/dialog and trigger an action there.
Pointer pressed is mostly used internally in LWUIT and for some special cases.

Resources