I have a ShortestPath class with a Dijkstra algorithm in it and a method called computeRoutes. I also have a form with a search button - I want to call the computeRoutes method from this button but can't figure out how to do this.
public class ShortestPath {
public static void computeRoutes(Node source){
source.minimumDistance = 0;
PriorityQueue<Node> nodeQueue = new PriorityQueue<Node>();
nodeQueue.add(source);
while(!nodeQueue.isEmpty()){
Node u = nodeQueue.poll();
for(Edge e : u.neighbours){
Node n = e.goal;
int weight = e.weight;
int distThruU = u.minimumDistance + weight;
if(distThruU < n.minimumDistance){
nodeQueue.remove(n);
n.minimumDistance = distThruU;
n.previousNode = u;
nodeQueue.add(n);
}
}
}
}
public static List<Node> getShortestRouteTo(Node goal){
List<Node> route = new ArrayList<Node>();
for(Node node = goal; node != null; node = node.previousNode)
route.add(node);
Collections.reverse(route);
return route;
}
}
public class BPForm extends javax.swing.JFrame {
....
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
(I want to call the computeRoutes method here)
In netbeans designer double click this button. It will open code for ActionListener(If you don't know what this is. you should have a look at event handling for buttons) for this button. Just call computeRoutes() here using an Object(Have you already created an object?) of ShortestPath Class.
i suppose you've implemented ActionListener, and in the code you have to overwrite
public void actionPerformed(ActionEvent e) {
if (e.getSource() == computeRoutes) {
// put the logic here
}
.....
}
You just need to implement OnClick Listener for button click event
and then just call your method
http://www.roseindia.net/java/example/java/awt/MouseClick.shtml
here is an example which will helps you
Related
I'm trying to randomly generate a tree structure of objects that look something like the following:
Branch parent = new Branch("Start");
Branch branch1 = new Branch(parent, "Branch 1");
Branch branch2 = new Branch(parent, "Branch 2");
Branch branch21 = new Branch(branch2, "Branch 2.1");
Branch branch22 = new Branch(branch2, "Branch 2.2");
I know how to create objects manually, and how to generate random numbers, and I've seen some stuff on randomly generating nodes for creating fractals, but I'm pretty lost all the sudden, as I've never had to programmatically generate objects before.
Any ideas as to where to start, or what technique to use would be appreciated.
Typically, when building such items it's good to have a designed in and out. Otherwise, you will find yourself having to support many methods of application to support the intended result.
Hope this helps!
Try something along the following :)
Branch start = new Branch();
CreateChildren(start);
const int ChildrenLimitCheck = 0;
private void CreateChildren(Branch parent) {
//Use a limit variable so that you can decrease, and if it's equal to a sepcific number(usually 0) exit.
int Limit = (int) (Math.random() * 5);
//Call the function that's recursive, inside of a function that isn't recursive. This gives you a clean way to interface with the recursive function without excessive lines of code in other areas
generateChildren(parent,Limit);
}
private void generateChildren(Branch parent,int limit) {
//Check to see if we've hit our minimum. If so, exit out of the logic
if(limit == ChildrenLimitCheck)
return;
//Specify the random number of branches created in this instance
int numberOfBranches = (int) (Math.random() * 5);
for (int i = 0; i < numberOfBranches; i++) {
Branch child = new Branch(parent);
parent.Children.Add(child);
//Depending on what you want to do, either pass i or pass limit. If you don't use limit, you can remove it from this function :)
//If you pass i, try doing:
//for (int i = numberOfBranches; i > 0; i--)
//So that you can eventually get down to 0, to automatically stop your recursive calls with the above return statement.
//Seems you just want to run a loop for xxx number of times. This will still grant that, but you won't have to guess the upper limit
//of numberOfBranches to exit on, and you'll be able to exit cleanly
//This may be what caused your stackoverflow error. For all recursive functions, you need an exit condition or it will run indefinately
generateChildren(child,--limit);
//generateChildren(child,i);
}
}
I do this quite often and I can definately help in some areas of efficiency.
Try logic similar to the following. Place a breakpoint at Console.Write to see depth. This is a C++ object oriented approach, which I personally prefer over LINQ for performance. I didn't fine tune this, so LINQ may be faster. But if you know what you're doing, you can significantly increase performance via custom methods and inheritance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication11
{
public class Branch
{
//Branch Name
public string BranchName { get; set; }
//Add depth
public List<Branch> Children = new List<Branch>();
//Add a parent
public Branch Parent = null;
public Branch()
{
}
public Branch(string BranchName)
{
this.BranchName = BranchName;
}
public Branch(Branch Parent, string BranchName)
{
this.Parent = Parent;
this.BranchName = BranchName;
}
//Internal Functions
public bool HasParent()
{
return this.Parent != null;
}
public Branch getParent()
{
return this.Parent;
}
}
//Wrap a list inside of a class so we can have leverage over the add, and create our own functions for our need
public class BranchList
{
public List<Branch> branchParentList = new List<Branch>();
public void AddBranchToParent(Branch parent, Branch child)
{
foreach (Branch node in branchParentList)
{
if (node == parent)
{
node.Children.Add(child);
}
}
}
public void AddBranchAsChild(string parent, Branch child)
{
foreach (Branch node in branchParentList)
{
if (node.BranchName == parent)
{
node.Children.Add(child);
return;//Exit out, don't do the other loop. We found it
}
//Depth
AddBranchAsChildInChildren(node, child,parent);
}
}
public void AddBranchAsChildInChildren(Branch branch,Branch Child,string parent)
{
foreach(Branch child in branch.Children)
{
if (child.BranchName == parent)
child.Children.Add(Child);
}
}
public void AddBranchAsChildInChildren(Branch branch, string Child, string parent)
{
foreach (Branch child in branch.Children)
{
if (child.BranchName == parent)
child.Children.Add(new Branch() { BranchName=Child });
}
}
public void AddBranchAsChild(string parent, string child)
{
foreach (Branch node in branchParentList)
{
if (node.BranchName == parent)
{
node.Children.Add(new Branch() { BranchName = child });
return;
}
//Depth
AddBranchAsChildInChildren(node, child, parent);
}
}
public void AddBranchAsParent(Branch Branch, Branch Child)
{
if (branchParentList.Contains(Branch) == false)
throw new Exception("Parent exists");
foreach (Branch b in branchParentList)
{
if (b == Child)
{
b.Parent = Branch;
}
}
}
public void AddParent(Branch Parent)
{
if (branchParentList.Contains(Parent))
throw new Exception("Parent exists");
this.branchParentList.Add(Parent);
}
}
//Wrap the list, use it as an interface
public class BranchManager
{
public BranchList branchList = new BranchList();
public BranchManager()
{
}
public void AddParent(Branch Branch)
{
branchList.AddParent(Branch);
}
public void AddBranchAsChild(Branch Parent, Branch Child)
{
branchList.AddBranchToParent(Parent, Child);
}
public void AddBranchAsChild(string ParentName, Branch Child)
{
branchList.AddBranchAsChild(ParentName, Child);
}
public void AddBranchAsChild(string ParentName, string ChildName)
{
branchList.AddBranchAsChild(ParentName, ChildName);
}
}
class Program
{
static void Main(string[] args)
{
/*
Branch parent = new Branch("Start");
Branch branch1 = new Branch(parent, "Branch 1");
Branch branch2 = new Branch(parent, "Branch 2");
Branch branch21 = new Branch(branch2, "Branch 2.1");
Branch branch22 = new Branch(branch2, "Branch 2.2");
*/
BranchManager branchManager = new BranchManager();
branchManager.AddParent(new Branch("Start"));
branchManager.AddBranchAsChild("Start", "Branch 1");
branchManager.AddBranchAsChild("Start", "Branch 2");
branchManager.AddBranchAsChild("Branch 2", "Branch 2.1");
branchManager.AddBranchAsChild("Branch 2", "Branch 2.2");
Console.WriteLine(branchManager.branchList.branchParentList.Count);
}
}
}
Best guess so far, using a recursive function to handle the randomly generating children & parents:
Branch start = new Branch();
generateChildren(start);
private void generateChildren(Branch parent) {
int numberOfBranches = (int) (Math.random() * 5);
for (int i = 0; i < numberOfBranches; i++) {
Branch child = new Branch(parent);
generateChildren(child);
}
}
It properly creates a list of Branch objects with linked parents. I ran into a StackOverflow error until I wrapped it in a counter that limits the total number of branches.
The real question is: Is there a non-recursive way to handle it?
I need some help on my class design or better said a reference to a common design pattern for a problem.
I am working in the aircraft industry. So far my programming skills are VBA and basic JAVA applications.
As an engineer my task is to create CAD Models for fixating components in and on to aircraft kitchens. To ensure a high reusability and to reduce development time I want to create a program which can recommend previous solutions.
Basically each aircraft operator can select from a catalog which galleys/kitchens (Monument) it would like to have installed. Inside these Monuments are multiple compartments. Inside a compartment we can install multiple equipment’s/components.
I would like to write a program which can tell me "you have installed these components together before -> In this compartment -> in that aircraft for that customer"
I have modeled the compartment, the monuments, and the aircraft. Each class extends form the same class BaseHolder:
public abstract class BaseHolder <I> {
private final ArrayList <I> heldItems = new ArrayList<I>();
public boolean addItem(final I i){
Objects.requireNonNull(i, "cannot add NULL");
return heldItems.add(i);
}
public boolean removeItem(I i){
return heldItems.remove(i);
}
public boolean contains(I i){
return heldItems.contains(i);
}
public int itemCount(){
return heldItems.size();
}
public boolean isEmpty(){
return heldItems.isEmpty();
}
public void Clear() {
heldItems.clear();
}
protected List<I> getHeldItems(){
return heldItems;
}
public I getElement(int n){
return heldItems.get(n);
}
}
public class Aircraft extends BaseHolder<Monument> {
// code
}
public class Monument extends BaseHolder<Compartment> {
private String name;
public Monument (String name){
this.setName(name);
}
// code
#Override
public boolean addItem(final Compartment c) {
Objects.requireNonNull(c, "cannot add NULL");
if (contains (c) ){
throw new IllegalArgumentException("Compartment already added!");
};
for(Compartment ctmp : getHeldItems()){
if (ctmp.getName().equals(c.getName() ) ) {
throw new IllegalArgumentException("Compartment with an identical name already exits");
}
}
return getHeldItems().add(c);
}
public Compartment getCompartment(int n){
return getHeldItems().get(n);
}
public Compartment getCompartment(String name){
for(Compartment ctmp : getHeldItems()){
if (ctmp.getName().equals(name) ) {
return ctmp;
}
}
return null;
}
}
public class Compartment extends BaseHolder<IWeighable>{
private String name = "";
private double MAX_LOAD = 0.0;
public Compartment (String name ,final double max_load){
this.setName(name);
updateMaxLoad(max_load);
}
// code
protected double getTotalLoad(){
// code
}
/**
*
* #param load
* #throws InvalidParameterException if max load not >= than 0.0
*/
public void setMaxLoad(final double load){
if (load >= 0.0){
this.MAX_LOAD = load;
} else {
throw new InvalidParameterException("max load must be greater than 0.0");
}
}
public boolean isOverloaded(){
return (getTotalLoad() > MAX_LOAD ) ;
}
}
The problem I am having is that this design seems to have many flaws. Apart from it being rather tedious: getElement(n).getElement(n).getElement(n)
Adding elements to a compartment results in all aircrafts using the same compartment, having all the same equipment’s/components installed. As it is the same object in the DB. An instance of the compartment would be need. Cloning the DB Compartment before adding it to an aircraft is no option. I need to be able to change the allowable loads, a change it for all. To resolve this I thought of using some type of “wrapper” class as in:
public class MonumentManager {
public ArrayList <Monument> monuments = new ArrayList<>();
public ArrayList <LinkObect> links;
class LinkObect{
private Compartment c;
private IWeighable e;
LinkObect(Compartment c, IWeighable e){
this.c = c;
this.e = e;
}
}
public boolean addMonument(Monument m){
return monuments.add(m);
}
public void addElementToCompartment(IWeighable e, Compartment c){
boolean known = false; //to check if the passed compartment is known/handeld to/by the MonumentManager
for (Monument m : monuments){
if ( m.getCompartment(c.getName() ) != null ) known = true;
}
if (known){
links.add(new LinkObect(c, e));
} else {
throw new IllegalArgumentException("Compartment is not inside a managed Monument!");
}
}
public List<Compartment> whereUsed(IWeighable e){
// TODO
}
}
This class might solve the problem but it is feels odd. Can anybody point me in the right direction towards a common design pattern etc. I am reading a book from the local library on design patterns. But it seems to be slightly above me. (as is maybe my task).
Any suggestions / help etc would be highly appreciated.
I hope I'm understanding this correctly.
One thing is the Component you want to install that has certain characteristics and another thing is some representation of what you have installed.
The information of your installation does not need to be in your Component but in something else, let's call it Installation.
Your Installation has to know 2 things:
What kind of Component it is.
What other Installations it has inside.
The installation will look something like this.
public class Installation {
private Component type;
private List<Installation> content;
public Installation(Component type){
this.type = type;
this.content = new ArrayList<Component>();
}
//you can have methods for add, remove, etc...
}
Feel free to ask further clarifications.
I'm trying to create Button objects in a dynamic way. I'm not really sure if this is possible. The following code has been used before (and failed):
public class GraphManager{
private Vector<Button> machineButtons = null;
public Vector<Button> getMachineButtons(){
return machineButtons;
}
public void setMachineButtons(int machines, Context context){
for(int i = 0; i < machines; i++){
Button machineButton = new Button(context);
machineButtons.add(machineButton);
}
}
public Button getMachineButton(int index){
return machineButtons.elementAt(index);
}
}
Are there any solutions for my problem?
So I want to be able to only select leafs in JTree. There are some solutions online, but they don't work on multiple selection...
What I would like is to find the part of the code that fires when user clicks on a node and modify that part to suit my needs.
I have found a listener within DefaultTreeCellEditor, but that code seem to apply to when only one node is selected at a time...
The bottom line is, where can I find the code that, when nodes gets clicked, decides if it will select it or not, and will it or not deselect all the other selected nodes?
Fixed it!
public class LeafOnlyTreeSelectionModel extends DefaultTreeSelectionModel
{
private static final long serialVersionUID = 1L;
private TreePath[] augmentPaths(TreePath[] pPaths)
{
ArrayList<TreePath> paths = new ArrayList<TreePath>();
for (int i = 0; i < pPaths.length; i++)
{
if (((DefaultMutableTreeNode) pPaths[i].getLastPathComponent()).isLeaf())
{
paths.add(pPaths[i]);
}
}
return paths.toArray(pPaths);
}
#Override
public void setSelectionPaths(TreePath[] pPaths)
{
super.setSelectionPaths(augmentPaths(pPaths));
}
#Override
public void addSelectionPaths(TreePath[] pPaths)
{
super.addSelectionPaths(augmentPaths(pPaths));
}
}
I'm a newbie in java and I have a small problem. I want to access a variable in one class from another. I have three classes and I want to be able to access a variable in the main class to enable me read the array.
The error I am getting is
java.lang.SecurityException: MIDlet not constructed by createMIDlet
Please see the example below. Please bear in mind they're all in the same package.
package tungPackage;
import com.sun.lwuit.*;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import javax.microedition.midlet.MIDlet;
public class TungMidlet extends MIDlet implements ActionListener {
private Command back = new Command("Back");
private Command ok = new Command("Ok");
public ActionListener commandlistListener = new ActionListener() {
public void actionPerformed(ActionEvent cmd) {
// check which command cliked
if (cmd.getCommand() == back) {
// go back to previous form
mainForm.show();
} else if (cmd.getCommand() == ok) {
// go forward
}
}
};
private List list;
private Form mainForm;
private Label promptLabel;
private housesClass houseClassObject = new housesClass();
public int counter; //this is the variable I want to access in a class called calculate class object.
private int sumAmmt;
public TungMidlet tungMidletObject;
public calculateClass calculateClassObject;
public TungMidlet() {
Display.init(this);
}
private ActionListener applistListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(list.getSelectedIndex()==0){
counter++;
if (counter>5)
{
//check sum price.
sumAmmt = calculateClassObject.calculateSum();
Dialog x = new Dialog("info");
Label label = new Label("Maximum reached.");
Label label2 = new Label("Sum ammt = "+sumAmmt);
x.addComponent(label);
x.addComponent(label2);
x.addCommand(ok);
x.show();
}
else
{
//calculate the price
String info = houseClassObject.randomHouse();
Dialog x = new Dialog("info");
Label label = new Label(info);
x.addComponent(label);
x.addCommand(ok);
x.show();
}
}
}
};
public void startApp() {
//calculateClassObject = new calculateClass();
//sumAmmt = calculateClassObject.calculate(sumAmmt);
mainForm = new Form("Investment Categories");
promptLabel = new Label("choose category");
list = new List();
list.addItem("House");
list.addItem("Cars");
list.addItem("Schools");
list.addItem("Schools");
list.addItem("Supermarkets");
list.addItem("Stocks");
list.addItem("Land");
list.addActionListener(applistListener);
mainForm.addComponent(promptLabel);
mainForm.addComponent(list);
mainForm.addCommand(back);
mainForm.addCommandListener(commandlistListener);
mainForm.setTransitionInAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 1000));
mainForm.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
The class I want to access the "counter" variable using is shown below.
package tungPackage;
import java.util.Random;
public class housesClass {
public Random generator = new Random();
public String[] houseArray = new String[5];
public housesClass housesClassObject;
public calculateClass calcobj;// = new calculateClass();
public housesClass()
{
}
public String randomHouse() {
housesClassObject = new housesClass();
houseArray[0] = "Bungalow - 20,000,000 Shillings";
houseArray[1] = "Microhouse - 10,000,000 Shillings";
houseArray[2] = "Flat - 200,000,000 shillings";
houseArray[3] = "Garage apartment - 7,000,000 shillings";
houseArray[4] = "Studio apartment - 13,000,000 shillings";
int rnd = generator.nextInt(houseArray.length);
housesClassObject.housePrices(rnd);///noma
String house = houseArray[rnd];
return house;
}
void housePrices(int houseNumber) {
calcobj = new calculateClass();
TungMidlet tungmidobj = new TungMidlet();
int counter = tungmidobj.counter;
int[] housePriceArray = new int[5];
housePriceArray[0] = 20000000;
housePriceArray[1] = 10000000;
housePriceArray[2] = 200000000;
housePriceArray[3] = 7000000;
housePriceArray[4] = 13000000;
int price = housePriceArray[houseNumber];
calcobj.storePrice(counter,price);
}
}
The other supporting class is shown below.
package tungPackage;
public class calculateClass {
int[] storeArray = new int[5];
public calculateClass()
{
}
public void storePrice(int counter, int number2)
{
storeArray[counter] = number2;
}
public int calculateSum()
{
int sum =0;
for(int i=1; i<6; i++){
sum= sum+storeArray[i];
}
return sum;
}
}
Are you getting an error? It looks like your access code should work.
I can't seem to find anywhere that you actually initialise counter though, so maybe your problem is that you need to put counter = 0; somewhere in your code.
Java is also object oriented so you should avoid accessing like the above and make some 'getter and setter' methods:
public int getCounter() {
return counter;
}
and then call int counter = tungmidobj.getCounter();
remove TungMidlet constructor. If there was something useful to do there, you could also declare it protected - but this is not the case with your code snippet, see below.
Wherever you try to invoke that constructor directly, remove code that does this and find another way to do what you need. If needed, study code examples provided in LWUIT Tutorial - Introduction for how typical things are done in LWUIT.
put statement Display.init() in the beginning of the startApp method,
just like it is done in LWUIT Tutorial - Hello, LWUIT! example code
The reason why you are getting SecurityException is because you invoke TungMidlet constructor directly. Don't do that.
MIDP API documentation for MIDlet constructor states:
Throws:
SecurityException - unless the application management software is creating the MIDlet.
one way is
TungMidlet tungMidlet=new TungMidlet();
System.out.println(tungMidlet.counter);
but know encapsulation
second way is
you can make counter private variable and provide setter and getters.
private int counter;
public void setCounter(int counter){
this.counter=counter;
}
public int getCounter(){
return counter;
}
second way is preferred way as it achieves encapsulation