How to make a dynamic grid of EditText - android-layout

I want to create Dynamic grid of edittext but it gives me an IllegalStateException:
The specific child already has a prent, You must call removeView()
on child parent first.
Here is my code:
for (int x = 0; x < no_of_rows; x++)
{
ll = new LinearLayout(this.getApplicationContext());
ll.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setOrientation(0);
for(int y = 0; y < no_of_columns; y++){
LinearLayout(this.getApplicationContext());
this.edittext2.add(new EditText(this.getApplicationContext()));
this.edittext2.get(y).setId(y);
this.edittext2.get(y).setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT
,LinearLayout.LayoutParams.WRAP_CONTENT));
this.edittext2.get(y).setMaxLines(1);
this.edittext2.get(y).setText("Something");
ll.addView(this.edittext2.get(y));
}
tlayout.addView(ll);
}

Related

Which items were selected during Unbounded Knapsack algorithm?

I am using 1D array to get the final answer, but I also need to get selected items. How to achieve that?
private static int UnboundedKnapsack(int capacity, int n, int[] itemValue, int[] itemWeight)
{
int[] dp = new int[capacity + 1];
for (int i = 0; i <= capacity; i++)
{
for (int j = 0; j < n; j++)
{
if (itemWeight[j] <= i)
{
dp[i] = Math.Max(dp[i], dp[i - itemWeight[j]] + itemValue[j]);
}
}
}
return dp[capacity];
}
Let's introduce a new path function that gives the optimal selcetions of items using the previously calculated dp array.
private static void path(int capacity, int n, int[] itemValue, int[] itemWeight, int[] dp){
if(capacity == 0) return; // here you handle when the function will end. I assume capacity should be empty at the last
int ans = 0, chosenItem;
for(int j = 0; j < n; j++){
int newAns = dp[capacity - itemWeight[j]] + itemValue[j];
if(newAns > ans){
ans = newAns;
chosenItem = j;
}
}
printf("%d ",chosenItem); // here you get the current item you need to select;
path(capacity - itemWeight[chosenItem], n, itemValue, itemWeight, dp);
}

Adding to a hashmap

public static HashMap<Integer, Point> fillCellsCreatures = new HashMap<Integer, Point>();
for(int i = 0; i < 4; i++){
Creature cre = new Creature();
cre.x = ((int)(Math.random() * ((30 - 10) +1)));
cre.y = ((int)(Math.random() * ((30 - 10) +1)));
cre.energy_level = 10;
//fillCellsCreatures.add(new Point(cre.x, cre.y));
fillCellsCreatures.put(cre.energy_level, new Point(cre.x, cre.y));
}
The code above is me trying to add to a hashmap that contains an int as the key and a Point as the value. When i add to the hashmap via the for loop it appears i am constantly rewriting over the same position and rather not moving to the next position to add the new value. Could someone please help clarify what i am doing wrong and point me in the right direction.
Cheers
If you need to change use following code,
public static HashMap<Integer, Point> fillCellsCreatures = new HashMap<Integer, Point>();
for(int i = 0; i < 4; i++){
Creature cre = new Creature();
cre.x = ((int)(Math.random() * ((30 - 10) +1)));
cre.y = ((int)(Math.random() * ((30 - 10) +1)));
cre.energy_level = 10 * i+1;
//fillCellsCreatures.add(new Point(cre.x, cre.y));
fillCellsCreatures.put(cre.energy_level, new Point(cre.x, cre.y));
}

How to maintain GridPane's fixed-size after adding elemnts dynamically

