JList does not clear - swing

I have an issue with removing old elements from my lists. I tried using the methods clear() and removeAllElements() and removeAll() wherever I could but that does not seem to clear them.
To help you understand the situation a little bit better:
d1 is an ArrayList that contains all available devices in our program.
availList2 and availList3 are using the DefaultListModel.
We wanted to make it so that when the user loads the products from the proper text file, if he did that a second time the products already listed in our gui would be overwritten with the ones in the original text file. However we ended up having duplicates of the products, even though we used the clear() method in both the d1 (ArrayList) and the JList.
Any useful tips or possible causes would be appreciated. Thank you very much in advance.
if(ev.getSource() == load_availables) {
int returnVal = chooser.showOpenDialog(mainApp.this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
d1.returnDevices().removeAll(d1.returnDevices());
availList2.clear();
availList3.clear();
//availList2.removeAllElements();
//availList3.removeAllElements();
File file = chooser.getSelectedFile();
read.ReadDevices(file);
for(int i = 0; i < read.Size(); i++) {
d1.add_AvailableDevices(read.get(i));
}
}
}

If the list is not cleared then I would suggest you don't have the proper reference to the DefaultListModel that is being used by the JList when you invoke the clear() method.
Start by the reading the section from the Swing tutorial on How to Use Lists.
Download the ListDemo code and play with it. Change the "Fire" button to use the clear() method on the DefaultListModel to prove to yourself that is all you need to do.
Once you see the code working then you figure out how your code is different from the ListDemo working version.

Related

Android ListView binding programmatically

There are many examples of doing this in axml, but I would like to have a complete binding using code behind. To be honest, I would like to have NO axml, but seems like creating all the controls programmatically is a nightmare.
I first tried the suggestions at:
MvxListView create binding for template layout from code
I have my list binding from code-behind, and I get six rows (so source binding is working); but the cells itself does not bind.
Then at the following url:
Odd issue with MvvmCross, MvxListViewItem on Android
Stuart has the following comment: Have looked through. In this case, I don't think you want to use DelayBind. DelayBind is used to delay the binding action until next time the DataContext is set. In Android's MvxAdapter/MvxListItemView case, the DataContext is passed in the ctor - so DataContext isn't set again until the cell is reused. (This is different to iOS MvxTableDataSource).
So in essence, the only example I see shows DelayBind, which shouldn't work.
Can someone please show me some examples... thanks in advance.
Added reply to Comments:
Cheesebaron, first of all, a huge thank you and respect for all your contributions;
Now, why not use axml? Well, as programmers, we all have our own preferences and way of doing stuff - I guess I am old school where we didn't have any gui designer (not really true).
Real reasons:
Common Style: I have a setup where Core has all the style details, including what all the colors would be. My idea is, each platform would get the style details from core and update accordingly. It's easy for me to create controls with the correct style this way.
Copy-Paste across platform (which then I can even have as linked files if I wanted). For example, I have a login screen with web-like verification, where a red error text appears under a control; overall on that screen I have around 10 items that needs binding. I have already got iOS version working - so starting on Droid, I copied the whole binding section from ios, and it worked perfectly. So, the whole binding, I can make it same across all platform... Any possible error in my way will stop at building, which I think is a major advantage over axml binding. Even the control creation is extremely similar, where I have helpers with same method name.
Ofcourse I understand all the additional layout that has to be handled; to be honest, it's not that bad if one really think it through; I have created a StackPanel for Droid which is based on WP - that internally handles all the layouts for child views; so for LinearLayout, all I do is setup some custom parameters, and let my panel deal with it. Relative is a different story; so far, I have only one screen that's relative, and I can even make it Linear to reduce my additional layout code.
So, from my humble point of view, for my style, code-behind creation allows me to completely copy all my bindings (I do have some custom binding factories to allow that), copy all my control create lines; then only adding those controls to the view is the only part that is different (then again, droid and WP are almost identical). So there is no way I can miss something on one platform and all are forced to be the same. It also allows me to change all the styles for every platform just by changing the core. Finally, any binding error is detected during compile - and I love that.
My original question wasn't about NOT using axml... it was on how to use MvxListView where all the binding is done in code-behind; as I have explained, I got the list binding, but not the item/cell binding working.
Thanks again in advance.
Here is part of my LoginScreen from droid; I think it's acceptable amount of code for being without axml file.
//======================================================================================================
// create and add all controls
//======================================================================================================
var usernameEntry = ControlHelper.GetUITextFieldCustom(this, "Username.", maxLength: 20);
var usernameError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Username);
var passwordEntry = ControlHelper.GetUITextFieldCustom(this, "Password.", maxLength: 40, secureTextEntry: true);
var passwordError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Password);
var loginButton = ControlHelper.GetUIButtonMain(this);
var rememberMe = new UISwitch(this);
var joinLink = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var copyRightText = ControlHelper.GetUILabel(this, textAlignment: UITextAlignment.Center);
var copyRightSite = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var layout = new StackPanel(this, Orientation.Vertical)
{
Spacing = 15,
SubViews = new View[]
{
ControlHelper.GetUIImageView(this, Resource.Drawable.logo),
usernameEntry,
usernameError,
passwordEntry,
passwordError,
loginButton,
rememberMe,
joinLink,
ControlHelper.GetSpacer(this, ViewGroup.LayoutParams.MatchParent, weight: 2),
copyRightText,
copyRightSite
}
};
I just came across a similar situation myself using Mvx4.
The first link you mentioned had it almost correct AND when you combine it from Staurts comment in the second link and just remove the surrounding DelayBind call, everything should work out ok -
public class CustomListItemView
: MvxListItemView
{
public MvxListItemView(Context context,
IMvxLayoutInflater layoutInflater,
object dataContext,
int templateId)
: base(context, layoutInflater, dataContext, templateId)
{
var control = this.FindViewById<TextView>(Resource.Id.list_complex_title);
var set = this.CreateBindingSet<CustomListViewItem, YourThing>();
set.Bind(control).To(vm => vm.Title);
set.Apply();
}
}
p.s. I have asked for an Edit to the original link to help others.

