I'm testing the OrientDB and unfamiliar with the OrientDB-Graph API. And now I copied the code on the net, it rises the Exception.
Next is my code:
import com.tinkerpop.blueprints.impls.orient.*;
import com.tinkerpop.blueprints.Element.*;
import java.util.*;
class OrientInsert {
public static void testInsertion(OrientGraphNoTx graph) {
System.out.println(new Date());
int count = 1000;
for (int i = 0; i < count; ++i) {
OrientVertex vertex1 = graph.addVertex("class:CLASS1", "prop1", Integer.toString(i), "prop2", "22", "prop3", "3333");
for (int j = 0; j < count; ++j) {
OrientVertex vertex2 = graph.addVertex("class:CLASS2", "prop1", Integer.toString(i + j / 1000), "prop2", "22", "prop3", "3333");
graph.addEdge(null, vertex1, vertex2, "v1v2");
}
}
graph.commit();
System.out.println(new Date());
}
public static void main(String[] args) {
OrientGraphFactory factory = new OrientGraphFactory("remote:10.240.137.12/test", "admin", "admin");
OrientGraphNoTx graph = factory.getNoTx();
OrientInsert.testInsertion(graph);
}
} `
And the output is:
Mar 29, 2016 11:45:19 AM com.orientechnologies.common.log.OLogManager log
INFO: OrientDB auto-config DISKCACHE=3,725MB (heap=14,288MB os=64,292MB disk=7,451MB)
Tue Mar 29 11:45:19 CST 2016
Exception in thread "main" com.orientechnologies.orient.server.distributed.ODistributedException: Error on execution distributed COMMAND
at com.orientechnologies.orient.server.distributed.ODistributedStorage.command(ODistributedStorage.java:346)
at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:67)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.command(ONetworkProtocolBinary.java:1323)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:400)
at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:223)
at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:77)
Caused by: com.orientechnologies.orient.core.exception.OSchemaException: Class CLASS1 already exists in current database
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.doCreateClass(OSchemaShared.java:983)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:415)
at com.orientechnologies.orient.core.metadata.schema.OSchemaProxy.createClass(OSchemaProxy.java:127)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLCreateClass.execute(OCommandExecutorSQLCreateClass.java:179)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.execute(OCommandExecutorSQLDelegate.java:90)
at com.orientechnologies.orient.server.distributed.task.OSQLCommandTask.execute(OSQLCommandTask.java:116)
at com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin.executeOnLocalNode(OHazelcastPlugin.java:810)
at com.orientechnologies.orient.server.hazelcast.ODistributedWorker.onMessage(ODistributedWorker.java:279)
at com.orientechnologies.orient.server.hazelcast.ODistributedWorker.run(ODistributedWorker.java:103)
Apparently, it first inserts the vertex1 and vertex2 into the graphDatabase, and creates class1 and class2. But when it comes to the second insertion, it still wants to create the class1 and class2. Why? how can i control the creation of class. But, so many users use this api for testing.
Try this code:
public static void main(String[] args) {
OrientGraphFactory factory = new OrientGraphFactory("remote:localhost/test", "admin", "admin");
OrientGraphNoTx graph = factory.getNoTx();
OrientInsert.testInsertion(graph);
graph.shutdown();
System.out.println("");
System.out.println("End main");
}
public static class OrientInsert {
public static void testInsertion(OrientGraphNoTx graph) {
System.out.println(new Date());
int count = 1000;
//create class 1
OClass clVertice1;
OrientVertex vVertice1;
clVertice1 = graph.createVertexType("CLASS1", "V");
clVertice1.createProperty("prop1", OType.STRING);
clVertice1.createProperty("prop2", OType.STRING);
clVertice1.createProperty("prop3", OType.STRING);
//create class 2
OClass clVertice2;
OrientVertex vVertice2;
clVertice2 = graph.createVertexType("CLASS2", "V");
clVertice2.createProperty("prop1", OType.STRING);
clVertice2.createProperty("prop2", OType.STRING);
clVertice2.createProperty("prop3", OType.STRING);
for (int i = 0; i < count; ++i) {
System.out.println("");
System.out.println("i :"+i+" -------------------" );
//....class 1
vVertice1 = graph.addVertex("class:CLASS1");
vVertice1.setProperties("prop1", Integer.toString(i));
vVertice1.setProperties("prop2", "22");
vVertice1.setProperties("prop3", "3333");
for (int j = 0; j < count; ++j) {
System.out.print("");
System.out.print(j+" ");
//...class 2
vVertice2 = graph.addVertex("class:CLASS2");
vVertice2.setProperties("prop1", Integer.toString(i + j / 1000));
vVertice2.setProperties("prop2", "22");
vVertice2.setProperties("prop3", "3333");
//edge
graph.addEdge(null, vVertice1, vVertice2, "v1v2");
}
}
}
}
The result is this (i selected only 2 vertex with limit 100 E)
Related
I am having an issue with my merge sort, when I print out my sortedArray it only returns [ 0.0, 0.0.....] Im not sure if there is an error in my sort code or in my print line or if it has to do with doubles. The code I am us posted below.
By calling System.out.println(toString(sortedArray) I get an even more obscure answer.
Thanks for any help.
package mergesort;
import java.util.Arrays;
import java.util.Random;
public class mergesort {
public static void main(String[] args) {
double[] array = getIntArray();
long before = System.nanoTime();
double[] sortedArray= mergeSort(array);
System.out.println("Sorting took "+ (System.nanoTime() - before) +" nanoseconds ");
System.out.println(toString(array) + "\n\n" + toString(sortedArray) + "\n main method completed in: " + (System.nanoTime() - before) + " nanoseconds.");
}
private static String toString(double[] array) {
StringBuilder sb = new StringBuilder("[ ");
double len = array.length;
for(int i = 0; i < len - 1; i++) {
sb.append(array[i] + ", ");
}
sb.append(array[(int) (len - 1)] + " ]");
return sb.toString();
}
public static double[] mergeSort(double[] array) {
if (array.length <= 1) {
return array;
}
int half = array.length / 2;
return merge(mergeSort(Arrays.copyOfRange(array, 0, half)),
mergeSort(Arrays.copyOfRange(array, half, array.length)));
}
private static double[] merge(double[] ds, double[] ds2) {
int len1 = ds.length, len2 = ds2.length;
int totalLength = len1 + len2;
double[] result = new double[totalLength];
int counterForLeft =0,counterForRight=0,resultIndex=0;
while(counterForLeft<len1 || counterForRight < len2){
if(counterForLeft<len1 && counterForRight < len2){
if(ds[counterForLeft]<= ds2[counterForRight]){
result[resultIndex++] =(int) ds[counterForLeft++];
} else {
result[resultIndex++] =(int) ds2[counterForRight++];
}
}else if(counterForLeft<len1){
result[resultIndex++] = (int) ds[counterForLeft++];
}else if (counterForRight <len2){
result[resultIndex++] =(int) ds2[counterForRight++];
}
}
return result;
}
private static double[] getIntArray() {
double[] array = new double[10000];
Random random = new Random();
for(int i = 0; i < 10000; i++) {
array[i] = (random.nextDouble() * .99999);
}
return array;
}
}
In the merge method, when copying from one of the input arrays to the results, you cast to int. For example:
result[resultIndex++] =(int) ds[counterForLeft++];
All your doubles are in the range [0...1), so the result of casting any of them to int is zero. Just get rid of those casts, and you will keep your numbers in the merge result.
As an additional tip, it is much easier to debug small problems than large ones. It failed for any size greater than 2, so you should have been debugging with size 2, not 10000.
Is there a way using the Java API to access an edge index in OrientDB to determine whether a edge with a given label exists in between two known vertices?
Afaik tinkergraph is not exposing any methods for this?
I believe that Neo4j is providing an API like this:
graphDatabaseService.index().forRelationships("HAS_USER").get(key, valueOrNull, startNodeOrNull, endNodeOrNull)
You can call getEdges() from your vertex. Example:
v1.getEdges(v2, Direction.BOTH, "HAS_USER");
This is the JavaDoc:
/**
* (Blueprints Extension) Returns all the edges from the current Vertex to another one.
*
* #param iDestination
* The target vertex
* #param iDirection
* The direction between OUT, IN or BOTH
* #param iLabels
* Optional labels as Strings to consider
* #return
*/
public Iterable<Edge> getEdges(final OrientVertex iDestination, final Direction iDirection, final String... iLabels)
Another way is to use OrientGraph.getEdges()
It is important to create an index first via:
cmd.setText("create index edge.HAS_ITEM on E (out,in) unique");
g.command(cmd).execute();
or via pure Java:
OrientEdgeType e = g.getEdgeType("E");
e.createProperty("in", OType.LINK);
e.createProperty("out", OType.LINK);
e.createIndex("edge.has_item", OClass.INDEX_TYPE.UNIQUE_HASH_INDEX, "out", "in");
After this the index can be queried using:
Iterable<Edge> edges = g.getEdges("edge.has_item", new OCompositeKey(root.getId(), randomDocument.getId()));
Small pittfall: It is important to lowercase the index type when referencing it in the getEdges method. Otherwise orientdb will not be able to retrieve it.
A complete example which shows four ways of finding a specific edge in between two vertices is listed below.
In the example 14k vertices (items) are created which are connected to a single root node.
Creating {14000} items.
[graph.getEdges] Duration: 38
[graph.getEdges] Duration per lookup: 0.0095
[root.getEdges] Duration: 59439
[root.getEdges] Duration per lookup: 14.85975
[root.getEdges - iterating] Duration: 56710
[root.getEdges - iterating] Duration per lookup: 14.1775
[query] Duration: 817
[query] Duration per lookup: 0.20425
Example:
package de.jotschi.orientdb;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.orientechnologies.orient.core.index.OCompositeKey;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
public class EdgeIndexPerformanceTest {
private static OrientGraphFactory factory = new OrientGraphFactory("memory:tinkerpop");
private final static int nDocuments = 14000;
private final static int nChecks = 4000;
private static List<OrientVertex> items;
private static OrientVertex root;
#BeforeClass
public static void setupDatabase() {
setupTypesAndIndices(factory);
root = createRoot(factory);
items = createData(root, factory, nDocuments);
}
private static void setupTypesAndIndices(OrientGraphFactory factory2) {
OrientGraphNoTx g = factory.getNoTx();
try {
OCommandSQL cmd = new OCommandSQL();
cmd.setText("alter database custom useLightweightEdges=false");
g.command(cmd).execute();
cmd.setText("alter database custom useVertexFieldsForEdgeLabels=false");
g.command(cmd).execute();
OrientEdgeType e = g.getEdgeType("E");
e.createProperty("in", OType.LINK);
e.createProperty("out", OType.LINK);
OrientVertexType v = g.createVertexType("root", "V");
v.createProperty("name", OType.STRING);
v = g.createVertexType("item", "V");
v.createProperty("name", OType.STRING);
cmd.setText("create index edge.HAS_ITEM on E (out,in) unique");
g.command(cmd).execute();
} finally {
g.shutdown();
}
}
private static List<OrientVertex> createData(OrientVertex root, OrientGraphFactory factory, int count) {
OrientGraphNoTx g = factory.getNoTx();
try {
System.out.println("Creating {" + count + "} items.");
List<OrientVertex> items = new ArrayList<>();
for (int i = 0; i < count; i++) {
OrientVertex item = g.addVertex("class:item");
item.setProperty("name", "item_" + i);
items.add(item);
root.addEdge("HAS_ITEM", item, "class:E");
}
return items;
} finally {
g.shutdown();
}
}
private static OrientVertex createRoot(OrientGraphFactory factory) {
OrientGraphNoTx g = factory.getNoTx();
try {
OrientVertex root = g.addVertex("class:root");
root.setProperty("name", "root vertex");
return root;
} finally {
g.shutdown();
}
}
#Test
public void testEdgeIndexViaRootGetEdgesWithoutTarget() throws Exception {
OrientGraphNoTx g = factory.getNoTx();
try {
long start = System.currentTimeMillis();
for (int i = 0; i < nChecks; i++) {
OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
Iterable<Edge> edges = root.getEdges(Direction.OUT, "HAS_ITEM");
boolean found = false;
for (Edge edge : edges) {
if (edge.getVertex(Direction.IN).equals(randomDocument)) {
found = true;
break;
}
}
assertTrue(found);
}
long dur = System.currentTimeMillis() - start;
System.out.println("[root.getEdges - iterating] Duration: " + dur);
System.out.println("[root.getEdges - iterating] Duration per lookup: " + ((double) dur / (double) nChecks));
} finally {
g.shutdown();
}
}
#Test
public void testEdgeIndexViaRootGetEdges() throws Exception {
OrientGraphNoTx g = factory.getNoTx();
try {
long start = System.currentTimeMillis();
for (int i = 0; i < nChecks; i++) {
OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
Iterable<Edge> edges = root.getEdges(randomDocument, Direction.OUT, "HAS_ITEM");
assertTrue(edges.iterator().hasNext());
}
long dur = System.currentTimeMillis() - start;
System.out.println("[root.getEdges] Duration: " + dur);
System.out.println("[root.getEdges] Duration per lookup: " + ((double) dur / (double) nChecks));
} finally {
g.shutdown();
}
}
#Test
public void testEdgeIndexViaGraphGetEdges() throws Exception {
OrientGraphNoTx g = factory.getNoTx();
try {
long start = System.currentTimeMillis();
for (int i = 0; i < nChecks; i++) {
OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
Iterable<Edge> edges = g.getEdges("edge.has_item", new OCompositeKey(root.getId(), randomDocument.getId()));
assertTrue(edges.iterator().hasNext());
}
long dur = System.currentTimeMillis() - start;
System.out.println("[graph.getEdges] Duration: " + dur);
System.out.println("[graph.getEdges] Duration per lookup: " + ((double) dur / (double) nChecks));
} finally {
g.shutdown();
}
}
#Test
public void testEdgeIndexViaQuery() throws Exception {
OrientGraphNoTx g = factory.getNoTx();
try {
System.out.println("Checking edge");
long start = System.currentTimeMillis();
for (int i = 0; i < nChecks; i++) {
OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
OCommandSQL cmd = new OCommandSQL("select from index:edge.has_item where key=?");
OCompositeKey key = new OCompositeKey(root.getId(), randomDocument.getId());
assertTrue(((Iterable<Vertex>) g.command(cmd).execute(key)).iterator().hasNext());
}
long dur = System.currentTimeMillis() - start;
System.out.println("[query] Duration: " + dur);
System.out.println("[query] Duration per lookup: " + ((double) dur / (double) nChecks));
} finally {
g.shutdown();
}
}
}
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);
QueUserWorkItem is supposed to accept a delegate but i found exercise that passes instance method name instead of delegate like this:
public class Fibonacci
{
private int _n;
private int _fibOfN;
private ManualResetEvent _doneEvent;
public int N { get { return _n; } }
public int FibOfN { get { return _fibOfN; } }
// Constructor.
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n = n;
_doneEvent = doneEvent;
}
// Wrapper method for use with thread pool.
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("thread {0} started...with id={1}", threadIndex,Thread.CurrentThread.ManagedThreadId);
_fibOfN = Calculate(_n);
Console.WriteLine("thread {0} result calculated...", threadIndex);
_doneEvent.Set();
}
// Recursive method that calculates the Nth Fibonacci number.
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}
return Calculate(n - 1) + Calculate(n - 2);
}
}
public class Program
{
static void Main()
{
const int FibonacciCalculations = 10;
// One event is used for each Fibonacci object.
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();
// Configure and start threads using ThreadPool.
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i] = new ManualResetEvent(false);
Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
fibArray[i] = f;
ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback , i);
}
for (int x = 0; x < 10;x++ )
{
Console.WriteLine("x");
}
// Wait for all threads in pool to calculate.
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("All calculations are complete.");
// Display the results.
for (int i = 0; i < FibonacciCalculations; i++)
{
Fibonacci f = fibArray[i];
Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
}
}
why does this work? I do not see implicit or explicit delegate being passed
Ok. so I'm writing a grocery checkout system code and on the right side of the frame, I'm displaying a Jpanel with Labels. Every time I click the 'Scan' button, I add a new label into the JPanel so that everytime I click, it displays the output. However, I can only fit so many entries in my window, how do I incorporate a scroll bar so that I can scroll through the groceries?
I tried inputting a scroll bar EAST with a BorderLayout and all the labels CENTER, however, everytime I click the button, it only reprints it at the same exact spot instead of top/down so that I can scroll. (Please, bare in mind that this is a very very rough draft. I'll be incorporating the logic beneath the code once I get the nitty-gritty with the GUI)
Here's my code:
public class Checkout extends JFrame implements ActionListener
{
private int numOfItems = 21;
private Integer[] itemCode = new Integer[numOfItems];
private StringBuffer[] itemDesc = new StringBuffer[numOfItems];
private Double[] unitPrice = new Double[numOfItems];
private Integer[] taxCode = new Integer[numOfItems];
private Integer[] quantity = new Integer[numOfItems];
private Integer[] reorderLevel = new Integer[numOfItems];
private double subTotal, tax, grandTotal;
private JButton scan = new JButton("Scan");
private JButton pay = new JButton("Finish & Pay");
private JButton readFile = new JButton("Read from File");
private JTextField itemNumber = new JTextField(4);
private JTextField itemQuantity = new JTextField(4);
private JLabel displayReceipt = new JLabel();
private JPanel p4;
public Checkout()
{
setValues();
JPanel p2 = new JPanel(new FlowLayout());
p2.add(scan);
p2.add(pay);
p2.add(readFile);
JPanel p1 = new JPanel(new FlowLayout());
p1.add(new JLabel("Item Number:"));
p1.add(itemNumber);
p1.add(new JLabel("Item Quantity:"));
p1.add(itemQuantity);
p1.setBorder(new TitledBorder("Scan Items First. Then Hit 'Finish and Pay'"));
JPanel p3 = new JPanel(new BorderLayout(5, 5));
p3.add(p1, BorderLayout.NORTH);
p3.add(p2, BorderLayout.CENTER);
p4 = new JPanel(new GridLayout(0, 1, 0, 0));
JScrollPane scroll = new JScrollPane(p4);
add(p3, BorderLayout.WEST);
add(p4, BorderLayout.CENTER);
scan.addActionListener(this);
pay.addActionListener(this);
readFile.addActionListener(this);
}
public void setValues()
{
String[] tokens = new String[6];
String[][] multi = new String[numOfItems][6];
try{BufferedReader textReader = new BufferedReader(new FileReader("inventory.txt"));
for(int i = 0; i < numOfItems; i++) // Split the file
{
tokens = textReader.readLine().split("\t");
for(int j = 0; j < tokens.length; j++)
{
multi[i][j] = tokens[j];
}
}
for(int i = 0; i < numOfItems; i++)
{
itemCode[i] = (Integer.parseInt(multi[i][0]));
itemDesc[i] = new StringBuffer(multi[i][1]);
unitPrice[i] = (Double.parseDouble(multi[i][2]));
taxCode[i] = (Integer.parseInt(multi[i][3]));
quantity[i] = (Integer.parseInt(multi[i][4]));
reorderLevel[i] = (Integer.parseInt(multi[i][5]));
}}
catch(Exception e){}
}
public void setQuantity(int item, int itemCount)
{
for(int i = 0; i < numOfItems; i++)
{
if(itemCode[i].equals(item))
{
quantity[i] = quantity[i] - itemCount;
subTotal = itemCount * unitPrice[i];
if(quantity[i] < reorderLevel[i])
itemDesc[i] = itemDesc[i].append("**MARKED FOR REORDER**\t");
}
}
}
public String toString()
{
System.out.println("CUST TICKET");
//for(int i = 0; i < numOfItems; i++)
//return (itemCode[i] + "\t" + itemDesc[i] + "\t" + unitPrice[i] + "\t" + taxCode[i] + "\t" + quantity[i] + "\t" + reorderLevel[i]);
System.out.println("SUBTOTAL\t" + subTotal);
System.out.println("TAX\t\t" + tax);
System.out.println("GRAND TOTAL\t" + grandTotal);
return "";
}
public static void main(String[] args) throws Exception
{
Checkout frame = new Checkout(); // Frame layout
frame.setSize(600, 135);
frame.setTitle("Computer Science 202: Final Project - Supermarket Checkout System");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
/*Scanner input = new Scanner(System.in);
System.out.print("Please enter item number: ");
Integer itemNumber = Integer.parseInt(input.nextLine());
System.out.print("Please enter quantity: ");
Integer quantity = Integer.parseInt(input.nextLine());
System.out.println(frame.stockCheck(itemNumber, quantity));*/
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == scan)
{
try
{
Integer quantityOrdered = 1;
Integer item = Integer.parseInt(itemNumber.getText());
quantityOrdered = Integer.parseInt(itemQuantity.getText());
for(int i = 0; i < numOfItems; i++)
{
if(itemCode[i].equals(item))
{
if(quantityOrdered > 1)
{
p4.add(new JLabel(itemDesc[i] + "" + unitPrice[i]));
p4.add(new JLabel(quantityOrdered + " # " + unitPrice[i]));
p4.revalidate();
p4.repaint();
}
else
{
p4.add(new JLabel(itemDesc[i] + "\t" + unitPrice[i]));
p4.revalidate();
p4.repaint();
}
}
}
setQuantity(item, quantityOrdered);
}
catch(Exception ex){}
}
else if(e.getSource() == pay)
{
displayReceipt.setText(toString());
}
else if(e.getSource() == readFile)
{
System.out.println("READ FILE");
}
}
}