I need to create board game that can be dynamically change.
Its size can be 5x5, 6x6, 7x7 or 8x8.
I am jusing JavaFX with NetBeans and Scene builder for the GUI.
When the user choose board size greater than 5x5 this is what happens:
This is the template on the scene builder before adding cells dynamically:
To every cell in the GridPane I am adding StackPane + label of the cell number:
#FXML
GridPane boardGame;
public void CreateBoard()
{
int boardSize = m_Engine.GetBoard().GetBoardSize();
int num = boardSize * boardSize;
int maxColumns = m_Engine.GetNumOfCols();
int maxRows = m_Engine.GetNumOfRows();
for(int row = 0; row < maxRows ; row++)
{
for(int col = maxColumns - 1; col >= 0 ; col--)
{
StackPane stackPane = new StackPane();
stackPane.setPrefSize(150.0, 200.0);
stackPane.getChildren().add(new Label(String.valueOf(num)));
boardGame.add(stackPane, col, row);
num--;
}
}
boardGame.setGridLinesVisible(true);
boardGame.autosize();
}
The problem is the stack panes's size on the GridPane are getting smaller.
I tried to set them equal minimum and maximum size but it didn't help they are still getting smaller.
I searched on the web but didn't realy find same problem as mine.
The only similar problem to mine was found here:
Dynamically add elements to a fixed-size GridPane in JavaFX
But his suggestion is to use TilePane and I need to use GridPane because this is a board game and it more easier to use GridPane when I need to do tasks such as getting to cell on row = 1 and column = 2 for example.
EDIT:
I removed the GridPane from the FXML and created it manually on the Controller but now it print a blank board:
#FXML
GridPane boardGame;
public void CreateBoard()
{
int boardSize = m_Engine.GetBoard().GetBoardSize();
int num = boardSize * boardSize;
int maxColumns = m_Engine.GetNumOfCols();
int maxRows = m_Engine.GetNumOfRows();
boardGame = new GridPane();
boardGame.setAlignment(Pos.CENTER);
Collection<StackPane> stackPanes = new ArrayList<StackPane>();
for(int row = 0; row < maxRows ; row++)
{
for(int col = maxColumns - 1; col >= 0 ; col--)
{
StackPane stackPane = new StackPane();
stackPane.setPrefSize(150.0, 200.0);
stackPane.getChildren().add(new Label(String.valueOf(num)));
boardGame.add(stackPane, col, row);
stackPanes.add(stackPane);
num--;
}
}
this.buildGridPane(boardSize);
boardGame.setGridLinesVisible(true);
boardGame.autosize();
boardGamePane.getChildren().addAll(stackPanes);
}
public void buildGridPane(int i_NumOfRowsAndColumns)
{
RowConstraints rowConstraint;
ColumnConstraints columnConstraint;
for(int index = 0 ; index < i_NumOfRowsAndColumns; index++)
{
rowConstraint = new RowConstraints(3, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, VPos.CENTER, true);
boardGame.getRowConstraints().add(rowConstraint);
columnConstraint = new ColumnConstraints(3, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, HPos.CENTER, true);
boardGame.getColumnConstraints().add(columnConstraint);
}
}
Changed your code slightly with explanations in comments. HTH.
GridPane boardGame;
public void CreateBoard()
{
int boardSize = m_Engine.GetBoard().GetBoardSize();
int num = boardSize * boardSize;
int maxColumns = m_Engine.GetNumOfCols();
int maxRows = m_Engine.GetNumOfRows();
boardGame = new GridPane();
boardGame.setAlignment(Pos.CENTER);
Collection<StackPane> stackPanes = new ArrayList<StackPane>();
for(int row = 0; row < maxRows ; row++)
{
for(int col = maxColumns - 1; col >= 0 ; col--)
{
StackPane stackPane = new StackPane();
// To occupy fixed space set the max and min size of
// stackpanes.
// stackPane.setPrefSize(150.0, 200.0);
stackPane.setMaxSize(100.0, 100.0);
stackPane.setMinSize(100.0, 100.0);
stackPane.getChildren().add(new Label(String.valueOf(num)));
boardGame.add(stackPane, col, row);
stackPanes.add(stackPane);
num--;
}
}
// No need to add column and row constraints if you want just a uniform
// rigid grid view. So commented the line below.
// this.buildGridPane(boardSize);
boardGame.setGridLinesVisible(true);
boardGame.autosize();
// Here you are adding all stackpanes, those are added to the gridpane 'boardGame'
// before, to the another gridpane with name 'boardGamePane'. So all stackpanes are moved
// to this second gridpane. This is the reason of blank board you are seeing.
// So commenting this out also.
// boardGamePane.getChildren().addAll(stackPanes);
}

D3D11: Creating a cube map from 6 images

