C#: making a two-dimensional array of panels - panels

I'm trying to write some code that displays a grid of panels (grid[]) onto a larger panel (gridHolder). Here's my code so far:
public void setupPanels(int x, int y)
{
grid = new Panel[y, x];
this.Controls.Add(gridHolder);
gridHolder.Show();
gridHolder.Location = new Point(0 , 0);
gridHolder.Size = new Size(x * PANEL_SIZE, y * PANEL_SIZE);
for (int i = 0; i < grid.GetLength(0); i++)
{
for (int j = 0; j < grid.GetLength(1); j++)
{
gridHolder.Controls.Add(grid[i, j]);
grid[i, j].Location = new Point(i * PANEL_SIZE, j * PANEL_SIZE);
gridHolder.Size = new Size(PANEL_SIZE, PANEL_SIZE);
}
}
}
When I try to run the program, I get a debug error saying "NullReferenceException was unhandled". How can I fix my code?

Very far guess.. but try this:
In your Page_Load method alter the inner code so the line which calls setupPanels method will not call it on every entry but only in non-postback calls, should look something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
setupPanels(...)
}
Here is a full example:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:panel ID="gridHolder" runat="server"/>
</form>
</body>
</html>
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
SetupPanels(gridHolder, 40, 40, 6, 6);
}
private void SetupPanels(Panel panelsHolder, int widthPerPanel, int heightPerPanel, int panelsCountX, int panelsCountY)
{
panelsHolder.Style.Add("position","absolute");
panelsHolder.Width = widthPerPanel*panelsCountX;
panelsHolder.Height = heightPerPanel*panelsCountY;
for (int y = 0; y < panelsCountY; y++)
{
for (int x = 0; x < panelsCountX; x++)
{
var gridPanel = new Panel
{
Width = widthPerPanel,
Height = heightPerPanel,
BackColor = Color.SandyBrown,
BorderColor = Color.Black,
BorderWidth = 5,
};
gridPanel.Style.Add("position", "absolute");
gridPanel.Style.Add("top", (x*widthPerPanel) + "px");
gridPanel.Style.Add("left", (y*heightPerPanel) + "px");
panelsHolder.Controls.Add(gridPanel);
}
}
}
}

Related

JavaFX with Google Maps - Outstanding resource locks detected: D3D Vram Pool:

I'm writing a program that displays Google Map in JavaFX application. Below is a code:
public class Window {
private static JFXPanel fxContainer;
MyBrowser myBrowser;
double lat;
double lon;
WindowGPSServer windowsgpsserver;
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window().init();
}
});
}
public void init() {
fxContainer = new JFXPanel();
windowsgpsserver = new WindowGPSServer(fxContainer);
windowsgpsserver.setVisible(true);
// create JavaFX scene
Platform.runLater(new Runnable() {
#Override
public void run() {
//javaFX operations should go here
createScene();
}
});
}
private void createScene() {
myBrowser = new MyBrowser();
myBrowser.setCache(false);
Scene scene = new Scene(myBrowser);
fxContainer.setScene(scene);
this.windowsgpsserver.setMyBrowser(myBrowser);
}
}
and:
public class MyBrowser extends Pane {
double lat;
double lon;
MyBrowser myBrowser;
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
public MyBrowser() {
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) (tk.getScreenSize().getWidth()));
int ySize = ((int) tk.getScreenSize().getHeight());
xSize= new Double(xSize*0.75).intValue();
ySize= new Double(ySize*0.90).intValue();
webView.setPrefSize(xSize, ySize);
final URL urlGoogleMaps = getClass().getResource("demo.html");
webEngine.load(urlGoogleMaps.toExternalForm());
webEngine.setOnAlert(new EventHandler<WebEvent<String>>() {
#Override
public void handle(WebEvent<String> e) {
System.out.println(e.toString());
System.out.println(e.getData());
System.gc();
}
});
getChildren().add(webView);
}
public void ChangeLocation(String latit, String longi) {
lat = Double.parseDouble(latit);
lon = Double.parseDouble(longi);
webEngine.executeScript("" +
"window.lat = " + lat + ";" +
"window.lon = " + lon + ";" +
"document.goToLocation(window.lat, window.lon);"
);
}
}
and demo.html file:
<body style="height: 100%;" onload="mapaStart()">
<script type="text/javascript">
var map;
function mapaStart() {
//document.map = new google.maps.Map(document.getElementById("mapcanvas"));
var latlng = new google.maps.LatLng(35.857908, 10.598997);
var Options = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcanvas"), Options);
//var carMarkerImage = new google.maps.MarkerImage('resources/images/car.png');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(35.857908, 10.598997),
map: map,
draggable: false,
//icon: carMarkerImage,
title: "",
autoPan: true
});
var infobulle = new google.maps.InfoWindow({
content: "Aktualna pozycja"
});
google.maps.event.addListener(marker, 'mouseover', function() {
infobulle.open(map, marker);
});
document.goToLocation = function(x, y) {
alert("goToLocation, x: " + x +", y:" + y);
var latLng = new google.maps.LatLng(x, y);
marker.setPosition(latLng);
map.setCenter(latLng);
}
google.maps.event.addListener(map, 'zoom_changed', function() {
alert("ZOOM");
var MapOptions = {
scrollwheel: false
};
map.setOptions(MapOptions)
setTimeout(aaa, 1000);
});
}
function aaa() {
var MapOptions = {
scrollwheel: true
};
map.setOptions(MapOptions)
}
</script>
<div id="mapcanvas" style="width: 100%; height: 90%; border: 1px solid black; background: gray;">
</div>
</body>
</html>
fxContainer is added to JPanel and displayed in Swing application.
After starting program everything works just fine. But after zooming in and out a couple of times, program becomes unresponsive (hards to zoom, move map to sides) and following error is displayed:
"Outstanding resource locks detected:
D3D Vram Pool: 268 433 488 used (100,0%), 268 433 488 managed (100,0%), 268 435 456 total
39 total resources being managed
average resource age is 0.1 frames
0 resources at maximum supported age (0,000000)
35 resources marked permanent (89,700000)
2 resources have had mismatched locks (5,100000)
2 resources locked (5,100000)
35 resources contain interesting data (89,700000)
0 resources disappeared (0,000000)"
Can anybody help me to solve this problem?
Thank you
Martin
It is a known issue. Could you upvote this https://javafx-jira.kenai.com/browse/RT-36649.
Thanks ! :)

Some trouble with ComboBox in Ext.net