AS3-Flash CS6 How to make a code that applies to all objects

Right, I am trying to make a game and I would like a bit of code that whenever I place makes something applies to all objects. For example I have: A background, Lamp, Player and Text. I would like it so I don't have to make the Lamp, Background and Text a symbol but have one bit of code that refers to them whenever I type it, so I don't have to list them all individually.
If you are looking to affect a specific, known set of display objects, you could add them into an array when they get created, and then use that array as your collection of objects to do whatever you need to.
Code here is procedural, not OOP, but should give you the gist. If you paste this into an FLA file and create the three objects (instances names) you'll have a decent sample of what this approach may be able to help you work with.
This can become more advanced, creates asa its own AS3 class, and be made smarted to handle whatever visual display changes that might be needed. But you only need ot make it as complicated as suits your needs.
var myDisplayObjs_arr:Array = [];
function addObj(obj:DisplayObject):void{
myDisplayObjs_arr.push(obj);
}
function affectObjs(config:Object):void{
// config object that includes things like alpha, colorTransform, whatever
for (var i:int = 0; i<myDisplayObjs_arr.length; i++){
var dispObj:DisplayObject = myDisplayObjs_arr[i];
if (config.alpha) {
dispObj.alpha = config.alpha;
}
if (config.scaleX) {
dispObj.scaleX = config.scaleX;
}
}
}
addObj(lamp);
addObj(background);
addObj(header_txt);
// Call affectObjs(), passing it an object of some basic changes
affectObjs({alpha:.5, scaleX:2});

What, other the .row() can cause a libgdx table to start a new row?