How do I create a cube map in D3D11 from 6 images? All the examples I've found use only one .dds. Specifically, how do I upload individual faces of the cube texture?
It works like this:
D3D11_TEXTURE2D_DESC texDesc;
texDesc.Width = description.width;
texDesc.Height = description.height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 6;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.CPUAccessFlags = 0;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
SMViewDesc.Format = texDesc.Format;
SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
SMViewDesc.TextureCube.MipLevels = texDesc.MipLevels;
SMViewDesc.TextureCube.MostDetailedMip = 0;
D3D11_SUBRESOURCE_DATA pData[6];
std::vector<vector4b> d[6]; // 6 images of type vector4b = 4 * unsigned char
for (int cubeMapFaceIndex = 0; cubeMapFaceIndex < 6; cubeMapFaceIndex++)
{
d[cubeMapFaceIndex].resize(description.width * description.height);
// fill with red color
std::fill(
d[cubeMapFaceIndex].begin(),
d[cubeMapFaceIndex].end(),
vector4b(255,0,0,255));
pData[cubeMapFaceIndex].pSysMem = &d[cubeMapFaceIndex][0];// description.data;
pData[cubeMapFaceIndex].SysMemPitch = description.width * 4;
pData[cubeMapFaceIndex].SysMemSlicePitch = 0;
}
HRESULT hr = renderer->getDevice()->CreateTexture2D(&texDesc,
description.data[0] ? &pData[0] : nullptr, &m_pCubeTexture);
assert(hr == S_OK);
hr = renderer->getDevice()->CreateShaderResourceView(
m_pCubeTexture, &SMViewDesc, &m_pShaderResourceView);
assert(hr == S_OK);
This creates six "red" images, for the CubeMap.
I know this question is old, and there is already a solution.
Here is a code example that loads 6 textures from disk and puts them together as a cubemap:
Precondition:
ID3D11ShaderResourceView* srv = 0;
ID3D11Resource* srcTex[6];
Pointer to a ShaderResourceView and an array filled with the six textures from disc. I use the order right, left, top, bottom, front, back.
// Each element in the texture array has the same format/dimensions.
D3D11_TEXTURE2D_DESC texElementDesc;
((ID3D11Texture2D*)srcTex[0])->GetDesc(&texElementDesc);
D3D11_TEXTURE2D_DESC texArrayDesc;
texArrayDesc.Width = texElementDesc.Width;
texArrayDesc.Height = texElementDesc.Height;
texArrayDesc.MipLevels = texElementDesc.MipLevels;
texArrayDesc.ArraySize = 6;
texArrayDesc.Format = texElementDesc.Format;
texArrayDesc.SampleDesc.Count = 1;
texArrayDesc.SampleDesc.Quality = 0;
texArrayDesc.Usage = D3D11_USAGE_DEFAULT;
texArrayDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texArrayDesc.CPUAccessFlags = 0;
texArrayDesc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
ID3D11Texture2D* texArray = 0;
if (FAILED(pd3dDevice->CreateTexture2D(&texArrayDesc, 0, &texArray)))
return false;
// Copy individual texture elements into texture array.
ID3D11DeviceContext* pd3dContext;
pd3dDevice->GetImmediateContext(&pd3dContext);
D3D11_BOX sourceRegion;
//Here i copy the mip map levels of the textures
for (UINT x = 0; x < 6; x++)
{
for (UINT mipLevel = 0; mipLevel < texArrayDesc.MipLevels; mipLevel++)
{
sourceRegion.left = 0;
sourceRegion.right = (texArrayDesc.Width >> mipLevel);
sourceRegion.top = 0;
sourceRegion.bottom = (texArrayDesc.Height >> mipLevel);
sourceRegion.front = 0;
sourceRegion.back = 1;
//test for overflow
if (sourceRegion.bottom == 0 || sourceRegion.right == 0)
break;
pd3dContext->CopySubresourceRegion(texArray, D3D11CalcSubresource(mipLevel, x, texArrayDesc.MipLevels), 0, 0, 0, srcTex[x], mipLevel, &sourceRegion);
}
}
// Create a resource view to the texture array.
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texArrayDesc.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
viewDesc.TextureCube.MostDetailedMip = 0;
viewDesc.TextureCube.MipLevels = texArrayDesc.MipLevels;
if (FAILED(pd3dDevice->CreateShaderResourceView(texArray, &viewDesc, &srv)))
return false;
If anyone reads this question again, maybe try this one. Warning: this function is not threadsafe, because i have to use the deviceContext.

SpriteBatch.Draw in rectangle

I want to make something like Terraria item sidebar thing. (the Left-top rectangles one). And here is my code.
Variables are
public Rectangle InventorySlots;
public Item[] Quickbar = new Item[9];
public Item mouseItem = null;
public Item[] Backpack = new Item[49];
public int selectedBar = 0;
Here is the initialization
inventory[0] = Content.Load<Texture2D>("Contents/Overlays/InventoryBG");
inventory[1] = Content.Load<Texture2D>("Contents/Overlays/InventoryBG2");
update method
int a = viewport.Width / 22;
for (int b = 0; b <= Quickbar.Length; ++b)
{
InventorySlots = new Rectangle(((a/10)*b)+(b),0,a,a);
}
draw method
spriteBatch.Begin();
for (int num = 0; num <= Quickbar.Length; ++num )
spriteBatch.Draw(inventory[0], InventorySlots, Color.White);
spriteBatch.Draw(inventory[1], InventorySlots, Color.White);
spriteBatch.End();
Yes it is not done, but when i try to run it, the texture didn't show up.
I am unable to find out what is wrong in my code.
is it in with SpriteBatch? In the draw method? or In the Update?
Resolved
The problem isnt at the code Itself. the Problem is in this:
int a = viewport.Width / 22;
The thing is, i trought that viewport in here (I've used a Starter Kit) is the Game Window!
You are assigning InventorySlots overwriting its content...
also it seems that you want to draw two sprites... but you are drawing only one inside the loop... and your looping over Quickbar when seems that its not related with your drawing calls.
And it seems that your slot layout calculations have few sense...
You should use an array or a list:
public List<Rectangle> InventorySlots = new List<Rectangle>();
// You put this code in update... but it's not going to change..
// maybe initialize is best suited
// Initialize
int a = viewport.Width / 22;
InventorySlots.Clear();
for (int b = 0; b < Quickbar.Length; ++b)
{ // Generate slots in a line, with a pixel gap among them
InventorySlots.Add( new Rectangle( 1 + (a+2) * b ,0,a,a) );
}
//Draw
spriteBatch.Begin();
for (int num = 0; num < InventorySlots.Count; ++num )
{
spriteBatch.Draw(inventory[0], InventorySlots[num], Color.White);
spriteBatch.Draw(inventory[1], InventorySlots[num], Color.White);
}
spriteBatch.End();

Resources