Binary searchTree traversal display nodes up to N level - c#-3.0

I want to display nodes up to 3 level. Here I'm writing code using Level order(BFS). Each node having 2 childrens. I'm not sure how to increase level after displaying that level data and want to display up to 3 level.
public Void LevelOrder()
{
Queue q = new Queue();
int level=1;
q.Enqueue(root);
while (!q.empty() && level<=3)
{
level++;
Node n = q.DeQueue();
Console.Writeln(n.Value);
if (n.left !=null)
{
q.EnQueue(n.left);
}
if (n.right !=null)
{
q.EnQueue(n.right);
}
}
}

private static void Main(string[] args)
{
var root = new Node
{
Val = 0,
Left = new Node {Val = 1, Left = new Node {Val = 2, Left = new Node() {Val = 3}}},
Right = new Node() {Val = 1, Right = new Node() {Val = 2, Right = new Node() {Val = 3,Left = new Node(){Val = 4}}}}
};
Printbylevel(root, 5);
Console.ReadLine();
}
public static void Printbylevel(Node root, int depth)
{
Stack<Node> activenodes = new Stack<Node>();
Stack<Node> nextnodes = new Stack<Node>();
activenodes.Push(root);
var level = 0;
while (activenodes.Any())
{
level++;
if (level == depth+1) return;
Console.WriteLine("\n----{0}----", level);
while (activenodes.Any())
{
var current = activenodes.Pop();
if (current == null) continue;
Console.Write(current.Val);
nextnodes.Push(current.Left);
nextnodes.Push(current.Right);
}
while (nextnodes.Any())
{
activenodes.Push(nextnodes.Pop());
}
}
}
}
internal class Node
{
public int Val;
public Node Right { get; set; }
public Node Left { get; set; }
}

Related

Item in ScrollView is not seen in Scene, but it shows in hierarchy