Bit of a mystery to me this, but I have a table in libgdx where everything is being positioned in new cells vertically;
I am not using .row() anywhere.
Probably doing something stupid here but I cant see it.
Clues as to what can cause this?
(I'll post the code if needed, but its not that neat, and seeing as I think knowing anything that can cause a newline will help me, it shouldn't necessarily be needed)
edit
Tried to cut the code down to all the bits that happen when an item gets added
Code;
//function that triggers on adding
//SSSNode is a semantic reference for the items details,it just justs made into a label like object
public void addItem(SSSNode itemsnode){
Item newitem = new Item(itemsnode); //Item extends label
allItems.add(newitem);
super.add(newitem).size(60, 30).top().left().fillY().expandY();
//pack();
//super.invalidate();
//super.validate(); (tried doing pack, validate, and none...neither helped)
//update the GUI bar in case the inventory tab isnt there yet
MainExplorationView.usersGUI.setDataVisible(true);
}
The following code is in "usersGUI", which creates and handles the popup called inventory which is whats in the picture and is the table I cant get to behave.
//ensures the interface for the inventory popup is setup and visible
//also refreshes the links
public void setDataVisible(boolean visible){
if (myContents.isVisible!=true){
myContents.isVisible=visible;
refreshlinks();
setupInventory();
}
}
private void refreshlinks() {
super.clearChildren();
super.addActor(backgroundobject);
super.addActor(ME.playersInventory); //re adds the inventory panel table?
int y = 440;
ME.playersInventory.validate(); //revalidated the table (I dumped this almost everywhere in frustration)
//below is not relevant, it updates other items in a onscreen gui
for (InterfaceButton link : allLinks) {
if (link.isVisible==true){
link.setPosition(5,y);
super.addActor(link);
y=y-30;
}
}
backgroundobject.setSize(85, 200);
backgroundobject.setPosition(0,y+20);
}
//ensures inventory is setup once.
public void setupInventory() {
if (setup){
return;
}
Log.info("setupInventory");
ME.playersInventory.setPrefWidth(super.getWidth());
Log.info("width is "+super.getWidth());
ME.playersInventory.setHeight(200);
ME.playersInventory.pack();
float X = myContents.getX();
float Y = myContents.getY()-ME.playersInventory.getHeight();
Log.info("popping up inventory at:"+X+","+Y);
ME.playersInventory.setPosition(X, Y);
super.validate();
setup=true;
}
The full code is also on GitHub;
https://github.com/ThomasWrobel/MeshExplorerGDX
The whole project is a game being made to demo/test and open source distributed semantic database system. The relevant bit is the inventory and the maybe the gui that creates it.
Anyone with good knowledge of LibGDXs workings should I think not need to look any of the code though if theres other things that can tell a table to start a new row. (ie, any layout restrictions that can cause it to happen automatically? )
layout ending the current row was a side effect to make the layout logic simpler. It is now fixed.
Note HorizontalGroup is still a better fit for your use case and has the benefit that you can add/remove actors at any index.
The answer seems to be that layout() causes new rows;
http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=15857&p=68533&hilit=layout#p68533
Adherently this is how its supposed to work, despite the docs not saying that.

AS3: Addchild dynamically using varying identifier names

Im currently learning as3 but I come from several years of as2 experience, so what I was used to do is attach movieclips using string with a numeric variable to get the right identifier like this and maybe I was thinking about using eval here but of course its not available in as3 so here is what I was doing in as2:
currentlevel=1;
myString = "levelMc"+currentlevel;
And then of course use the constructed string in "attachMovie" function to get the right clip attached.
attachMovie(myString,myString+mydepth,mydepth);
But I see in as3 all is about classes and all different so I cant seem to find a way to dynamically get the right class name for the child to be added, is there an actual way to make that possible? because as far as I have gone I see that I should get the class name to make new object and then put that in "addChild" so therefore I cant find a way to pass any kind of dynamically constructed string or element refering my needed clip there, is it still possible?.
Thanks beforehand for any clues =)
EDIT I added the attachmovie call as a clarifying line, I know all you got what I was asking but as I cant find a right approach I prefer to clarify. Additionally I shouldnt have mentioned the "eval" here, sorry, I just can ask my as2 with string usage
EDIT Solved, thanks to you all guys, you saved me, I wish I could give you all kudos because all of your ideas and tips are awesome and really helpful, I marked that answer as correct because it was the one that lead me to getDefinitionByName which is what Im going to use in the end, but as said all tips and ideas to face new as3 world will help me greatly, so as said I wish I could give reputation to you all, thanks a lot =)
You still can set a name for your object, for instance:
var mc : MovieClip;
for (var i : int = 0; i < 5; i++) {
mc = new MovieClip();
mc.name = "myMc"+ i;
addChild(mc);
}
and you can get a specific child using:
this["myMc1"] as MovieClip
or
this["myMc"+ i] as MovieClip;
How about a simple array?
Because if you only need to access a set of levels in a ascending numeric fashion, this approach is easier.
var levels:Array = new Array();
levels[0] = //your level1 movieclip
levels[1] = //your level2 movieclip
...
function jumpToLevel(index:int):void{
//remove added levels beforehand
removeChildren(); //assuming the only children you added to this displaylist
//are levels, otherwise you will need another approach
addChild(levels[index]);
}
In AS2, we would store information about instances in instance name - button_0, button_1, etc. In AS3, you don't need/use instance names for anything other than keeping your code clear to you and to reference stuff you create by hand.
Use arrays to reference your instances. So, if you're making buttons, you create a button and push it into an array of buttons. Then just reference it as aMyButtons[i] instead of mcMyButtons["button_" + i]
Here's example code.
function fCreateButtons(): void {
var i: int = 0;
for (i = 0; i < 5; i++) {
var mcNewButton: McButton = new McButton();
mcNewButton.x = i * 200;
mcNewButton.iButtonNumber = i;
mcNewButton.tMain.text = "About Us";
mcNewButton.bButton.addEventListener(MouseEvent.MOUSE_DOWN, fButtonPress);
mcNewButton.bButton.addEventListener(MouseEvent.MOUSE_OVER, fButtonOver);
mcNewButton.bButton.addEventListener(MouseEvent.MOUSE_OUT, fButtonOut);
aButtons.push(mcNewButton);
}
}
function fButtonPress(e: MouseEvent): void {
var iButtonNumber: int = e.currentTarget.parent.iButtonNumber;
trace("fButtonPress(): iButtonNumber: " + iButtonNumber);
}
This is how you'd add the buttons to a holder clip and remove them.
mcButtonsHolder.addChild(aButtons[i]);
mcButtonsHolder.removeChild(aButtons[i]);
Well as I said above I managed to solve it finally using getDefinitionByName which is the closer I think I can get to "eval", that function managed to bring dinamycally formed class name to be used to call the new clips on run time which is perfect for me, at least make the code cleaner and easier to change if needed. As I said in last edit, thanks a lot to you all who helped, all your tips and ideas will be of great use for me in the as3 time, wish I could give you all reputation, thanks a lot =).

