Posted By

s1w on 06/13/11


Tagged

algorithm tsp problem minimum travelling salesman spanning kruskal prim


Versions (?)

Travelling Salesman Problem >> Java


 / Published in: Java
 

URL: http://siwego.net/dev/tsp_java.zip

[start_tsp.bat] file should be made for launching: start "output" java -jar TSP.jar

  1. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*;
  2. @SuppressWarnings("serial")
  3. /*
  4.  * @author: Michal Sztolcman s3826
  5.  * subject: TSP z alg. Kruskala i Prima
  6. */
  7.  
  8. class TSPgraphics extends JPanel implements ComponentListener {
  9. public static int ROUTE_POINTS = 20;
  10. Dimension size; double factorX, factorY;
  11. Node[] Nodes; // zbior wylosowanych pojedynczych punktow (wezlow)
  12. ArrayList<String> output; boolean printed, connections; Set routes;
  13. char tmp_ch; TSP.alg last_alg; boolean last_tsp, rolled;
  14.  
  15. class Node extends Point {
  16. char point; int tsp_degree;
  17. public Node(char c, int x, int y) {
  18. super(x, y);
  19. point = c; tsp_degree = 0;
  20. }
  21. public Node(int i, int x, int y) {
  22. this((char)('A'+i), x, y);
  23. }
  24. public double getDistance(Node n) {
  25. return Math.sqrt(Math.pow(x-n.x,2)+Math.pow(y-n.y,2));
  26. }
  27. public String toString() {
  28. return ""+point;
  29. }
  30. }
  31.  
  32. public TSPgraphics() {
  33. addComponentListener(this);
  34. }
  35.  
  36. public void roll() {
  37. size = new Dimension(getWidth(), getHeight());
  38. factorX = factorY = 1;
  39. connections = false; printed = false;
  40. rollNodes();
  41. repaint();
  42. }
  43.  
  44. public void connect(final TSP.alg alg, final char startNode) {
  45. if (alg != last_alg || last_tsp != TSP.TSPselected() || (alg == TSP.alg.PRIM && tmp_ch != startNode))
  46. printed = false;
  47. last_alg = alg; last_tsp = TSP.TSPselected();
  48. if (!printed) System.out.print("\n\nconnecting.");
  49. else return;
  50.  
  51. final Thread connecting = new Thread() {
  52. public void run() {
  53. NodePair p; Character A, B; dumped = false;
  54. output = new ArrayList<String>();
  55. output.add("\n\n"+(TSP.TSPselected() ? "tsp " : "")+(""+alg).toLowerCase()+" - step log:");
  56.  
  57. if (alg == TSP.alg.KRUSKAL) { // <-- KRUSKAL
  58. // rodzina jednoelementowych zbiorow z kazdym z wezlow
  59. LinkedList divList = new LinkedList(); Set hs1;
  60.  
  61. // utworzenie uporzadkowanego zbioru segmentow NodePair rosnaco wg. dystansu
  62. routes = new TreeSet( new Comparator<NodePair>() {
  63. public int compare(NodePair p1, NodePair p2) {
  64. //w przypadku wyniku 0 TreeSet nie dopuscil by roznych polaczen o tej samej odleglosci
  65. return p1.distance - p2.distance < 0 ? -1 : 1;
  66. }
  67. });
  68. // dodanie wszystkich par punktow NodePair wraz z odlegloscia do zbioru
  69. for (int i = 0; i < Nodes.length; i++) {
  70. for (int j = 0; j < i && i > 0; j++) {
  71. routes.add( new NodePair(Nodes[j]+""+Nodes[i], Nodes[j].getDistance(Nodes[i])) );
  72. }
  73. // utworzenie zbioru z jednym elementem (wezlem)
  74. hs1 = new HashSet(); hs1.add((char) ('A'+i));
  75. divList.add(hs1); // dodanie do rodziny zbiorow
  76. }
  77.  
  78. // operacja laczenia zbiorow w rodzinie zbiorow i oznaczanie polaczen
  79. Iterator divIt, routeIt = routes.iterator();
  80. Set pointSet, leftSet;
  81. while(routeIt.hasNext() && divList.size() != 1) {
  82. divIt = divList.iterator();
  83. p = (NodePair) routeIt.next();
  84. A = p.segment.charAt(0);
  85. B = p.segment.charAt(1);
  86. leftSet = null;
  87. pointSet = null;
  88. String tmp = "route("+A+","+B+") --> ";
  89. while (divIt.hasNext()) {
  90. pointSet = (HashSet) divIt.next();
  91.  
  92. if (TSP.TSPselected() && (Nodes[idx(A)].tsp_degree >= 2 || Nodes[idx(B)].tsp_degree >= 2)) continue;
  93. if (pointSet.contains(A) && pointSet.contains(B)) continue;
  94. else if (pointSet.contains(A) || pointSet.contains(B))
  95. if (leftSet == null) leftSet = pointSet;
  96. else {
  97. leftSet.addAll(pointSet);
  98. divIt.remove();
  99. p.connection = true;
  100. if (TSP.TSPselected()) {
  101. Nodes[idx(A)].tsp_degree++;
  102. Nodes[idx(B)].tsp_degree++;
  103. }
  104. break;
  105. }
  106. }
  107. divIt = divList.iterator();
  108. while (divIt.hasNext())
  109. tmp += divIt.next();
  110. output.add(tmp);
  111. }
  112. if (TSP.TSPselected()) {
  113. String segment = "";
  114. for (int i = 0; i < Nodes.length; i++) {
  115. if (Nodes[i].tsp_degree == 1) segment += Nodes[i];
  116. Nodes[i].tsp_degree = 0;
  117. }
  118. routeIt = routes.iterator();
  119. while(routeIt.hasNext()) {
  120. p = (NodePair) routeIt.next();
  121. if (p.segment.equals(segment)) {
  122. p.connection = true;
  123. output.add("finally "+segment.charAt(0)+" -> "+segment.charAt(1));
  124. break;
  125. }
  126. }
  127. }
  128. }
  129. else if (alg == TSP.alg.PRIM) { tmp_ch = startNode; // <-- PRIM
  130. routes = new LinkedHashSet(); // zbior do wydruku wybranych polaczen
  131. PrimTree ptree = new PrimTree(); // uproszczone drzewo polaczen dla alg tsp
  132.  
  133. double[] distances = new double[Nodes.length]; // tablica odleglosci
  134. Node[] parents = new Node[Nodes.length]; // tablica wierzcholkow rodzicow
  135.  
  136. // utworzenie mst prim uzywajac dwoch pomocniczych tablic, przy zalozeniu ze wszystkie punkty sie widza
  137. Node curr = Nodes[idx(startNode)];
  138. distances[idx(startNode)] = -1;
  139.  
  140. String tmp1 = "\nparent nodes array:\n", tmp2 = "\n-";
  141. for (int i = 0; i < Nodes.length; i++) {
  142. tmp1+=" "+Nodes[i]; tmp2+="--"; }
  143. output.add(tmp1+" take: "+curr+tmp2);
  144.  
  145. for (int min = 0; min != -1;) { min = -1;
  146. for (int i = 0; i < Nodes.length; i++) {
  147. if (distances[i] == -1) continue;
  148. if (distances[i] == 0 || curr.getDistance(Nodes[i]) < distances[i]) {
  149. distances[i] = curr.getDistance(Nodes[i]);
  150. parents[i] = curr;
  151. }
  152. if (curr != Nodes[i] && (min == -1 || distances[i] < distances[min]))
  153. min = i;
  154. }
  155. if (min != -1) {
  156. tmp1 = "";
  157. for (int i = 0; i < Nodes.length; i++)
  158. tmp1 += " "+(distances[i] != -1 ? parents[i] : ".");
  159. output.add(tmp1+" next: "+parents[min]+" -> "+Nodes[min]+" ("+((int)distances[min])+"."+(""+distances[min]).charAt((""+distances[min]).indexOf('.')+1)+")");
  160.  
  161. if (TSP.TSPselected()) ptree.add(parents[min], Nodes[min]);
  162. else routes.add( new NodePair(parents[min]+""+Nodes[min], parents[min].getDistance(Nodes[min]), true) );
  163. distances[min] = -1;
  164. curr = Nodes[min];
  165. }
  166. }
  167.  
  168. if (TSP.TSPselected()) {
  169. final ArrayList print = new ArrayList<String>();
  170.  
  171. // wlasna definicja stosu
  172. myStack stack = new myStack() {
  173. private stnode head;
  174. private int count;
  175. class stnode {
  176. Node node; stnode next;
  177. public stnode(Node n) { count++;
  178. node = n;
  179. next = head;
  180. head = this;
  181. }
  182. };
  183. public myStack push(Set<Node> hs) {
  184. if (hs != null)
  185. for (Iterator it = hs.iterator(); it.hasNext();)
  186. new stnode((Node) it.next());
  187. return this;
  188. }
  189. public Node pop() { count--;
  190. Node n = head.node;
  191. head = head.next;
  192. popPrint(n);
  193. return n;
  194. }
  195. public Node top() {
  196. return head.node;
  197. }
  198. public boolean empty() {
  199. return head == null;
  200. }
  201. private void popPrint(Node n) {
  202. int i; stnode pointer = head; Node[] nod = new Node[count];
  203. for (i = count-1; pointer != null; i--) { nod[i] = pointer.node; pointer = pointer.next; }
  204. i = 0;
  205. if (print.isEmpty()) {
  206. print.add(" "+n);
  207. print.add(" =");
  208. for (; i < nod.length-1; i++)
  209. print.add(" "+nod[i]);
  210. print.add(" "+n);
  211. } else {
  212. print.set(i, print.get(i++)+" "+n);
  213. print.set(i, print.get(i++)+" =");
  214. for (; i < nod.length+2; i++) {
  215. if (print.size() > i) print.set(i, print.get(i)+" "+nod[i-2]);
  216. else print.add(fill(((String)print.get(0)).length()-1)+nod[i-2]);
  217. }
  218. if (print.size() > i) print.set(i, print.get(i)+" "+n);
  219. else print.add(fill(((String)print.get(0)).length()-1)+n); i++;
  220. while (i < print.size()) print.set(i, print.get(i++)+" ");
  221. }
  222. }
  223. };
  224.  
  225. // okreslenie trasy tsp na utworzonym wczesniej minimalnym drzewie rozpinajacym prim
  226. Node parent = Nodes[idx(startNode)], next;
  227. stack.push(Collections.singleton(parent));
  228. stack.push(ptree.get(stack.pop()));
  229. while (!stack.empty()) {
  230. next = stack.pop();
  231. stack.push(ptree.get(next));
  232. routes.add( new NodePair(parent+""+next, parent.getDistance(next), true) );
  233. parent = next;
  234. }
  235. routes.add( new NodePair(Nodes[idx(startNode)]+""+parent, Nodes[idx(startNode)].getDistance(parent), true) );
  236. print.add("\n\ntsp prim - stack pop log:\n");
  237. for (int i = print.size()-1; i >= 0; i--) output.add(""+print.set(i, null));
  238. output.add("\nfinally "+Nodes[idx(startNode)]+" -> "+parent);
  239. }
  240. ptree.clear();
  241. }
  242.  
  243. connections = true;
  244. repaint();
  245. }
  246. };
  247.  
  248. // obsluga wyjatkow przepelnienia, ktore nie powinno sie zdarzyc
  249. connecting.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
  250. public void uncaughtException(Thread t, Throwable e) {
  251. if (e instanceof ThreadDeath) { }
  252. else if (e instanceof Error) {
  253. System.out.println(".\n"+e+", connecting interrupted\nhint: use less nodes");
  254. System.exit(1);
  255. } else
  256. System.out.println(".\nwarning: "+e.getClass().getSimpleName()+", connecting interrupted..\nplease try again..");
  257. dumped = true; connections = false;
  258. routes.clear(); output.clear();
  259. return;
  260. }
  261. });
  262. connecting.start();
  263. /*
  264.   (new Thread() {
  265.   public void run() {
  266.   progress = 0;
  267.   while (connecting.isAlive()) {
  268.   try {
  269.   this.sleep(1000);
  270.   } catch(InterruptedException e) {
  271.   return;
  272.   }
  273.   if (connecting.isAlive()) {
  274.   progress++;
  275.   if (progress == 2) {
  276.   System.out.println(".\nwarning: computing connections takes very long, possibility of data overflow");
  277.   }
  278.   else if (progress > 5) {
  279.   System.out.println(".\noperation aborted.\nhint: use less nodes");
  280.   try {
  281.   connecting.stop();
  282.   } catch (SecurityException exc) { }
  283.   return;
  284.   }
  285.   else
  286.   System.out.print(".");
  287.   }
  288.   else if (!connections && !dumped) {
  289.   System.out.println("\nfatal error: most propably OutOfMemoryError occured: Java heap overflow\n");
  290.   System.exit(1);
  291.   }
  292.   }
  293.   }
  294.   }).start();
  295.   try { connecting.join(); } catch (InterruptedException exc) { }
  296.   */
  297. } int progress; boolean dumped;
  298.  
  299. public void paintComponent(Graphics g) {
  300. super.paintComponent(g);
  301. if (rolled) {
  302. int w = getWidth();
  303. int h = getHeight();
  304. g.setColor(new Color(224,224,224));
  305. g.setFont(new Font("Dialog", Font.PLAIN, 9));
  306. g.drawString("Michael Sztolcman s3826", w - 130, h - 5);
  307.  
  308. for (int i = 0; i < Nodes.length; i++) {
  309. g.setColor(Color.orange);
  310. g.fillOval(getX(i), getY(i), 6, 6);
  311. g.setColor(Color.gray);
  312. g.drawOval(getX(i), getY(i), 6, 6);
  313. g.setColor(Color.lightGray);
  314. g.setFont(new Font("Dialog", Font.PLAIN, 11));
  315. g.drawString(""+Nodes[i], getX(i) + 8, getY(i) + 18);
  316. }
  317. if (connections) {
  318. if (!printed) System.out.println((progress == 0 ? ".." : progress == 1 ? "." : "")+"\n\n connect distance");
  319. Iterator routeIt = routes.iterator();
  320. NodePair p; Character A, B;
  321. while(routeIt.hasNext()) {
  322. p = (NodePair) routeIt.next();
  323. if (!printed) System.out.println(p.segment + " = " + p.connection + (p.connection ? " " : "") + " " + p.distance);
  324. if (p.connection) {
  325. A = p.segment.charAt(0);
  326. B = p.segment.charAt(1);
  327. g.drawLine(getX(A) + 3, getY(A) + 3, getX(B) + 3, getY(B) + 3);
  328. }
  329. }
  330. if (!printed)
  331. for (Iterator it = output.iterator(); it.hasNext();)
  332. System.out.println(it.next());
  333. printed = true;
  334. }
  335. }
  336. }
  337. private int getX(char c) { return getX(idx(c)); }
  338. private int getX(int i) { return (int) (Nodes[i].x * factorX); }
  339. private int getY(char c) { return getY(idx(c)); }
  340. private int getY(int i) { return (int) (Nodes[i].y * factorY); }
  341.  
  342. private void rollNodes() {
  343. rolled = false; Nodes = new Node[ROUTE_POINTS];
  344. int x, y, i = 0; boolean ok;
  345.  
  346. while (i < Nodes.length) {
  347. x = rnd(getWidth()-24)+6; y = rnd(getHeight()-28)+5; ok = true;
  348. for (int j = 0; j < i && i > 0; j++)
  349. if (((x <= Nodes[j].x && x > Nodes[j].x - 16) ||
  350. (x > Nodes[j].x && x < Nodes[j].x + 16)) &&
  351. ((y <= Nodes[j].y && y > Nodes[j].y - 16) ||
  352. (y > Nodes[j].y && y < Nodes[j].y + 16))) {
  353. ok = false; break;
  354. }
  355. if (ok) {
  356. Nodes[i] = new Node(i, x, y);
  357. i++;
  358. }
  359. }
  360. rolled = true;
  361. }
  362. private static int rnd(int n) {
  363. Random r = new Random();
  364. return r.nextInt(n);
  365. }
  366. private String fill(int n) {
  367. String s = "";
  368. for (int i = 0; i < n; i++) s += " ";
  369. return s;
  370. }
  371.  
  372. private int idx(char c) { return c-'A'; }
  373.  
  374. // uproszczone drzewo polaczen dla alg tsp prima
  375. class PrimTree extends HashMap<Node, HashSet> {
  376. public void add(Node root, Node child) {
  377. if (containsKey(root)) {
  378. HashSet<Node> hs = remove(root);
  379. hs.add(child); put(root, hs);
  380. }
  381. else
  382. put(root, new HashSet<Node>(Collections.singleton(child)));
  383. }
  384. public HashSet<Node> get(Node node) {
  385. return super.remove(node);
  386. }
  387. };
  388.  
  389. public void componentResized(ComponentEvent e) {
  390. double x = getWidth(), y = getHeight();
  391. if (size != null) {
  392. factorX = x/((double) size.width);
  393. factorY = y/((double) size.height);
  394. }
  395. }
  396. public void componentMoved(ComponentEvent e) { }
  397. public void componentHidden(ComponentEvent e) { }
  398. public void componentShown(ComponentEvent e) { }
  399.  
  400. //abstract class myStack
  401. interface myStack {
  402. boolean empty(); Node top(); Node pop();
  403. myStack push(Set<Node> hs);
  404. }
  405. }
  406.  
  407.  
  408. class NodePair /*implements Comparable*/ {
  409. String segment; double distance;
  410. boolean connection;
  411.  
  412. public NodePair(String s, double d, boolean c) {
  413. segment = s;
  414. distance = d;
  415. connection = c;
  416. }
  417. public NodePair(String s, double d) {
  418. this(s, d, false);
  419. }
  420. /* public int compareTo(Object o) {
  421.   return distance - ((NodePair) o).distance < 0 ? -1 : 1;
  422.   }*/
  423. }
  424.  
  425. class TSP extends JFrame {
  426. final static int SIZ_X = 600, SIZ_Y = 400;
  427. public static enum alg { KRUSKAL, PRIM };
  428. static JCheckBox CB_TSP; static JButton BRoute;
  429. static JTextField JTF; static JLabel JL;
  430. static myRadio RBKruskal, RBPrim;
  431.  
  432. public TSP() {
  433. addWindowListener(new WindowAdapter() {
  434. public void windowClosing(WindowEvent e) {
  435. dispose();
  436. System.exit(0);
  437. }
  438. });
  439. }
  440.  
  441. public static void main(String args[]) {
  442. System.out.println("Starting TSP...");
  443. final TSP f = new TSP();
  444. final TSPgraphics t = new TSPgraphics();
  445. Container p = f.getContentPane();
  446. JToolBar j = new JToolBar();
  447. j.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
  448. public void propertyChange(java.beans.PropertyChangeEvent e) {
  449. //t.setSize(SIZ_X, SIZ_Y);
  450. Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(new ComponentEvent(t, ComponentEvent.COMPONENT_RESIZED));
  451. }
  452. });
  453.  
  454. JButton b = new JButton(" roll ");
  455. b.addActionListener(new ActionListener() {
  456. public void actionPerformed(ActionEvent e) {
  457. t.roll();
  458. }
  459. });
  460. b.setFocusPainted(false);
  461. j.add(b);
  462. j.add(Box.createRigidArea(new Dimension(3,0)));
  463. Box box = Box.createHorizontalBox();
  464. box.setPreferredSize(new Dimension(180, 22));
  465. box.setMaximumSize(new Dimension(180, 22));
  466. box.add(Box.createHorizontalGlue());
  467. // box.setBackground(Color.red);
  468. // box.setOpaque(true);
  469. JLabel jl = new JLabel("start from:");
  470. jl.setFont(new Font("Dialog", Font.ITALIC, 11));
  471. jl.setForeground(Color.gray);
  472. jl.setAlignmentX(Component.RIGHT_ALIGNMENT);
  473. box.add(JL = jl);
  474. box.add(Box.createRigidArea(new Dimension(3,0)));
  475. final JTextField tf = new JTextField("A");
  476. tf.setPreferredSize(new Dimension(27, 22));
  477. tf.setMaximumSize(new Dimension(27, 22));
  478. tf.setHorizontalAlignment(JTextField.CENTER);
  479. tf.setFont(new Font("Dialog", Font.BOLD, 12));
  480. tf.setForeground(Color.gray);
  481. tf.addKeyListener(new KeyListener() {
  482. public void keyPressed (KeyEvent arg) {
  483. JTextField f = (JTextField) arg.getSource();
  484. f.setText("");
  485. }
  486. public void keyReleased (KeyEvent arg) {
  487. JTextField f = (JTextField) arg.getSource();
  488. f.setText(f.getText().length() > 0 ? f.getText().toUpperCase() : "A");
  489. }
  490. public void keyTyped (KeyEvent arg) { }
  491. });
  492. box.add(JTF = tf);
  493. box.add(Box.createRigidArea(new Dimension(2,0)));
  494. b = new JButton(" TSP ROUTE ");
  495. b.setToolTipText(" find 'travelling salesman problem' route ");
  496. b.setMargin(new Insets(1,4,1,4));
  497. b.addActionListener(new ActionListener() {
  498. public void actionPerformed(ActionEvent e) {
  499. char ch = tf.getText().charAt(0);
  500. if (RBPrim.isSelected() && (ch < 'A' || ch > 'A' + TSPgraphics.ROUTE_POINTS-1))
  501. JOptionPane.showMessageDialog(null, "Route point '"+ tf.getText() +"' not exists!", "route canceled", JOptionPane.WARNING_MESSAGE);
  502. else
  503. t.connect(RBPrim.isSelected() ? alg.PRIM : alg.KRUSKAL, ch);
  504. }
  505. });
  506. b.setFocusPainted(false);
  507. b.setPreferredSize(new Dimension(93, 22));
  508. box.add(BRoute = b);
  509. j.add(box);
  510. j.add(Box.createGlue());
  511. j.add(Box.createRigidArea(new Dimension(3,0)));
  512. jl = new JLabel("nodes:");
  513. jl.setFont(new Font("Dialog", Font.ITALIC, 11));
  514. jl.setForeground(Color.gray);
  515. j.add(jl);
  516. j.add(Box.createRigidArea(new Dimension(3,0)));
  517. String tf_tmp;
  518. JTextField tf1 = new JTextField(""+TSPgraphics.ROUTE_POINTS);
  519. tf1.setPreferredSize(new Dimension(30, 22));
  520. tf1.setMaximumSize(new Dimension(30, 22));
  521. tf1.setHorizontalAlignment(JTextField.CENTER);
  522. tf1.setFont(new Font("Dialog", Font.BOLD, 12));
  523. tf1.setForeground(Color.gray);
  524. tf1.addFocusListener(new FocusListener() {
  525. JTextField j; String tf_tmp; int n;
  526.  
  527. public void focusGained(FocusEvent e) {
  528. j = (JTextField) e.getSource();
  529. tf_tmp = j.getText();
  530. j.setSelectionStart(0);
  531. j.setSelectionEnd(tf_tmp.length());
  532. };
  533.  
  534. public void focusLost(FocusEvent e) {
  535. j = (JTextField) e.getSource();
  536. if (j.getText().length() == 0) j.setText(tf_tmp);
  537. else
  538. try {
  539. n = Integer.parseInt(j.getText());
  540. if (n < 2) { n = 2; j.setText(""+n); }
  541. else if (n > 50) { n = 50; j.setText(""+n); }
  542. TSPgraphics.ROUTE_POINTS = n;
  543. } catch (NumberFormatException ex) {
  544. j.setText(tf_tmp);
  545. }
  546. }
  547. });
  548. j.add(tf1);
  549. j.add(Box.createRigidArea(new Dimension(4,0)));
  550. j.add(Box.createGlue());
  551. j.add(Box.createGlue());
  552.  
  553. /*JRadioButton rb = new JRadioButton("Kruskal", true) {
  554.   public void paintComponent(Graphics g) {
  555.   super.paintComponent(g);
  556.   if (this.isSelected())
  557.   setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
  558.   else
  559.   setCursor(new Cursor(Cursor.HAND_CURSOR));
  560.   }
  561.   };
  562.   gr.add(rb);*/
  563.  
  564. j.add(RBKruskal = new myRadio(f, "Kruskal", gr));
  565. j.add(RBPrim = new myRadio(f, "Prim", gr));
  566.  
  567. CB_TSP = new JCheckBox("TSP", true);
  568. CB_TSP.setFont(new Font("Dialog", Font.BOLD, 11));
  569. CB_TSP.setFocusPainted(false);
  570. CB_TSP.setOpaque(false);
  571. CB_TSP.setHorizontalTextPosition(JCheckBox.LEADING);
  572. CB_TSP.addItemListener(new ItemListener() {
  573. public void itemStateChanged(ItemEvent e) {
  574. boolean isSet = (e.getStateChange() == ItemEvent.SELECTED);
  575. f.setTitle((isSet ? "TSP " : "")+(RBPrim.isSelected() ? "PRIM" : "KRUSKAL"));
  576. BRoute.setText(isSet ? " TSP ROUTE " : " FIND MST ");
  577. BRoute.setToolTipText(" find "+(isSet ? "'travelling salesman problem' route " : "minimum spanning tree using "+(RBPrim.isSelected() ? "Prim's " : "Kruskal's ")+"algorithm "));
  578. }
  579. });
  580. j.add(CB_TSP);
  581.  
  582. RBKruskal.doClick();
  583.  
  584. p.add(j, BorderLayout.NORTH);
  585. p.add(t, BorderLayout.CENTER);
  586. p.add(new JPanel(), BorderLayout.WEST);
  587. p.add(new JPanel(), BorderLayout.EAST);
  588. f.setSize(SIZ_X, SIZ_Y);
  589. f.setMinimumSize(new Dimension(530, 360));
  590. f.setDefaultCloseOperation(EXIT_ON_CLOSE);
  591. f.setLocationRelativeTo(null);
  592. f.setVisible(true);
  593.  
  594. t.roll();
  595. }
  596. public static boolean TSPselected() {
  597. return CB_TSP.isSelected();
  598. }
  599.  
  600. static class myRadio extends JRadioButton {
  601. public myRadio(final JFrame f, String n, ButtonGroup g) {
  602. super(n);
  603. setFont(new Font("Dialog", Font.BOLD, 11));
  604. setFocusPainted(false);
  605. setOpaque(false);
  606. setHorizontalTextPosition(JCheckBox.LEADING);
  607. addActionListener(new ActionListener() {
  608. public void actionPerformed(ActionEvent e) {
  609. //((JFrame) getParent().getParent().getParent().getParent().getParent()).setTitle("");
  610. boolean isSet = TSPselected();
  611. f.setTitle((isSet ? "TSP " : "")+getText().toUpperCase());
  612. BRoute.setText(isSet ? " TSP ROUTE " : " FIND MST ");
  613. BRoute.setToolTipText(" find "+(isSet ? "'travelling salesman problem' route " : "minimum spanning tree using "+getText()+"'s algorithm "));
  614. JL.setVisible(RBPrim.isSelected());
  615. JTF.setVisible(RBPrim.isSelected());
  616. }
  617. });
  618. g.add(this);
  619. }
  620.  
  621. public void paintComponent(Graphics g) {
  622. super.paintComponent(g);
  623. if (this.isSelected())
  624. setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
  625. else
  626. setCursor(new Cursor(Cursor.HAND_CURSOR));
  627. }
  628. }
  629. }

Report this snippet  

You need to login to post a comment.