I am trying to display a list, generated dinamically. I created a prefab with the things I need in it (a TextView, 3 TMP_InputFields and 2 Buttons.)
To manage the different list items, I created a script (SkillManager, since the items represents skill the player can choose), which I attached to the prefab.
Then, I add every item (currently I am adding only one for testing purposes) to a List, iterate that list, and add the prefab to the Content of a ScrollView:
for(int i = 0; i < listaSkills.Count; i++)
{
GameObject listItem = Instantiate(SkillPrefab) as GameObject;
listItem.GetComponent<SkillManager>().skill = listaSkills[i];
//listItem.transform.SetParent(SkillsContent.transform, false);
listItem.transform.parent = SkillsContent.transform;
}
When I run this, no item is seen in the ScrollView, but I can see the SkillItem added to the hierarchy:
If I move to Scene tab after playing, I see a square with red lines crossing it:
Why is my item not displaying? Why the red cross? How can I populate my ScrollView?
EDIT:
This is the code of SkillManager, the script added to SkillPrefab:
public class SkillManager : MonoBehaviour
{
public TMP_InputField toSpend;
public TMP_InputField rangos;
public TMP_InputField modificadores;
public TMP_InputField total;
public Button plusButton;
public Button minusButton;
public TMP_Text nombre;
public Skill skill;
private int modificador;
private int pointsToSpend;
private int totalPoints;
// Start is called before the first frame update
void Start()
{
print("Start");
if(total!=null)
total.text = "0";
if(modificadores!=null)
modificadores.text = "0";
if (toSpend != null)
{
toSpend.GetComponent<TMP_InputField>().text = GetSkillPoints();
totalPoints = int.Parse(total.GetComponent<TMP_InputField>().text);
pointsToSpend = int.Parse(toSpend.GetComponent<TMP_InputField>().text);
}
else
{
GameObject GameObjectToSpend = GameObject.FindGameObjectWithTag("tospend");
toSpend = GameObjectToSpend.GetComponent<TMP_InputField>();
if (toSpend == null)
{
print("Sigue siendo nulo");
}
else
{
toSpend.text= GetSkillPoints();
//totalPoints = int.Parse(total.GetComponent<TMP_InputField>().text);
if(total!=null)
totalPoints = int.Parse(total.text);
if(toSpend!=null)
pointsToSpend = int.Parse(toSpend.text);
}
}
if (skill != null)
{
modificador = GetModificador(skill);
string sModificador = modificadores.GetComponent<TMP_InputField>().text;
int iModificador = int.Parse(sModificador);
modificadores.GetComponent<TMP_InputField>().text = iModificador.ToString();
}
if (plusButton != null)
{
plusButton.onClick.AddListener(PlusButtonClicked);
minusButton.onClick.AddListener(MinusButtonClicked);
}
}
private string GetSkillPoints()
{
return "1";
}
public void MinusButtonClicked()
{
string ranks = rangos.GetComponent<TMP_InputField>().text;
int ranksInt = int.Parse(ranks);
if (ranksInt > 0)
{
int newRank = ranksInt - 1;
pointsToSpend += 1;
rangos.GetComponent<TMP_InputField>().text = newRank.ToString();
toSpend.GetComponent<TMP_InputField>().text = pointsToSpend.ToString();
total.GetComponent<TMP_InputField>().text = (newRank + modificador).ToString();
skill.Puntos = newRank;
}
}
public void PlusButtonClicked()
{
string ranks=rangos.GetComponent<TMP_InputField>().text;
int ranksInt = int.Parse(ranks);
Character character = Almacen.instance.Character;
int level = character.CharacterLevel;
if (ranksInt < level && pointsToSpend > 0)
{
int newRank = ranksInt + 1;
rangos.GetComponent<TMP_InputField>().text = newRank.ToString();
pointsToSpend -= 1;
toSpend.GetComponent<TMP_InputField>().text = pointsToSpend.ToString();
total.GetComponent<TMP_InputField>().text = (newRank + modificador).ToString();
skill.Puntos = newRank;
}
}
private int GetModificador(Skill skill)
{
int retorno=0;
if (skill.Clasea)
{
retorno += 3;
}
else
{
retorno += 0;
}
retorno += GetModificadorCaracteristica();
return retorno;
}
private int GetModificadorCaracteristica()
{
Utils utils = new Utils();
int retorno = 0;
int characteristic=0;
switch (skill.Caracteristica)
{
case "Fue":
characteristic = Almacen.instance.Character.EffectiveStr;
break;
case "Des":
characteristic = Almacen.instance.Character.EffectiveDex;
break;
case "Con":
characteristic = Almacen.instance.Character.EffectiveCon;
break;
case "Int":
characteristic = Almacen.instance.Character.EffectiveInt;
break;
case "Sab":
characteristic = Almacen.instance.Character.EffectiveWis;
break;
case "Car":
characteristic = Almacen.instance.Character.EffectiveCha;
break;
}
retorno = utils.GetCharModifier(characteristic);
return retorno;
}
}
it looks like you instantiate the object as a GameObject. but this will not be seen in the canvas because it isn't a UI component. you may want to add a sprite or image to the component and instantiate that into the Canvas. it will look something like this:
public class SkillPrefab
{
//put all your variables here!!!
public Sprite skillSprite;
}
public class YourClassName : MonoBehaviour
{
[SerializeField]
public List<SkillPrefab> skills = new List<SkillPrefab>();
private void Update()
{
Sprite listItem = Instantiate(skills[0].skillSprite); //the index is the skill you want to spawn in the list.
}
}
this does take into account that you have made your skills into a list of skills that you can acces.

Have Dijkstra compute widest path