Linq to SQL - Turn off UpdateCheck in code

I am wanting to turn off the UpdateCheck functionality for all members (except their primary keys). Now I was following the example below as guidance, however my MetaDataMembers of the table are still set to Always.
http://www.the-lazy-coder.com/2013/04/set-updatecheck-to-never.html
The above code snippet just gets you to change the attribute, however it seems to never get picked up, as I can debug the code when it is running and I see all the properties being set, so I am presuming that the attributes changing does not change the underlying object.
Now if I were to change approach and just get the MetaDataMembers directly from the RowType I notice they have the UpdateCheck property, however only a getter. So is there a way to (via reflection if needed) overwrite this property once it is set? Even after looking at decompiled source it is an abstract class and I cannot find any implementations to use for reference.
I am using SQLMetal to generate the Context files, so there is no designer tinkering available, and although some people will say that I should run some text editing macros to parse and change the attributes, it all sounds too long winded when I should just be able to go into the object in memory and tell it to ignore whatever it has been told previously.
SO! Is there a way to override the property in the entities? I have tried running the original code in that link in both constructor, after the objects created and just before I am about to do an update, however none of the changes seem to stick or at least propagate to where it matters, and there is hardly any material on how to do any of this progmatically.
After searching around the internet I found no nice way to do it, and although there is the link I mentioned originally it doesn't work as it works on the attributes which are partly right but in the case above they are working on the attributes which are not in memory and are just the decorations, anyway the code below seems to work but is not nice:
public static void SetUpdateCheckStatus(this IDataContext dataContext, UpdateCheck updateCheckStatus)
{
var tables = dataContext.Mapping.GetTables();
foreach (var table in tables)
{
var dataMembers = table.RowType.DataMembers;
foreach (var dataMember in dataMembers)
{
if (!dataMember.IsPrimaryKey)
{
var dataMemberType = dataMember.GetType();
if (dataMemberType.Name == "AttributedMetaDataMember")
{
var underlyingAttributeField = dataMember.GetType().GetField("attrColumn", BindingFlags.Instance | BindingFlags.NonPublic);
if (underlyingAttributeField != null)
{
var underlyingAttribute = underlyingAttributeField.GetValue(dataMember) as ColumnAttribute;
if (underlyingAttribute != null)
{ underlyingAttribute.UpdateCheck = updateCheckStatus; }
}
}
else
{
var underlyingField = dataMember.Type.GetField("updateCheck", BindingFlags.Instance | BindingFlags.NonPublic);
if (underlyingField != null)
{ underlyingField.SetValue(dataMember, updateCheckStatus); }
}
}
}
}
}
The IDataContext is just a wrapper we put around a DataContext for mocking purposes, so feel free to change that to just DataContext. It is written extremely defensively as this way pulls back lots of members which do not have all the desired data so it has to filter them out and only work on the ones which do.