I have a Page which a FormPanel(there's a ComboBox in it) and a TreePanel(has a default root node) in it and open ViewState.
I set a value to ComboBox in GET.
When i GET the page the TreePanel's Store send a POST request(store read) before FormPane rendered in client,in this POST request the fromdata has no info about FormPane.
in the POST request recover the ComboBox.Value from ViewState,but in ComboBoxBase.LoadPostData() Ext.Net get value from formdata and cover ComboBox.Value without precondition
it's ComboBoxBase.LoadPostData() code
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
if (!this.EmptyText.Equals(text) && text.IsNotEmpty())
{
List<ListItem> items = null;
if (this.SimpleSubmit)
{
var array = state.Split(new char[] { ',' });
items = new List<ListItem>(array.Length);
foreach (var item in array)
{
items.Add(new ListItem(item));
}
}
else if(state.IsNotEmpty())
{
items = ComboBoxBase.ParseSelectedItems(state);
}
bool fireEvent = false;
if (items == null)
{
items = new List<ListItem>
{
new ListItem(text)
};
/*fireEvent = this.SelectedItems.Count > 0;
this.SelectedItems.Clear();
return fireEvent;
*/
}
foreach (var item in items)
{
if (!this.SelectedItems.Contains(item))
{
fireEvent = true;
break;
}
}
this.SelectedItems.Clear();
this.SelectedItems.AddRange(items);
return fireEvent;
}
else
{
if (this.EmptyText.Equals(text) && this.SelectedItems.Count > 0)
{
this.SelectedItems.Clear();
return true;
}
}
return false;
}
Look at Line 5 to 11,why not change like this
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.Value = text;
this.ResumeScripting();
Sample for this question
page file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<ext:ResourceManager ID="ResourceManager1" runat="server" DisableViewState="false"
AjaxViewStateMode="Enabled" ViewStateMode="Enabled"/>
<form id="form1" runat="server">
<ext:Viewport runat="server" ID="VP">
</ext:Viewport>
</form>
</body>
</html>
cs file
public partial class WebFormTest : System.Web.UI.Page
{
protected override void OnInitComplete(EventArgs e)
{
FP = new FormPanel();
FP.ID = "FP";
FP.Title = "FP";
FP.Region = Region.Center;
TF = new TextField();
TF.ID = "TF";
TF.FieldLabel = "TF";
CB = new ComboBox();
CB.ID = "CB";
CB.FieldLabel = "CB";
CB.Items.Clear();
CB.Items.Add(new ListItem("one", "1"));
CB.Items.Add(new ListItem("two", "2"));
Button test = new Button() { ID = "testbtn", Text = "test" };
test.Listeners.Click.Handler = "App.Store2.load()";
FP.TopBar.Add(new Toolbar() { Items = { test } });
FP.Items.Add(TF);
FP.Items.Add(CB);
GP = new GridPanel();
GP.ID = "GP";
GP.Title = "GP";
GP.Region = Region.East;
GP.Listeners.BeforeRender.Handler = "App.Store1.reload()";
BTN = new Button();
BTN.ID = "BTN";
BTN.Text = "click";
BTN.Icon = Icon.ArrowJoin;
BTN.DirectEvents.Click.Event += new ComponentDirectEvent.DirectEventHandler(Click);
TB = new Toolbar();
TB.Items.Add(BTN);
GP.TopBar.Add(TB);
Store1 = new Store();
Store1.ID = "Store1";
Store1.ReadData += new Store.AjaxReadDataEventHandler(WebFormTest_ReadData);
Model1 = new Model();
Model1.ID = "Model1";
Store1.Model.Add(Model1);
GP.Store.Add(Store1);
TP = new TreePanel();
TP.ID = "TP";
TP.Title = "TP";
TP.Region = Region.East;
TP.RootVisible = false;
TP.Root.Add(new Node() { NodeID = "test", Text = "test" });
Store2 = new TreeStore();
Store2.ID = "Store2";
Store2.ReadData += new TreeStoreBase.ReadDataEventHandler(Store2_ReadData);
TP.Store.Add(Store2);
VP.Items.Add(FP);
//VP.Items.Add(GP);
VP.Items.Add(TP);
if (!X.IsAjaxRequest)
{
CB.Value = "2";
TF.Value = "TEXT";
}
base.OnInitComplete(e);
}
FormPanel FP;
TextField TF;
ComboBox CB;
GridPanel GP;
Button BTN;
Toolbar TB;
Store Store1;
Model Model1;
TreePanel TP;
TreeStore Store2;
protected override void CreateChildControls()
{
base.CreateChildControls();
}
void Store2_ReadData(object sender, NodeLoadEventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
//if (!X.IsAjaxRequest)
//{
// this.Store1.DataSource = this.Data;
// this.Store1.DataBind();
//}
}
protected void Refresh(object sender, DirectEventArgs e)
{
}
bool flag = false;
protected void Click(object sender, DirectEventArgs e)
{
GP.GetStore().Reload();
flag = true;
}
protected override void OnPreRender(EventArgs e)
{
if (flag)
{
TF.Value = "asdasd";
}
base.OnPreRender(e);
}
protected void WebFormTest_ReadData(object sender, StoreReadDataEventArgs e)
{
}
private object[] Data
{
get
{
return new object[]
{
new object[] { "3m Co", 71.72, 0.02, 0.03, "9/1 12:00am" },
};
}
}
}
you also can discuss in Ext.net Forums
We committed the change to the SVN trunk. It will go to the next release (v2.3).
The change is similar to your one, but we decided not to change RawValue as well. Thank you for the report and suggested fix.
Fix (ComboBoxBase LoadPostData)
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();

How to highlight page numbers in PagedDataSource to paginate Repeater