I would like to modify the dijkstra algorithm to compute the widest path. I know I have to change the sum to min and min to max but I am having difficulty making the changes in the code.
Please take a look at the code below and suggest where and how to make the changes. Thanks.
public class DijkstraAlgorithm {
private final List<Vertex> nodes;
private final List<Edge> edges;
private Set<Vertex> settledNodes;
private Set<Vertex> unSettledNodes;
private Map<Vertex, Vertex> predecessors;
private Map<Vertex, Integer> distance;
public DijkstraAlgorithm(Graph graph) {
// create a copy of the array so that we can operate on this array
this.nodes = new ArrayList<Vertex>(graph.getVertexes());
this.edges = new ArrayList<Edge>(graph.getEdges());
}
public void execute(Vertex source) {
settledNodes = new HashSet<Vertex>();
unSettledNodes = new HashSet<Vertex>();
distance = new HashMap<Vertex, Integer>();
predecessors = new HashMap<Vertex, Vertex>();
distance.put(source, 0);
unSettledNodes.add(source);
while (unSettledNodes.size() > 0) {
Vertex node = getMinimum(unSettledNodes);
settledNodes.add(node);
unSettledNodes.remove(node);
findMinimalDistances(node);
}
}
private void findMinimalDistances(Vertex node) {
List<Vertex> adjacentNodes = getNeighbors(node);
for (Vertex target : adjacentNodes) {
// looks at the connected nodes in the graph
if (getShortestDistance(target) > getShortestDistance(node) + getDistance(node, target)) // looks at the source (node), then at the adjacent nodes and then the target one by one
{
distance.put(target, getShortestDistance(node) + getDistance(node, target));
predecessors.put(target, node);
unSettledNodes.add(target);
}
}
}
private int getDistance(Vertex node, Vertex target) {
for (Edge edge : edges) {
if (edge.getSource().equals(node) && edge.getDestination().equals(target)) {
return edge.getWeight();
}
}
throw new RuntimeException("Should not happen");
}
private List<Vertex> getNeighbors(Vertex node) {
List<Vertex> neighbors = new ArrayList<Vertex>();
for (Edge edge : edges) {
if (edge.getSource().equals(node) && !isSettled(edge.getDestination())) {
neighbors.add(edge.getDestination());
}
}
return neighbors;
}
private Vertex getMinimum(Set<Vertex> vertexes) {
Vertex minimum = null;
for (Vertex vertex : vertexes) {
if (minimum == null) {
minimum = vertex;
} else {
if (getShortestDistance(vertex) < getShortestDistance(minimum)) {
minimum = vertex;
}
}
}
return minimum;
}
private boolean isSettled(Vertex vertex) {
return settledNodes.contains(vertex);
}
private int getShortestDistance(Vertex destination) {
Integer d = distance.get(destination);
if (d == null) {
return Integer.MAX_VALUE;
} else {
return d;
}
}
/*
* This method returns the path from the source to the selected target and
* NULL if no path exists
*/
public LinkedList<Vertex> getPath(Vertex target) {
LinkedList<Vertex> path = new LinkedList<Vertex>();
Vertex step = target;
// check if a path exists
if (predecessors.get(step) == null) {
return null;
}
path.add(step);
while (predecessors.get(step) != null) {
step = predecessors.get(step);
path.add(step);
}
// Put it into the correct order
Collections.reverse(path);
return path;
}
}
As far as I can see, I think I have to make changes to findMinimalDistances and getMinimum. I understand how both Dijkstra and Widest path work on paper but in terms of code, I'm having some difficulty.

Unity player freezing due to script but without error

My unity player keeps on freezing after a while, I know what script is causing it (if it is indeed a script that is causing it). since there's only one script I've edited when it started freezing. But I can't figure out WHY it is freezing!
Here is the script that is causing it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
//public GameObject allPlayersPrefab;
public GameObject allPlayers;
public Transform playerRed;
public Transform playerGreen;
//public Transform playerPurple;
//public Transform playerYellow;
//Tail redTail;
//Tail greenTail;
//Tail purpleTail;
//Tail yellowTail;
public float secondsBetweenGaps = 2f;
public float secondsToGap = .25f;
public float snakeSpeed = 3f;
public float turnSpeed = 200f;
public int biggerPickupDuration = 3;
public int smallerPickupDuration = 3;
public int speedPickupDuration = 2;
public int invinciblePickupDuration = 3;
public int maxPickups = 3;
public int spawnPickupThreshold = 5;
private GameObject[] currPickups;
public GameObject[] pickupTypes;
public Transform pickupsParent;
public int players = 2;
[HideInInspector]
public int alive;
public bool enableKeys = false;
public GameObject prefabTail;
public GameObject settingsMenu;
public GameObject startingPanel;
public Text scoreText;
public Text radiusText;
public Text speedText;
public Text winText;
private bool hasEnded = false;
[HideInInspector]
public bool playerWon = false;
public bool running;
public Snake[] snakes;
ButtonManager buttonManager;
Pickup[] pickups;
void Start() {
//InstantiateNewPlayers();
playerRed = allPlayers.transform.FindChild("Red");
playerGreen = allPlayers.transform.FindChild("Green");
snakes = allPlayers.GetComponentsInChildren<Snake>(true);
alive = players;
//redTail = playerRed.GetComponentInChildren<Tail>();
//greenTail = playerGreen.GetComponentInChildren<Tail>();
//purpleTail = playerPurple.GetComponentInChildren<Tail>();
//yellowTail = playerYellow.GetComponentInChildren<Tail>();
buttonManager = FindObjectOfType<ButtonManager>();
pickups = FindObjectsOfType<Pickup>();
playerRed.gameObject.SetActive(false);
playerGreen.gameObject.SetActive(false);
//playerPurple.gameObject.SetActive(false);
//playerYellow.gameObject.SetActive(false);
winText.enabled = false;
foreach(Snake snake in snakes) {
snake.scoreText.enabled = false;
}
}
void Update() {
if(Input.GetKey(KeyCode.Escape)) {
foreach(Snake snake in snakes) {
snake.score = 0;
snake.scoreText.text = "0";
}
buttonManager.anima.Play("BackToSettings");
playerWon = true;
ResetGame();
buttonManager.restartButt.gameObject.SetActive(false);
buttonManager.StopAllCoroutines();
buttonManager.countDownText.enabled = false;
winText.enabled = false;
foreach(Snake snake in snakes) {
snake.scoreText.enabled = false;
}
}
if(alive == 1 && !hasEnded) {
Transform lastPlayer;
foreach(Snake child in snakes) {
if(!child.dead) {
lastPlayer = child.transform.parent;
if(child.score >= int.Parse(scoreText.text)) {
Win(lastPlayer.name);
AllPlayersDead();
} else
AllPlayersDead();
break;
}
}
}
if(alive == 0) {
if(hasEnded)
return;
buttonManager.restartButt.gameObject.SetActive(true);
hasEnded = true;
running = false;
}
foreach(Snake child in snakes) {
if(child.score >= int.Parse(scoreText.text)) {
AllPlayersDead();
Win(child.transform.parent.name);
}
}
}
public void AllPlayersDead() {
if(hasEnded)
return;
buttonManager.restartButt.gameObject.SetActive(true);
hasEnded = true;
running = false;
}
void Win(string winningPlayer) {
foreach(Snake snake in snakes) {
snake.score = 0;
snake.scoreText.text = "0";
}
Debug.Log("Win got called");
winText.gameObject.SetActive(true);
winText.enabled = true;
winText.text = winningPlayer + " wins!";
playerWon = true;
running = false;
}
public void PlayerDied() {
foreach(Snake child in snakes) {
if(!child.dead) {
child.score += 1;
}
}
}
public IEnumerator SpawnPickups() {
while(enabled) {
Debug.Log("SpawnPickups running...");
if(running) {
if(pickupsParent.childCount < maxPickups) {
int type = Random.Range(0, pickupTypes.Length);
float X = Random.Range(-7f, 7f);
float Y = Random.Range(-3f, 3f);
Vector3 spawnPos = new Vector3(X, Y, 0);
/*GameObject newPickup = */Instantiate(pickupTypes[type], spawnPos, Quaternion.Euler(0, 0, 0), pickupsParent);
Debug.Log("SpawnPickups instantiated new pickup...");
yield return new WaitForSeconds(spawnPickupThreshold);
}
}
}
}
public void ResetGame() {
Debug.Log("Resetting everything...");
for(int i = 0; i < players; i++) {
Transform currPlayer = allPlayers.transform.GetChild(i);
currPlayer.GetComponentInChildren<Tail>().points.Clear();
currPlayer.GetComponentInChildren<Snake>().dead = false;
currPlayer.GetComponentInChildren<Snake>().invincible = false;
currPlayer.GetComponentInChildren<Snake>().posInformer.position = new Vector3(-20, 0, 0);
if(playerWon) {
currPlayer.GetComponentInChildren<Snake>().score = 0;
playerWon = false;
}
//currPlayer.GetComponentInChildren<LineRenderer>().positionCount = 0;
currPlayer.GetComponentInChildren<LineRenderer>().numPositions = 0;
List<Vector2> list = new List<Vector2>();
list.Add(new Vector2(0, 5));
list.Add(new Vector2(0, 6));
StopAllCoroutines();
for(int i2 = 0; i2 < pickups.Length; i2++) {
pickups[i2].StopAllCoroutines();
}
foreach(Transform pickup in pickupsParent) {
Destroy(pickup.gameObject);
}
currPlayer.GetComponentInChildren<EdgeCollider2D>().points = list.ToArray();
foreach(Transform child in currPlayer) {
if(child.CompareTag("PrefabTail")) {
Destroy(child.gameObject);
}
}
currPlayer.gameObject.SetActive(false);
currPlayer.GetComponentInChildren<Tail>().enabled = true;
Destroy(GameObject.FindWithTag("PrefabTail"));
turnSpeed = int.Parse(radiusText.text) * 10;
snakeSpeed = float.Parse(speedText.text);
alive = players;
hasEnded = false;
running = false;
}
Debug.Log("Resetting done.");
}
}
I do have a small suspection that the freezing has something to do with the SpawnPickups method and/or the part where it destroys the pickups in the ResetGame method.
Thanks!
Your method SpawnPickups is doing this.
When you call this coroutine, and enable is true and running is false, you never reach a "yield" instruction, so your while(enabled) is indeed a while(true)
Coroutines are not threads, they run on the main thread and if you block a coroutine like this one, you are blocking the game.
public IEnumerator SpawnPickups() {
while(enabled) {
Debug.Log("SpawnPickups running...");
if(running) {
if(pickupsParent.childCount < maxPickups) {
int type = Random.Range(0, pickupTypes.Length);
float X = Random.Range(-7f, 7f);
float Y = Random.Range(-3f, 3f);
Vector3 spawnPos = new Vector3(X, Y, 0);
/*GameObject newPickup = */Instantiate(pickupTypes[type], spawnPos, Quaternion.Euler(0, 0, 0), pickupsParent);
Debug.Log("SpawnPickups instantiated new pickup...");
yield return new WaitForSeconds(spawnPickupThreshold);
}
//Here you need some yield in case running is true but you reached maxPickups (this one is not necessary if you put the next one)
}
//Here you need some yield in case running is false
//yield return null; //this should be enough to prevent your game from freezing
}
}