I am using PagedDataSource To Paginate Repeater and it works fine but is there a way to highlight selected page number or make it bold. I tried css, itemcommand,and click event but no luck.
Thanks in advance
Repeater:
<asp:Repeater ID="repeaterPager" runat="server" OnItemCommand="repeaterPager_ItemCommand">
<ItemTemplate>
<asp:LinkButton CssClass="sayfaNo" ID="btnPage" CommandName="Page" CommandArgument="<%#Container.DataItem %>" runat="server">
<%# Container.DataItem %></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
CodeBehind :
private void MakeleleriGetir()
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT p.PostID,p.Title,p.DateTime,p.PostShort,p.CategoryID,i.SmallFileName,c.CategoryName From Posts as p inner join Resimler as i ON p.PostID = i.PostID inner join Categories as c On p.CategoryID = c.CategoryID", cnn);
DataTable dt = new DataTable();
da.Fill(dt);
PagedDataSource pds = new PagedDataSource();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 4;
pds.CurrentPageIndex = CurrentPage;
PageCount = pds.PageCount;
btnPrevious.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
if (pds.PageCount > 1)
{
repeaterPager.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pds.PageCount; i++)
{
{
pages.Add((i + 1).ToString());
}
}
repeaterPager.DataSource = pages;
repeaterPager.DataBind();
}
else
{
repeaterPager.Visible = false;
}
RepeaterPosts.DataSource = pds;
RepeaterPosts.DataBind();
}
protected int CurrentPage
{
get
{ // look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
{
return 0; // default to showing the first page
}
else
{
return (int)o;
}
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
public int PageCount
{
get
{
if (ViewState["_PageCount"] != null)
return Convert.ToInt32(ViewState["_PageCount"]);
else
return 0;
}
set
{
ViewState["_PageCount"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
repeaterPager.ItemCommand += new RepeaterCommandEventHandler(repeaterPager_ItemCommand);
}
protected void repeaterPager_ItemCommand(object source, RepeaterCommandEventArgs e)
{
CurrentPage = Convert.ToInt32(e.CommandArgument) - 1;
MakeleleriGetir();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
MakeleleriGetir();
}
protected void btnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
MakeleleriGetir();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
MakeleleriGetir();
}
}
}
Logic:
Use ItemDataBound event and compare currentpage with current value of btnPage. You may use FindControl to get the current btnPage value.
Hope that helps!
protected void repeaterPager_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//Enabled False for current selected Page index
LinkButton lnkPage = (LinkButton)e.Item.FindControl("btnPage");
if (lnkPage.CommandArgument.ToString() == (CurrentPage+1).ToString())
{
lnkPage.Enabled = false;
lnkPage.BackColor = System.Drawing.Color.FromName("#FFCC01");
}
}

Creating Tabmenu in j2me