Check manually a JMenuItem in a JPopUpMenu?

I have a JPopUpMenu with several JCheckBoxMenuItem's on it.
Actually what I would like to do is basicly to select an item of the JPopUpMenu with a specific index.
For exemple, a method like myPopUpMenu.setSelected(2), which would select "Algérie" in my JPopUpMenu.
The problem is that I don't know any method which would allow me to check an item manually...
Here's the code of my JPopUpMenu :
MainVue.java:
public class MainVue extends JFrame implements ActionListener {
private static final JScrollPopupMenu menuProduit = new JScrollPopupMenu();
private static final JScrollPopupMenu menuPays = new JScrollPopupMenu();
private static List<String> listeFiltres = new ArrayList<String>();
private String listeDeFiltres;
private String[] tableauFiltrePermanent;
private String listeFiltrePermanent;
private String[] tableauPays = { "Autres", "Afrique du sud", "Algérie", "Allemagne", "Arabie Saoudite", "Argentine",
"Australie", "Bangladesh", "Belgique", "Brésil", "Bulgarie", "Canada", "Chine", "Corée du sud", "Egypte",
"Emirats-Arabes Unis", "Espagne", "Etats-Unis", "Ethiopie", "Europe", "France", "Hongrie", "Inde",
"Indonésie", "Irak", "Iran", "Israél", "Italie", "Japon", "Jordanie", "Kazakhstan", "Koweit", "Liban",
"Libye", "Malaisie", "Maroc", "Mexique", "Monde", "Oman", "Pakistan", "Pays-Bas", "Philippines", "Poligne",
"Portugal", "Qatar", "République tchéque", "Roumanie", "Russie", "Taïwan", "Tunisie", "Turquie",
"Ukraine" };
private String[] tableauProduit = { "Blé", "Colza", "Mais", "Orge", "Orge de Brasserie", "Palme", "Soja",
"Tournesol", "Tourteaux De Colza", "Tourteaux de Soja", "Huile de Soja", "Huile De Colza" };
private List<JCheckBoxMenuItem> listJCBProduit = new ArrayList<JCheckBoxMenuItem>();
private List<JCheckBoxMenuItem> listJCBPays = new ArrayList<JCheckBoxMenuItem>();
public static PropertiesConfiguration prop;
public MainVue(Modele modele, Controleur controleur) throws ClassNotFoundException, SQLException, IOException {
prop = new PropertiesConfiguration("config.properties");
for (int i = 0; i < tableauProduit.length; i++) {
listJCBProduit.add(new JCheckBoxMenuItem(tableauProduit[i]));
}
for (int j = 0; j < listJCBProduit.size(); j++) {
JCheckBoxMenuItem produitActuel = listJCBProduit.get(j);
menuProduit.add(produitActuel);
produitActuel.addActionListener(new OpenAction(menuProduit, boutonProduit));
}
for (int i = 0; i < tableauPays.length; i++) {
listJCBPays.add(new JCheckBoxMenuItem(tableauPays[i]));
}
for (int j = 0; j < listJCBPays.size(); j++) {
JCheckBoxMenuItem paysActuel = listJCBPays.get(j);
menuPays.add(paysActuel);
paysActuel.addActionListener(new OpenAction(menuPays, boutonPays));
}
listeDeFiltres = "";
for (int p = 0; p < listeFiltres.size(); p++) {
String filtreActuel = listeFiltres.get(p);
if (listeDeFiltres == "") {
listeDeFiltres += filtreActuel;
} else {
listeDeFiltres += "," + filtreActuel;
}
}
prop.setProperty("listeFiltres", listeDeFiltres);
}
}
Here's the JScrollPopUpMenu component :
JScrollPopUpMenu.java:
package fr.views;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
public class JScrollPopupMenu extends JPopupMenu {
protected int maximumVisibleRows = 10;
public JScrollPopupMenu() {
this(null);
}
public JScrollPopupMenu(String label) {
super(label);
setLayout(new ScrollPopupMenuLayout());
super.add(getScrollBar());
addMouseWheelListener(new MouseWheelListener() {
#Override public void mouseWheelMoved(MouseWheelEvent event) {
JScrollBar scrollBar = getScrollBar();
int amount = (event.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL)
? event.getUnitsToScroll() * scrollBar.getUnitIncrement()
: (event.getWheelRotation() < 0 ? -1 : 1) * scrollBar.getBlockIncrement();
scrollBar.setValue(scrollBar.getValue() + amount);
event.consume();
}
});
}
private JScrollBar popupScrollBar;
protected JScrollBar getScrollBar() {
if(popupScrollBar == null) {
popupScrollBar = new JScrollBar(JScrollBar.VERTICAL);
popupScrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override public void adjustmentValueChanged(AdjustmentEvent e) {
doLayout();
repaint();
}
});
popupScrollBar.setVisible(false);
}
return popupScrollBar;
}
public int getMaximumVisibleRows() {
return maximumVisibleRows;
}
public void setMaximumVisibleRows(int maximumVisibleRows) {
this.maximumVisibleRows = maximumVisibleRows;
}
public void paintChildren(Graphics g){
Insets insets = getInsets();
g.clipRect(insets.left, insets.top, getWidth(), getHeight() - insets.top - insets.bottom);
super.paintChildren(g);
}
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
if(maximumVisibleRows < getComponentCount()-1) {
getScrollBar().setVisible(true);
}
}
public void remove(int index) {
// can't remove the scrollbar
++index;
super.remove(index);
if(maximumVisibleRows >= getComponentCount()-1) {
getScrollBar().setVisible(false);
}
}
public void show(Component invoker, int x, int y){
JScrollBar scrollBar = getScrollBar();
if(scrollBar.isVisible()){
int extent = 0;
int max = 0;
int i = 0;
int unit = -1;
int width = 0;
for(Component comp : getComponents()) {
if(!(comp instanceof JScrollBar)) {
Dimension preferredSize = comp.getPreferredSize();
width = Math.max(width, preferredSize.width);
if(unit < 0){
unit = preferredSize.height;
}
if(i++ < maximumVisibleRows) {
extent += preferredSize.height;
}
max += preferredSize.height;
}
}
Insets insets = getInsets();
int widthMargin = insets.left + insets.right;
int heightMargin = insets.top + insets.bottom;
scrollBar.setUnitIncrement(unit);
scrollBar.setBlockIncrement(extent);
scrollBar.setValues(0, heightMargin + extent, 0, heightMargin + max);
width += scrollBar.getPreferredSize().width + widthMargin;
int height = heightMargin + extent;
setPopupSize(new Dimension(width, height));
}
super.show(invoker, x, y);
}
protected static class ScrollPopupMenuLayout implements LayoutManager{
#Override public void addLayoutComponent(String name, Component comp) {}
#Override public void removeLayoutComponent(Component comp) {}
#Override public Dimension preferredLayoutSize(Container parent) {
int visibleAmount = Integer.MAX_VALUE;
Dimension dim = new Dimension();
for(Component comp :parent.getComponents()){
if(comp.isVisible()) {
if(comp instanceof JScrollBar){
JScrollBar scrollBar = (JScrollBar) comp;
visibleAmount = scrollBar.getVisibleAmount();
}
else {
Dimension pref = comp.getPreferredSize();
dim.width = Math.max(dim.width, pref.width);
dim.height += pref.height;
}
}
}
Insets insets = parent.getInsets();
dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);
return dim;
}
#Override public Dimension minimumLayoutSize(Container parent) {
int visibleAmount = Integer.MAX_VALUE;
Dimension dim = new Dimension();
for(Component comp : parent.getComponents()) {
if(comp.isVisible()){
if(comp instanceof JScrollBar) {
JScrollBar scrollBar = (JScrollBar) comp;
visibleAmount = scrollBar.getVisibleAmount();
}
else {
Dimension min = comp.getMinimumSize();
dim.width = Math.max(dim.width, min.width);
dim.height += min.height;
}
}
}
Insets insets = parent.getInsets();
dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);
return dim;
}
#Override public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
int width = parent.getWidth() - insets.left - insets.right;
int height = parent.getHeight() - insets.top - insets.bottom;
int x = insets.left;
int y = insets.top;
int position = 0;
for(Component comp : parent.getComponents()) {
if((comp instanceof JScrollBar) && comp.isVisible()) {
JScrollBar scrollBar = (JScrollBar) comp;
Dimension dim = scrollBar.getPreferredSize();
scrollBar.setBounds(x + width-dim.width, y, dim.width, height);
width -= dim.width;
position = scrollBar.getValue();
}
}
y -= position;
for(Component comp : parent.getComponents()) {
if(!(comp instanceof JScrollBar) && comp.isVisible()) {
Dimension pref = comp.getPreferredSize();
comp.setBounds(x, y, width, pref.height);
y += pref.height;
}
}
}
}
}
Thanks in advance for any help !
The index which you get from getIndex() method use as follows. You are adding ScrollBar in your JScrollPopupMenu at 0 index. So to remove casting error update your code as follow.
int index = getIndex("name");
((JCheckBoxMenuItem)menuProduit.getComponentAtIndex(index+1)).setState(true);

Calling Method by using String instead of ObjectName - Processing in Eclipse

I am trying to combine multiple sketches I had, by having them as classes in a single sketch and go through them by pressing keys.
I'm not sure I'm following the right method but I'm basically turning them on and off by using a boolean for each. I have something like:
package combiner;
public class Combiner extends PApplet {
//...
ClassNameOne s1;
ClassNameTwo s2;
//...
ClassNameNine s9;
// AllSketches //
boolean[] sketches;
int totalSketches = 9;
String str_ts = String.valueOf(totalSketches);
char char_ts = str_ts.charAt(0);
public void setup() {
size(1920, 1080);
sketches = new boolean[totalSketches];
for (int i = 0; i < sketches.length; i++) {
sketches[i] = false;
}
s1 = new ClassNameOne(this);
s2 = new ClassNameTwo(this);
//...
s9 = new ClassNameNine(this);
}
public void draw() {
//drawingEachSketchIfItsBoolean==True
if (sketches[0] == true) {
s1.run();
} else if (sketches[1] == true) {
s2.run();
//....
}
}
public void keyPressed() {
if (key >= '1' && key <= char_ts) {
String str_key = Character.toString(key);
int KEY = Integer.parseInt(str_key);
for (int i = 0; i < sketches.length; i++) {
sketches[i] = false;
}
sketches[KEY - 1] = true;
//initializingEachClassIfKeyPressed
if (KEY == 0) {
s1.init();
} else if (KEY == 1) {
s2.init();
}
//....
}
}
As you can see each Class has an .init and a .run method (used to be my setup + draw).
I was wandering if somehow I can loop to .init or .run them without having to write it once for each, something like:
for(int i=0;i<sketches.length;i++){
if(sketches[i]==true){
String str = String.valueOf(i+1);
str="s"+str; //str becomes the Object's name
??? str.run(); ???
}
}
The cleanest solution would be to create an interface Sketch, which must be implemented in your sketch classes then:
Sketch[] sketches;
int activeSketch = 0;
void setup(){
sketches = new Sketch[2];
sketches[0] = new SketchRed();
sketches[1] = new SketchGreen();
sketches[activeSketch].init();
}
void draw(){
sketches[activeSketch].draw();
}
interface Sketch{
void init();
void draw();
}
class SketchRed implements Sketch{
void init(){}
void draw(){
fill(255, 0, 0);
ellipse(width/2, height/2, 30, 30);
}
}
class SketchGreen implements Sketch{
void init(){}
void draw(){
fill(0, 255, 0);
ellipse(width/2, height/2, 30, 30);
}
}
void keyPressed(){
activeSketch++;
if(activeSketch >= sketches.length){
activeSketch = 0;
}
sketches[activeSketch].init();
}
I am not sure if the whole idea of representing different sketches as classes in a new sketch is really that good, but in any case there seems to be a possibilty in Java for obtaining a class from a String! Look for Class.forName() as described here: http://docs.oracle.com/javase/tutorial/reflect/class/classNew.htm
Keep in mind that you will obtain a class from this and not an instance yet!