Is there any way to create a Tab Menu in j2me?
I found a code but I am unable to understand it
In this code there is Tab Menu created which is in Canvas class and then Tab menu is created which is totally done in Canvas or painted. The only part I found difficult to grasp was the void go() method and then
When I try to draw anything above and below this code using paint method, it doesn't work - what's the problem?
Below is the code
// Tab Menu CANVAS class
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class TabMenuCanvas extends Canvas
{
TabMenu menu = null;
public TabMenuCanvas()
{
menu = new TabMenu(
new String[]{"Home", "News", "Community", "Your files", "Credits", "Events", "Blog", "Upload", "Forum Nokia"},
getWidth() - 20
);
}
protected void keyPressed(int key)
{
int gameAction = getGameAction(key);
if(gameAction == Canvas.RIGHT)
{
menu.goRight();
repaint();
}
else if(gameAction == Canvas.LEFT)
{
menu.goLeft();
repaint();
}
}
protected void paint(Graphics g)
{
g.translate(10, 30);
menu.paint(g);
g.translate(- 10, - 30);
}
}
// Tab Menu Class
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class TabMenu
{
int background = 0xffffff;
int bgColor = 0xcccccc;
int bgFocusedColor = 0x0000ff;
int foreColor = 0x000000;
int foreFocusedColor = 0xffffff;
int cornerRadius = 6;
int padding = 2;
int margin = 2;
Font font = Font.getDefaultFont();
int scrollStep = 20;
int selectedTab = 0; //selected tab index
int[] tabsWidth = null; //width of single tabs
int[] tabsLeft = null; //left X coordinate of single tabs
int tabHeight = 0; //height of tabs (equal for all tabs)
String[] tabs = null; //tab labels
int menuWidth = 0; //total menu width
int viewportWidth = 0; //visible viewport width
int viewportX = 0; //current viewport X coordinate
public TabMenu(String[] tabs, int width)
{
this.tabs = tabs;
this.viewportWidth = width;
initialize();
}
void initialize()
{
tabHeight = font.getHeight() + cornerRadius + 2 * padding; //[ same for all tabs]
menuWidth = 0;
tabsWidth = new int[tabs.length];
tabsLeft = new int[tabs.length];
for(int i = 0; i < tabsWidth.length; i++)
{
tabsWidth[i] = font.stringWidth(tabs[i]) + 2 * padding + 2 * cornerRadius;
tabsLeft[i] = menuWidth;
menuWidth += tabsWidth[i];
if(i > 0)
{
menuWidth += margin;
}
}
}
public void goRight()
{
go(+1);
}
public void goLeft()
{
go(-1);
}
private void go(int delta)
{
int newTab = Math.max(0, Math.min(tabs.length - 1, selectedTab + delta));
boolean scroll = true;
if(newTab != selectedTab && isTabVisible(newTab))
{
selectedTab = newTab;
if( (delta > 0 && tabsLeft[selectedTab] + tabsWidth[selectedTab] > viewportX + viewportWidth) ||
(delta < 0 && tabsLeft[selectedTab] < viewportX))
{
scroll = true;
}
else
{
scroll = false;
}
}
if(scroll)
{
viewportX = Math.max(0, Math.min(menuWidth - viewportWidth, viewportX + delta * scrollStep));
}
}
private boolean isTabVisible(int tabIndex)
{
return tabsLeft[tabIndex] < viewportX + viewportWidth &&
tabsLeft[tabIndex] + tabsWidth[tabIndex] >= viewportX;
}
public void paint(Graphics g)
{
int currentX = - viewportX;
g.setClip(0, 0, viewportWidth, tabHeight);
g.setColor(background);
g.fillRect(0, 0, viewportWidth, tabHeight);
for(int i = 0; i < tabs.length; i++)
{
g.setColor(i == selectedTab ? bgFocusedColor : bgColor);
g.fillRoundRect(currentX, 0, tabsWidth[i], tabHeight + cornerRadius, 2 * cornerRadius, 2 * cornerRadius);
g.setColor(i == selectedTab ? foreFocusedColor : foreColor);
g.drawString(tabs[i], currentX + cornerRadius + padding, cornerRadius + padding, Graphics.LEFT | Graphics.TOP);
currentX += tabsWidth[i] + margin;
}
}
}
When I try to draw anything above and below this code using paint method, it doesn't work
what of the paint methods you use to draw above and below? Pay attention that there are two methods named that way - first is in TabMenuCanvas, second is in TabMenu (second method is invoked from TabMenuCanvas#repaint).
whatever you would try to draw in TabMenuCanvas#paint will most likely be overwritten by setClip and fillRect when TabMenu#paint is invoked following repaint request
The only place where one can expect to be able to draw something visible seems to be in TabMenu#paint method, inside the clip area that is set there.
You can use GUI Libraries for J2ME,for example Lightweight User Interface Toolkit (LWUIT),Flemil have "tab menu".You can see list of GUI Libraries here.

getting JTextPane to scroll

How do I get JTextPane to scroll? In this example, JScrollPane is employed but as running the code will reveal, the scroll bar can be displayed but it is not functional.
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.text.*;
public class JTextPaneTester
{
JTextPane jtp = new JTextPane();
StyledDocument doc;
Style style;
JScrollPane jsp = new JScrollPane(jtp);
JTextPaneTester()
{
doc = (StyledDocument)jtp.getDocument();
style = doc.addStyle("fancy", null);
jsp.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
}
void append(String s)
{
try
{
doc.insertString(doc.getLength(), s, style);
}
catch (BadLocationException e) { assert false: "problem"; }
}
public static void main(String[] args)
{
JTextPaneTester thing = new JTextPaneTester();
for (int i = 0; i < 100; i++)
thing.append("nouns verbs adjectives \n");
JFrame f = new JFrame();
JPanel center = new JPanel();
f.add(center, BorderLayout.CENTER);
center.add(thing.jsp);
f.setSize(400, 400);
f.setVisible(true);
}
}
If I place the snippet
for (int i = 0; i < 100; i++) {
thing.append("nouns verbs adjectives \n");
}
after
f.setVisible(true);
it seems to work.

Resources