Search Results

Search found 269 results on 11 pages for 'actionlistener'.

Page 3/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Getting JRuby to work in RubyMine

    - by John Baker
    I setup the proper SDK because all my ruby code will compile but RubyMine complains that it can't find the any of my java classes? Is this a flaw or is there a way to get it to recognizewhere the classes are? Here is my code, I have underlined all the things its complaining about require 'java' include_class 'java.awt.event.ActionListener' include_class 'javax.swing.JButton' include_class 'javax.swing.JFrame' class ClickAction include ActionListener def action_performed(event) puts "Button got clicked." end end Is there a way around this because I'd love to buy RubyMine if it's able to inform me of what Java classes and methods I can pick from. Thanks

    Read the article

  • Recursion causes exit to exit all JFrames (terminates app)

    - by Trizicus
    I have made an application that gives the user the option to open up a new spawn of the application entirely. When the user does so and closes the application the entire application terminates; not just the window. How should I go about recursively spawning an application and then when the user exits the JFrame spawn; killing just that JFrame and not the entire instance? Here is the relevant code: [...] JMenuItem newMenuItem = new JMenuItem ("New"); newMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new MainWindow(); } }); fileMenu.add(newMenuItem); [....] JMenuItem exit = new JMenuItem("Exit"); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }); fileMenu.add(exit); [...]

    Read the article

  • Java: where should I put anonymous listener logic code?

    - by tulskiy
    Hi, we had a debate at work about what is the best practice for using listeners in java: whether listener logic should stay in the anonymous class, or it should be in a separate method, for example: button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // code here } }); or button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttonPressed(); } }); private void buttonPressed() { // code here } which is the recommended way in terms of readability and maintainability? I prefer to keep the code inside the listener and only if gets too large, make it an inner class. Here I assume that the code is not duplicated anywhere else. Thank you.

    Read the article

  • Javascript calling JSF handler method

    - by msharma
    Hi All, I am reading an xml file using javascript and then I need to submit my form so that it calls a particular method in my JSF handler. Usually this can be done on a jsp when user clicks a button by having an actionlistener like so: <h:commandLink styleClass="button" action="#{myHandler.outcome}" actionListener="#{myHandler.doNext}"> <span><h:outputText value="#{text.button_submit}" /></span> </h:commandLink> I am not sure how to call a method like 'doNext' above in the handler from javascript. I cannot do a simple: document.form.submit(); as it then repeats the processing i have already done. I want to read values from an xml file and then call a particular method in handler. Any ideas much appreciated.

    Read the article

  • repaint problem

    - by user357816
    I have a problem with my repaint in the method move. I dont know what to doo, the code is below import java.awt.*; import java.io.*; import java.text.*; import java.util.*; import javax.sound.sampled.*; import javax.swing.*; import javax.swing.Timer; import java.awt.event.*; import java.lang.*; public class bbb extends JPanel { public Stack<Integer> stacks[]; public JButton auto,jugar,nojugar; public JButton ok,ok2; public JLabel info=new JLabel("Numero de Discos: "); public JLabel instruc=new JLabel("Presiona la base de las torres para mover las fichas"); public JLabel instruc2=new JLabel("No puedes poner una pieza grande sobre una pequenia!"); public JComboBox numeros=new JComboBox(); public JComboBox velocidad=new JComboBox(); public boolean seguir=false,parar=false,primera=true; public int n1,n2,n3; public int click1=0; public int opcion=1,tiempo=50; public int op=1,continuar=0,cont=0; public int piezas=0; public int posx,posy; public int no; public bbb() throws IOException { stacks = new Stack[3]; stacks[0]=new Stack<Integer>(); stacks[1]=new Stack<Integer>(); stacks[2]=new Stack<Integer>(); setPreferredSize(new Dimension(1366,768)); ok=new JButton("OK"); ok.setBounds(new Rectangle(270,50,70,25)); ok.addActionListener(new okiz()); ok2=new JButton("OK"); ok2.setBounds(new Rectangle(270,50,70,25)); ok2.addActionListener(new vel()); add(ok2);ok2.setVisible(false); auto=new JButton("Automatico"); auto.setBounds(new Rectangle(50,80,100,25)); auto.addActionListener(new a()); jugar=new JButton("PLAY"); jugar.setBounds(new Rectangle(100,100,70,25)); jugar.addActionListener(new play()); nojugar=new JButton("PAUSE"); nojugar.setBounds(new Rectangle(100,150,70,25)); nojugar.addActionListener(new stop()); setLayout(null); info.setBounds(new Rectangle(50,50,170,25)); info.setForeground(Color.white); instruc.setBounds(new Rectangle(970,50,570,25)); instruc.setForeground(Color.white); instruc2.setBounds(new Rectangle(970,70,570,25)); instruc2.setForeground(Color.white); add(instruc);add(instruc2); add(jugar);add(nojugar);jugar.setVisible(false);nojugar.setVisible(false); add(info); info.setVisible(false); add(ok); ok.setVisible(false); add(auto); numeros.setBounds(new Rectangle(210,50,50,25)); numeros.addItem(1);numeros.addItem(2);numeros.addItem(3);numeros.addItem(4);numeros.addItem(5); numeros.addItem(6);numeros.addItem(7);numeros.addItem(8);numeros.addItem(9);numeros.addItem(10); add(numeros); numeros.setVisible(false); velocidad.setBounds(new Rectangle(150,50,100,25)); velocidad.addItem("Lenta"); velocidad.addItem("Intermedia"); velocidad.addItem("Rapida"); add(velocidad); velocidad.setVisible(false); } public void Mover(int origen, int destino) { for (int i=0;i<3;i++) { System.out.print("stack "+i+": "); for(int n : stacks[i]) System.out.print(n+";"); System.out.println(""); } System.out.println("de <"+origen+"> a <"+destino+">"); stacks[destino].push(stacks[origen].pop()); System.out.println(""); this.validate(); this.repaint( ); } public void hanoi(int origen, int destino, int cuantas) { while (parar) {} if (cuantas <= 1) Mover(origen,destino); else { hanoi(origen,3 - (origen+destino),cuantas-1); Mover(origen,destino); hanoi(3 - (origen+destino),destino,cuantas-1); } } public void paintComponent(Graphics g) { ImageIcon fondo= new ImageIcon("fondo.jpg"); g.drawImage(fondo.getImage(),0, 0,1366,768,null); g.setColor(new Color((int)(Math.random() * 254), (int)(Math.random() *255), (int)(Math.random() * 255))); g.fillRect(0,0,100,100); g.setColor(Color.white); g.fillRect(150,600,250,25); g.fillRect(550,600,250,25); g.fillRect(950,600,250,25); g.setColor(Color.red); g.fillRect(270,325,10,275); g.fillRect(270+400,325,10,275); g.fillRect(270+800,325,10,275); int x, y,top=0; g.setColor(Color.yellow); x=150;y=580; for(int ii:stacks[0]) { g.fillRect(x+((ii*125)/10),y-(((ii)*250)/10),((10-ii)*250)/10,20);} x=550;y=580; for(int ii:stacks[1]) {g.fillRect(x+((ii*125)/10),y-(((ii)*250)/10),((10-ii)*250)/10,20);} x=950;y=580; for(int ii:stacks[2]) {g.fillRect(x+((ii*125)/10),y-(((ii)*250)/10),((10-ii)*250)/10,20);} System.out.println("ENTRO"); setOpaque(false); } private class play implements ActionListener //manual { public void actionPerformed(ActionEvent algo) { parar=false; if(primera=true) { hanoi(0,2,no); primera=false; } } } private class stop implements ActionListener //manual { public void actionPerformed(ActionEvent algo) { parar=true; } } private class vel implements ActionListener //manual { public void actionPerformed(ActionEvent algo) { if (velocidad.getSelectedItem()=="Lenta") {tiempo=150;} else if (velocidad.getSelectedItem()=="Intermedia") {tiempo=75;} else tiempo=50; ok2.setVisible(false); jugar.setVisible(true); nojugar.setVisible(true); } } private class a implements ActionListener //auto { public void actionPerformed(ActionEvent algo) { auto.setVisible(false); info.setVisible(true); numeros.setVisible(true); ok.setVisible(true); op=3; } } private class okiz implements ActionListener //ok { public void actionPerformed(ActionEvent algo) { no=Integer.parseInt(numeros.getSelectedItem().toString()); piezas=no; if (no>0 && no<11) { info.setVisible(false); numeros.setVisible(false); ok.setVisible(false); for (int i=no;i>0;i--) stacks[0].push(i); opcion=2; if (op==3) { info.setText("Velocidad: ");info.setVisible(true); velocidad.setVisible(true); ok2.setVisible(true); } } else { } repaint(); } } } the code of the other class that calls the one up is below: import java.awt.*; import java.io.*; import java.net.URL; import javax.imageio.*; import javax.swing.*; import javax.swing.border.*; import java.lang.*; import java.awt.event.*; public class aaa extends JPanel { private ImageIcon Background; private JLabel fondo; public static void main(String[] args) throws IOException { JFrame.setDefaultLookAndFeelDecorated(true); final JPanel cp = new JPanel(new BorderLayout()); JFrame frame = new JFrame ("Torres de Hanoi"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.setSize(550,550); frame.setVisible(true); bbb panel = new bbb(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } }

    Read the article

  • Annotation Processor for Superclass Sensitive Actions

    - by Geertjan
    Someone creating superclass sensitive actions should need to specify only the following things: The condition under which the popup menu item should be available, i.e., the condition under which the action is relevant. And, for superclass sensitive actions, the condition is the name of a superclass. I.e., if I'm creating an action that should only be invokable if the class implements "org.openide.windows.TopComponent",  then that fully qualified name is the condition. The position in the list of Java class popup menus where the new menu item should be found, relative to the existing menu items. The display name. The path to the action folder where the new action is registered in the Central Registry. The code that should be executed when the action is invoked. In other words, the code for the enablement (which, in this case, means the visibility of the popup menu item when you right-click on the Java class) should be handled generically, under the hood, and not every time all over again in each action that needs this special kind of enablement. So, here's the usage of my newly created @SuperclassBasedActionAnnotation, where you should note that the DataObject must be in the Lookup, since the action will only be available to be invoked when you right-click on a Java source file (i.e., text/x-java) in an explorer view: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.netbeans.sbas.annotations.SuperclassBasedActionAnnotation; import org.openide.awt.StatusDisplayer; import org.openide.loaders.DataObject; import org.openide.util.NbBundle; import org.openide.util.Utilities; @SuperclassBasedActionAnnotation( position=30, displayName="#CTL_BrandTopComponentAction", path="File", type="org.openide.windows.TopComponent") @NbBundle.Messages("CTL_BrandTopComponentAction=Brand") public class BrandTopComponentAction implements ActionListener { private final DataObject context; public BrandTopComponentAction() { context = Utilities.actionsGlobalContext().lookup(DataObject.class); } @Override public void actionPerformed(ActionEvent ev) { String message = context.getPrimaryFile().getPath(); StatusDisplayer.getDefault().setStatusText(message); } } That implies I've created (in a separate module to where it is used) a new annotation. Here's the definition: package org.netbeans.sbas.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface SuperclassBasedActionAnnotation { String type(); String path(); int position(); String displayName(); } And here's the processor: package org.netbeans.sbas.annotations; import java.util.Set; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import org.openide.filesystems.annotations.LayerBuilder.File; import org.openide.filesystems.annotations.LayerGeneratingProcessor; import org.openide.filesystems.annotations.LayerGenerationException; import org.openide.util.lookup.ServiceProvider; @ServiceProvider(service = Processor.class) @SupportedAnnotationTypes("org.netbeans.sbas.annotations.SuperclassBasedActionAnnotation") @SupportedSourceVersion(SourceVersion.RELEASE_6) public class SuperclassBasedActionProcessor extends LayerGeneratingProcessor { @Override protected boolean handleProcess(Set annotations, RoundEnvironment roundEnv) throws LayerGenerationException { Elements elements = processingEnv.getElementUtils(); for (Element e : roundEnv.getElementsAnnotatedWith(SuperclassBasedActionAnnotation.class)) { TypeElement clazz = (TypeElement) e; SuperclassBasedActionAnnotation mpm = clazz.getAnnotation(SuperclassBasedActionAnnotation.class); String teName = elements.getBinaryName(clazz).toString(); String originalFile = "Actions/" + mpm.path() + "/" + teName.replace('.', '-') + ".instance"; File actionFile = layer(e).file( originalFile). bundlevalue("displayName", mpm.displayName()). methodvalue("instanceCreate", "org.netbeans.sbas.annotations.SuperclassSensitiveAction", "create"). stringvalue("type", mpm.type()). newvalue("delegate", teName); actionFile.write(); File javaPopupFile = layer(e).file( "Loaders/text/x-java/Actions/" + teName.replace('.', '-') + ".shadow"). stringvalue("originalFile", originalFile). intvalue("position", mpm.position()); javaPopupFile.write(); } return true; } } The "SuperclassSensitiveAction" referred to in the code above is unchanged from how I had it in yesterday's blog entry. When I build the module containing two action listeners that use my new annotation, the generated layer file looks as follows, which is identical to the layer file entries I hard coded yesterday: <folder name="Actions"> <folder name="File"> <file name="org-netbeans-sbas-impl-ActionListenerSensitiveAction.instance"> <attr name="displayName" stringvalue="Process Action Listener"/> <attr methodvalue="org.netbeans.sbas.annotations.SuperclassSensitiveAction.create" name="instanceCreate"/> <attr name="type" stringvalue="java.awt.event.ActionListener"/> <attr name="delegate" newvalue="org.netbeans.sbas.impl.ActionListenerSensitiveAction"/> </file> <file name="org-netbeans-sbas-impl-BrandTopComponentAction.instance"> <attr bundlevalue="org.netbeans.sbas.impl.Bundle#CTL_BrandTopComponentAction" name="displayName"/> <attr methodvalue="org.netbeans.sbas.annotations.SuperclassSensitiveAction.create" name="instanceCreate"/> <attr name="type" stringvalue="org.openide.windows.TopComponent"/> <attr name="delegate" newvalue="org.netbeans.sbas.impl.BrandTopComponentAction"/> </file> </folder> </folder> <folder name="Loaders"> <folder name="text"> <folder name="x-java"> <folder name="Actions"> <file name="org-netbeans-sbas-impl-ActionListenerSensitiveAction.shadow"> <attr name="originalFile" stringvalue="Actions/File/org-netbeans-sbas-impl-ActionListenerSensitiveAction.instance"/> <attr intvalue="10" name="position"/> </file> <file name="org-netbeans-sbas-impl-BrandTopComponentAction.shadow"> <attr name="originalFile" stringvalue="Actions/File/org-netbeans-sbas-impl-BrandTopComponentAction.instance"/> <attr intvalue="30" name="position"/> </file> </folder> </folder> </folder> </folder>

    Read the article

  • Java JPanel not showing up....

    - by user69514
    I'm not sure what I am doing wrong, but the text for my JPanels is not showing up. I just get the question number text, but the question is not showing up. Any ideas what I am doing wrong? import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class NewFrame extends JFrame { JPanel centerpanel; // For the questions. CardLayout card; // For the centerpanel. JTextField tf; // Used in question 1. boolean // Store selections for Q2. q2Option1, q2Option2, q2Option3, q2Option4; JList q4List; // For question 4. double // Score on each question. q1Score = 0, q2Score = 0, q3Score = 0, q4Score = 0; // Constructor. public NewFrame (int width, int height) { this.setTitle ("Snoot Club Membership Test"); this.setResizable (true); this.setSize (width, height); Container cPane = this.getContentPane(); // cPane.setLayout (new BorderLayout()); // First, a welcome message, as a Label. JLabel L = new JLabel ("<html><b>Are you elitist enough for our exclusive club?" + " <br>Fill out the form and find out</b></html>"); L.setForeground (Color.blue); cPane.add (L, BorderLayout.NORTH); // Now the center panel with the questions. card = new CardLayout (); centerpanel = new JPanel (); centerpanel.setLayout (card); centerpanel.setOpaque (false); // Each question will be created in a separate method. // The cardlayout requires a label as second parameter. centerpanel.add (firstQuestion (), "1"); centerpanel.add (secondQuestion(), "2"); centerpanel.add (thirdQuestion(), "3"); centerpanel.add (fourthQuestion(), "4"); cPane.add (centerpanel, BorderLayout.CENTER); // Next, a panel of four buttons at the bottom. // The four buttons: quit, submit, next-question, previous-question. JPanel bottomPanel = getBottomPanel (); cPane.add (bottomPanel, BorderLayout.SOUTH); // Finally, show the frame. this.setVisible (true); } // No-parameter constructor. public NewFrame () { this (500, 300); } // The first question uses labels for the question and // gets input via a textfield. A panel containing all // these things is returned. The question asks for // a vacation destination: the more exotic the location, // the higher the score. JPanel firstQuestion () { // We will package everything into a panel and return the panel. JPanel subpanel = new JPanel (); // We will place things in a single column, so // a GridLayout with one column is appropriate. subpanel.setLayout (new GridLayout (8,1)); JLabel L1 = new JLabel ("Question 1:"); L1.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L1); JLabel L2 = new JLabel (" Select a vacation destination"); L2.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L2); JLabel L3 = new JLabel (" 1. Baltimore"); L3.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L3); JLabel L4 = new JLabel (" 2. Disneyland"); L4.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L4); JLabel L5 = new JLabel (" 3. Grand Canyon"); L5.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L5); JLabel L6 = new JLabel (" 4. French Riviera"); L6.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L6); JLabel L7 = new JLabel ("Enter 1,2,3 or 4 below:"); L7.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L7); // Here's the textfield to get user-input. tf = new JTextField (); tf.addActionListener ( new ActionListener () { // This interface has only one method. public void actionPerformed (ActionEvent a) { String q1String = a.getActionCommand(); if (q1String.equals ("2")) q1Score = 2; else if (q1String.equals ("3")) q1Score = 3; else if (q1String.equals ("4")) q1Score = 4; else q1Score = 1; } } ); subpanel.add (tf); return subpanel; } // For the second question, a collection of checkboxes // will be used. More than one selection can be made. // A listener is required for each checkbox. The state // of each checkbox is recorded. JPanel secondQuestion () { JPanel subpanel = new JPanel (); subpanel.setLayout (new GridLayout (7,1)); JLabel L1 = new JLabel ("Question 2:"); L1.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L1); JLabel L2 = new JLabel (" Select ONE OR MORE things that "); L2.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L2); JLabel L3 = new JLabel (" you put into your lunch sandwich"); L3.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L3); // Initialize the selections to false. q2Option1 = q2Option2 = q2Option3 = q2Option4 = false; // First checkbox. JCheckBox c1 = new JCheckBox ("Ham, beef or turkey"); c1.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JCheckBox c = (JCheckBox) i.getSource(); q2Option1 = c.isSelected(); } } ); subpanel.add (c1); // Second checkbox. JCheckBox c2 = new JCheckBox ("Cheese"); c2.addItemListener ( new ItemListener () { // This is where we will react to a change in checkbox. public void itemStateChanged (ItemEvent i) { JCheckBox c = (JCheckBox) i.getSource(); q2Option2 = c.isSelected(); } } ); subpanel.add (c2); // Third checkbox. JCheckBox c3 = new JCheckBox ("Sun-dried Arugula leaves"); c3.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JCheckBox c = (JCheckBox) i.getSource(); q2Option3 = c.isSelected(); } } ); subpanel.add (c3); // Fourth checkbox. JCheckBox c4 = new JCheckBox ("Lemon-enhanced smoked Siberian caviar"); c4.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JCheckBox c = (JCheckBox) i.getSource(); q2Option4 = c.isSelected(); } } ); subpanel.add (c4); return subpanel; } // The third question allows only one among four choices // to be selected. We will use radio buttons. JPanel thirdQuestion () { JPanel subpanel = new JPanel (); subpanel.setLayout (new GridLayout (6,1)); JLabel L1 = new JLabel ("Question 3:"); L1.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L1); JLabel L2 = new JLabel (" And which mustard do you use?"); L2.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L2); // First, create the ButtonGroup instance. // We will add radio buttons to this group. ButtonGroup bGroup = new ButtonGroup(); // First checkbox. JRadioButton r1 = new JRadioButton ("Who cares?"); r1.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JRadioButton r = (JRadioButton) i.getSource(); if (r.isSelected()) q3Score = 1; } } ); bGroup.add (r1); subpanel.add (r1); // Second checkbox. JRadioButton r2 = new JRadioButton ("Safeway Brand"); r2.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JRadioButton r = (JRadioButton) i.getSource(); if (r.isSelected()) q3Score = 2; } } ); bGroup.add (r2); subpanel.add (r2); // Third checkbox. JRadioButton r3 = new JRadioButton ("Fleishman's"); r3.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JRadioButton r = (JRadioButton) i.getSource(); if (r.isSelected()) q3Score = 3; } } ); bGroup.add (r3); subpanel.add (r3); // Fourth checkbox. JRadioButton r4 = new JRadioButton ("Grey Poupon"); r4.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JRadioButton r = (JRadioButton) i.getSource(); if (r.isSelected()) q3Score = 4; } } ); bGroup.add (r4); subpanel.add (r4); return subpanel; } // For the fourth question we will use a drop-down Choice. JPanel fourthQuestion () { JPanel subpanel = new JPanel (); subpanel.setLayout (new GridLayout (3,1)); JLabel L1 = new JLabel ("Question 4:"); L1.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L1); JLabel L2 = new JLabel (" Your movie preference, among these:"); L2.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L2); // Create a JList with options. String[] movies = { "Lethal Weapon IV", "Titanic", "Saving Private Ryan", "Le Art Movie avec subtitles"}; q4List = new JList (movies); q4Score = 1; q4List.addListSelectionListener ( new ListSelectionListener () { public void valueChanged (ListSelectionEvent e) { q4Score = 1 + q4List.getSelectedIndex(); } } ); subpanel.add (q4List); return subpanel; } void computeResult () { // Clear the center panel. centerpanel.removeAll(); // Create a new panel to display in the center. JPanel subpanel = new JPanel (new GridLayout (5,1)); // Score on question 1. JLabel L1 = new JLabel ("Score on question 1: " + q1Score); L1.setFont (new Font ("Serif", Font.ITALIC, 15)); subpanel.add (L1); // Score on question 2. if (q2Option1) q2Score += 1; if (q2Option2) q2Score += 2; if (q2Option3) q2Score += 3; if (q2Option4) q2Score += 4; q2Score = 0.6 * q2Score; JLabel L2 = new JLabel ("Score on question 2: " + q2Score); L2.setFont (new Font ("Serif", Font.ITALIC, 15)); subpanel.add (L2); // Score on question 3. JLabel L3 = new JLabel ("Score on question 3: " + q3Score); L3.setFont (new Font ("Serif", Font.ITALIC, 15)); subpanel.add (L3); // Score on question 4. JLabel L4 = new JLabel ("Score on question 4: " + q4Score); L4.setFont (new Font ("Serif", Font.ITALIC, 15)); subpanel.add (L4); // Weighted score. double avg = (q1Score + q2Score + q3Score + q4Score) / (double) 4; JLabel L5; if (avg <= 3.5) L5 = new JLabel ("Your average score: " + avg + " - REJECTED!"); else L5 = new JLabel ("Your average score: " + avg + " - WELCOME!"); L5.setFont (new Font ("Serif", Font.BOLD, 20)); //L5.setAlignment (JLabel.CENTER); subpanel.add (L5); // Now add the new subpanel. centerpanel.add (subpanel, "5"); // Need to mark the centerpanel as "altered" centerpanel.invalidate(); // Everything "invalid" (e.g., the centerpanel above) // is now re-computed. this.validate(); } JPanel getBottomPanel () { // Create a panel into which we will place buttons. JPanel bottomPanel = new JPanel (); // A "previous-question" button. JButton backward = new JButton ("Previous question"); backward.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); backward.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { // Go back in the card layout. card.previous (centerpanel); } } ); bottomPanel.add (backward); // A forward button. JButton forward = new JButton ("Next question"); forward.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); forward.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { // Go forward in the card layout. card.next (centerpanel); } } ); bottomPanel.add (forward); // A submit button. JButton submit = new JButton ("Submit"); submit.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); submit.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { // Perform submit task. computeResult(); } } ); bottomPanel.add (submit); JButton quitb = new JButton ("Quit"); quitb.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); quitb.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { System.exit (0); } } ); bottomPanel.add (quitb); return bottomPanel; } } public class Survey { public static void main (String[] argv) { NewFrame nf = new NewFrame (600, 300); } }

    Read the article

  • How do I ensure that a JPanel Shrinks when the parent frame is resized?

    - by dah
    I have a basic notes panel that I'm looking to shrink the width of when the parent jframe is resized but it isn't happening. I'm using nested gridbaglayouts. package com.protocase.notes.views; import com.protocase.notes.controller.NotesController; import com.protocase.notes.model.Subject; import com.protocase.notes.model.Note; import com.protocase.notes.model.database.PMSNotesAdapter; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; /** * @author DavidH */ public class NotesViewer extends JPanel { // <editor-fold defaultstate="collapsed" desc="Attributes"> private Subject subject; private NotesController controller; //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Getters N' Setters"> /** * Gets back the current subject. * @return */ public Subject getSubject() { return subject; } public NotesController getController() { return controller; } public void setController(NotesController controller) { this.controller = controller; } /** * Should clear the panel of the current subject and load the details for * the other object. * @param subject */ public void setSubject(Subject subject) { this.subject = subject; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructor"> /** * -- Sets up a note viewer with a subject and a controller. Likely this * would be the constructor used if you were passing off from another * NoteViewer or something else that used a notes adapter or controller. * @param subject * @param controller */ public NotesViewer(Subject subject, NotesController controller) { this.subject = subject; this.controller = controller; initComponents(); } /** * -- Sets up a note view with a subject and creates a new controller. This * would be the constructor typically chosen if choosing notes was * infrequent and only one or two notes needs to be displayed. * @param subject */ public NotesViewer(Subject subject) { this(subject, new NotesController(new PMSNotesAdapter())); } /** * -- Sets up a note view without a subject and creates a new controller. * This would be for a note viewer without any notes, perhaps populating * as you choose values in another form. * @param subject */ public NotesViewer() { this(null); } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="initComponents()"> /** * Sets up the view for the NotesViewer */ private void initComponents() { // -- Make a new panel for the header JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridy = 0; c.weightx = .5; //c.anchor = GridBagConstraints.NORTHWEST; JLabel label = new JLabel("Viewing Notes for [Subject]"); label.setAlignmentX(JLabel.LEFT_ALIGNMENT); label.setBorder(BorderFactory.createLineBorder(Color.YELLOW)); panel.add(label); JButton newNoteButton = new JButton("New"); c = new GridBagConstraints(); // c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 0; c.weightx = .5; c.anchor = GridBagConstraints.EAST; panel.add(newNoteButton, c); // -- NotePanels c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.weighty = 1; c.gridx = 0; c.gridwidth = 2; int y = 1; for (Note n : subject.getNotes()) { c.gridy = y++; panel.add(new NotesPanel(n, controller), c); } this.setLayout(new GridBagLayout()); GridBagConstraints pc = new GridBagConstraints(); pc.gridx = 0; pc.gridy = 0; pc.weightx = 1; pc.weighty = 1; pc.fill = GridBagConstraints.BOTH; panel.setBackground(Color.blue); JScrollPane scroll = new JScrollPane(); scroll.setViewportView(panel); //scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.add(scroll, pc); //this.add(panel, pc); // -- Add it all to the layout } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="private methods"> //</editor-fold> } package com.protocase.notes.views; import com.protocase.notes.controller.NotesController; import com.protocase.notes.model.Note; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.MatteBorder; /** * @author dah01 */ public class NotesPanel extends JPanel { // <editor-fold defaultstate="collapsed" desc="Attributes"> private Note note; private NotesController controller; private CardLayout cardLayout; private JTextArea viewTextArea; private JTextArea editTextArea; //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Getters N' Setters"> public NotesController getController() { return controller; } public void setController(NotesController controller) { this.controller = controller; } public Note getNote() { return note; } public void setNote(Note note) { this.note = note; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructor"> /** * Sets up a note panel that shows everything about the note. * @param note */ public NotesPanel(Note note, NotesController controller) { this.note = note; cardLayout = new CardLayout(); this.setLayout(cardLayout); // -- Setup the layout manager. this.setBackground(new Color(199, 187, 192)); this.setBorder(new BevelBorder(BevelBorder.RAISED)); // -- ViewPanel this.add("ViewPanel", initViewPanel()); this.add("EditPanel", initEditPanel()); } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="EditPanel"> private JPanel initEditPanel() { JPanel editPanel = new JPanel(); editPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.gridy = 0; c.weightx = 1; c.weighty = 0.3; editPanel.add(initCreatorLabel(), c); c.gridy++; editPanel.add(initEditTextScroll(), c); c.gridy++; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; editPanel.add(initEditorLabel(), c); c.gridx++; c.anchor = GridBagConstraints.EAST; editPanel.add(initSaveButton(), c); return editPanel; } private JScrollPane initEditTextScroll() { this.editTextArea = new JTextArea(note.getContents()); editTextArea.setLineWrap(true); editTextArea.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(editTextArea); scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT); Border b = scrollPane.getViewportBorder(); MatteBorder mb = BorderFactory.createMatteBorder(2, 2, 2, 2, Color.BLUE); scrollPane.setBorder(mb); return scrollPane; } private JButton initSaveButton() { final CardLayout l = this.cardLayout; final JPanel p = this; final NotesController c = this.controller; final Note n = this.note; final JTextArea noteText = this.viewTextArea; final JTextArea textToSubmit = this.editTextArea; ActionListener al = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //controller.saveNote(n); noteText.setText(textToSubmit.getText()); l.next(p); } }; JButton saveButton = new JButton("Save"); saveButton.addActionListener(al); saveButton.setPreferredSize(new Dimension(62, 26)); return saveButton; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="ViewPanel"> private JPanel initViewPanel() { JPanel viewPanel = new JPanel(); viewPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL ; c.gridy = 0; c.weightx = 1; c.weighty = 0.3; viewPanel.add(initCreatorLabel(), c); c.gridy++; viewPanel.add(this.initNoteTextArea(), c); c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.WEST; c.gridy++; viewPanel.add(initEditorLabel(), c); c.gridx++; c.anchor = GridBagConstraints.EAST; viewPanel.add(initEditButton(), c); return viewPanel; } private JLabel initCreatorLabel() { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if (note != null) { String noteBy = "Note by " + note.getCreator(); String noteCreated = formatter.format(note.getDateCreated()); JLabel creatorLabel = new JLabel(noteBy + " @ " + noteCreated); creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT); return creatorLabel; } else { System.out.println("NOTE IS NULL"); return null; } } private JScrollPane initNoteTextArea() { // -- Setup the notes area. this.viewTextArea = new JTextArea(note.getContents()); viewTextArea.setEditable(false); viewTextArea.setLineWrap(true); viewTextArea.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(viewTextArea); scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT); return scrollPane; } private JLabel initEditorLabel() { // -- Setup the edited by label. JLabel editorLabel = new JLabel(" -- Last edited by " + note.getLastEdited() + " at " + note.getDateModified()); editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT); return editorLabel; } private JButton initEditButton() { final CardLayout l = this.cardLayout; final JPanel p = this; ActionListener ar = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { l.next(p); } }; JButton editButton = new JButton("Edit"); editButton.setPreferredSize(new Dimension(62,26)); editButton.addActionListener(ar); return editButton; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Grow Width When Resized"> @Override public Dimension getPreferredSize() { int fw = this.getParent().getSize().width; int fh = super.getPreferredSize().height; return new Dimension(fw,fh); } //</editor-fold> }

    Read the article

  • How to set BackGround color to a divider in JSplitPane

    - by Sunil Kumar Sahoo
    I have created a divider in JSplitPane. I am unable to set the color of divider. I want to set the color of divider. please help me how to set color of that divider import javax.swing.; import java.awt.; import java.awt.event.*; public class SplitPaneDemo { JFrame frame; JPanel left, right; JSplitPane pane; int lastDividerLocation = -1; public static void main(String[] args) { SplitPaneDemo demo = new SplitPaneDemo(); demo.makeFrame(); demo.frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); demo.frame.show(); } public JFrame makeFrame() { frame = new JFrame(); // Create a horizontal split pane. pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); left = new JPanel(); left.setBackground(Color.red); pane.setLeftComponent(left); right = new JPanel(); right.setBackground(Color.green); pane.setRightComponent(right); JButton showleft = new JButton("Left"); showleft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Container c = frame.getContentPane(); if (pane.isShowing()) { lastDividerLocation = pane.getDividerLocation(); } c.remove(pane); c.remove(left); c.remove(right); c.add(left, BorderLayout.CENTER); c.validate(); c.repaint(); } }); JButton showright = new JButton("Right"); showright.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Container c = frame.getContentPane(); if (pane.isShowing()) { lastDividerLocation = pane.getDividerLocation(); } c.remove(pane); c.remove(left); c.remove(right); c.add(right, BorderLayout.CENTER); c.validate(); c.repaint(); } }); JButton showboth = new JButton("Both"); showboth.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Container c = frame.getContentPane(); c.remove(pane); c.remove(left); c.remove(right); pane.setLeftComponent(left); pane.setRightComponent(right); c.add(pane, BorderLayout.CENTER); if (lastDividerLocation >= 0) { pane.setDividerLocation(lastDividerLocation); } c.validate(); c.repaint(); } }); JPanel buttons = new JPanel(); buttons.setLayout(new GridBagLayout()); buttons.add(showleft); buttons.add(showright); buttons.add(showboth); frame.getContentPane().add(buttons, BorderLayout.NORTH); pane.setPreferredSize(new Dimension(400, 300)); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.pack(); pane.setDividerLocation(0.5); return frame; } } Thanks Sunil kumar Sahoo

    Read the article

  • JSTL c:forEach causes @ViewScoped bean to invoke @PostConstruct on every request

    - by Nitesh Panchal
    Hello, Again i see that the @PostConstruct is firing every time even though no binding attribute is used. See this code :- <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:c="http://java.sun.com/jsp/jstl/core"> <h:head> <title>Facelet Title</title> </h:head> <h:body> <h:form> <c:forEach var="item" items="#{TestBean.listItems}"> <h:outputText value="#{item}"/> </c:forEach> <h:commandButton value="Click" actionListener="#{TestBean.actionListener}"/> </h:form> </h:body> </html> And this is the simplest possible bean in JSF :- package managedBeans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; @ManagedBean(name="TestBean") @ViewScoped public class TestBean implements Serializable { private List<String> listItems; public List<String> getListItems() { return listItems; } public void setListItems(List<String> listItems) { this.listItems = listItems; } public TestBean() { } @PostConstruct public void init(){ System.out.println("Post Construct fired!"); listItems = new ArrayList<String>(); listItems.add("Mango"); listItems.add("Apple"); listItems.add("Banana"); } public void actionListener(){ System.out.println("Action Listener fired!"); } } Do you see any behaviour that should cause postconstruct callback to fire each time? I think JSF 2.0 is highly unstable. If it has to fire PostConstruct each and every time what purpose does @ViewScoped serve. Why not to use @RequestScoped only? I thought i have made some mistake in my application. But when i created this simplest possible in JSF, i still get this error. Am i not understanding the scopes of JSF? or are they not testing it properly? Further, if you remove c:forEach and replace it with ui:repeat, then it works fine. Waiting for replies to confirm whether it is bug or it is intentional to stop the programmers from using jstl?

    Read the article

  • Yet another bug of JSF?

    - by Nitesh Panchal
    Hello, Again i see that the @PostConstruct is firing every time even though no binding attribute is used. See this code :- <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:c="http://java.sun.com/jsp/jstl/core"> <h:head> <title>Facelet Title</title> </h:head> <h:body> <h:form> <c:forEach var="item" items="#{TestBean.listItems}"> <h:outputText value="#{item}"/> </c:forEach> <h:commandButton value="Click" actionListener="#{TestBean.actionListener}"/> </h:form> </h:body> </html> And this is the simplest possible bean in JSF :- package managedBeans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; @ManagedBean(name="TestBean") @ViewScoped public class TestBean implements Serializable { private List<String> listItems; public List<String> getListItems() { return listItems; } public void setListItems(List<String> listItems) { this.listItems = listItems; } public TestBean() { } @PostConstruct public void init(){ System.out.println("Post Construct fired!"); listItems = new ArrayList<String>(); listItems.add("Mango"); listItems.add("Apple"); listItems.add("Banana"); } public void actionListener(){ System.out.println("Action Listener fired!"); } } Do you see any behaviour that should cause postconstruct callback to fire each time? I think JSF 2.0 is highly unstable. If it has to fire PostConstruct each and every time what purpose does @ViewScoped serve. Why not to use @RequestScoped only? I thought i have made some mistake in my application. But when i created this simplest possible in JSF, i still get this error. Am i not understanding the scopes of JSF? or are they not testing it properly? Further, if you remove c:forEach and replace it with ui:repeat, then it works fine. Waiting for replies to confirm whether it is bug or it is intentional to stop the programmers from using jstl?

    Read the article

  • ScrollPanel in java does not appear JTextarea resizes instead

    - by Casper Marcussen
    Hello everyone My program is finished, but testing it out, i found out that the scrollpanel does not appear, it just resizes the JTextarea instead. The code is provided below: package javaapplication15; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.io.IOException; import javax.swing.*; public class Tekstprogram extends JFrame { public Tekstprogram() { setSize(400, 600); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); Container Indhold = getContentPane(); Indhold.setLayout(new FlowLayout()); JButton openButton = new JButton("Open"); JButton saveButton = new JButton("Save"); final JLabel statusbar = new JLabel("Output of your selection will go here"); final JTextArea TekstOmråde = new JTextArea(29, 30); JScrollPane scrollText = new JScrollPane(TekstOmråde); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); int option = chooser.showOpenDialog(Tekstprogram.this); if (option == JFileChooser.APPROVE_OPTION) { File[] sf = chooser.getSelectedFiles(); String filelist = "nothing"; if (sf.length > 0) { filelist = sf[0].getName(); } for (int i = 1; i < sf.length; i++) { filelist = filelist + ", " + sf[i].getName(); } try { String strLine; File selectedFile = chooser.getSelectedFile(); FileInputStream in = new FileInputStream(selectedFile); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((strLine = br.readLine()) != null) { TekstOmråde.append(strLine + "\n"); } } catch (Exception e) { System.out.println("En fejl opstod ved" + e); } } } }); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); int option = chooser.showSaveDialog(Tekstprogram.this); if (option == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(TekstOmråde.getText()); out.close(); } catch (IOException e) { System.out.println("IOException fejl opstod :"); e.printStackTrace(); } } } }); Indhold.add(openButton); Indhold.add(saveButton); Indhold.add(TekstOmråde); Indhold.add(scrollText); Indhold.add(statusbar); } public static void main(String args[]) { Tekstprogram sfc = new Tekstprogram(); sfc.setVisible(true); } } Is there anyway to make the JTexarea static?

    Read the article

  • GUI Freezes and Output to JTextField from user input

    - by user2929005
    I am having I hope only two issues currently. I have had help on this on a previous question that I have asked but now I am running into different issues. My current issues now is that I need to print out into a JTextField a sorted array. I do not have questions about how to sort the array I just would like help on how to get the array to print to the JTextField when the Bubble Sort button is pressed. Currently when I press the button it freezes. It freezes at this line. list.add(Integer.valueOf(input.nextInt())); please help Thank you. import java.awt.EventQueue; import javax.swing.*; import java.awt.event.*; import java.util.*; public class Sorting { private JFrame frame; private JTextArea inputArea; private JTextField outputArea; ArrayList<Integer> list = new ArrayList<Integer>(); Scanner input = new Scanner(System.in); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Sorting window = new Sorting(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Sorting() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Sorting"); frame.getContentPane().setLayout(null); JButton bubbleButton = new JButton("Bubble Sort"); bubbleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { list.add(Integer.valueOf(input.nextInt())); // for(int i = 0; i < list.size(); i++){ // // } } }); bubbleButton.setBounds(10, 211, 114, 23); frame.getContentPane().add(bubbleButton); JButton mergeButton = new JButton("Merge Sort"); mergeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); mergeButton.setBounds(305, 211, 114, 23); frame.getContentPane().add(mergeButton); JButton quickButton = new JButton("Quick Sort"); quickButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); quickButton.setBounds(163, 211, 114, 23); frame.getContentPane().add(quickButton); inputArea = new JTextArea(); inputArea.setBounds(10, 36, 414, 51); frame.getContentPane().add(inputArea); outputArea = new JTextField(); outputArea.setEditable(false); outputArea.setBounds(10, 98, 414, 59); frame.getContentPane().add(outputArea); outputArea.setColumns(10); JLabel label = new JLabel("Please Enter 5 Numbers"); label.setHorizontalAlignment(SwingConstants.CENTER); label.setBounds(10, 11, 414, 14); frame.getContentPane().add(label); } }

    Read the article

  • save as .txt format

    - by user1180492
    I made a NotePad program. The problem is it doesn't save in .txt format, It save as a file with no format. But it can open .txt files. How can i fix it? Here is my work. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Scanner; import java.io.*; public class NotePad extends JFrame { private JTextArea noteArea; public static void main(String[] args) { NotePad p = new NotePad(); p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); p.setSize(500,300); p.setVisible(true); } public NotePad() { super("Java Notepad"); setLayout(new BorderLayout()); noteArea = new JTextArea("",20,20); noteArea.setWrapStyleWord(true); noteArea.setLineWrap(true); Font font = new Font("sanserif", Font.BOLD,14); noteArea.setFont(font); JScrollPane scroller = new JScrollPane(noteArea); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); add(scroller,BorderLayout.CENTER); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem openMenu = new JMenuItem("Open"); openMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser openFile = new JFileChooser(); openFile.showOpenDialog(new NotePad()); loadFile(openFile.getSelectedFile()); } }); JMenuItem saveMenu = new JMenuItem("Save"); saveMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser saveFile = new JFileChooser(); saveFile.showSaveDialog(new NotePad()); fileSaved(saveFile.getSelectedFile()); } }); JMenuItem exitMenu = new JMenuItem("Close"); exitMenu.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { System.exit(0); } }); fileMenu.add(openMenu); fileMenu.add(saveMenu); fileMenu.add(exitMenu); menuBar.add(fileMenu); this.setJMenuBar(menuBar); } public void loadFile(File file) { noteArea.setText(""); try { BufferedReader read = new BufferedReader(new FileReader(file)); String line = null; while((line =read.readLine())!=null) { noteArea.append(line +"\n"); } read.close(); } catch (Exception e) { System.out.println("Error " + e.toString()); } } public void fileSaved(File file) { try { PrintWriter writer = new PrintWriter(file); String[] lines = noteArea.getText().split("\\n"); for (String ) { writer.println(words); } writer.close(); } catch (Exception e) { System.out.println("Error " + e.toString()); } } } btw I can't post my question because of not explaning the scenario according to the site. So there. Thanks for the help

    Read the article

  • surviveFocusChange=true

    - by Geertjan
    Here's a very cool thing that I keep forgetting about but that Jesse reminded me of in the recent blog entries on Undo/Redo: "surviveFocusChange=true". Look at the screenshot below. You see two windows with a toolbar button. The toolbar button is enabled whenever an object named "Bla" is in the Lookup. The "Demo" window has a "Bla" object in its Lookup and hence the toolbar button is enabled when the focus is in the "Demo" window, as shown below: Now the focus is in the "Output" window, which does not have a "Bla" object in its Lookup and hence the button is disabled: However, there are scenarios where you might like the button to remain enabled even when the focus changes. (One such scenario is the Undo/Redo scenario in this blog a few days ago, i.e., even when the Properties window has the focus the Undo/Redo buttons should be enabled.) Here you can see that the button is enabled even though the focus has switched to the "Output" window: How to achieve this? Well, you need to register your Action to have "surviveFocusChange" set to "true". It is, by default, set to "false": import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle.Messages; @ActionID(category = "File", id = "org.mymodule.BlaAction") @ActionRegistration(surviveFocusChange=true, iconBase = "org/mymodule/Datasource.gif", displayName = "#CTL_BlaAction") @ActionReferences({     @ActionReference(path = "Toolbars/Bla", position = 0) }) @Messages("CTL_BlaAction=Bla") public final class BlaAction implements ActionListener {     private final Bla context;     public BlaAction(Bla context) {         this.context = context;     }     @Override     public void actionPerformed(ActionEvent ev) {         // TODO use context     } } That's all. Now folders and files will be created in the NetBeans Platform filesystem from the annotations above when the module is compiled such that the NetBeans Platform will automatically keep the button enabled even when the user switches focus to a window that does not contain a "Bla" object in its Lookup. Hence, the same "Bla" object will remain available when switching from one window to another, until a new "Bla" object will be made available in the Lookup.

    Read the article

  • JDeveloper 11.1.2 : Command Link in Table Column Work Around

    - by Frank Nimphius
    Just figured that in Oracle JDeveloper 11.1.2, clicking on a command link in a table does not mark the table row as selected as it is the behavior in previous releases of Oracle JDeveloper. For the time being, the following work around can be used to achieve the "old" behavior: To mark the table row as selected, you need to build and queue the table selection event in the code executed by the command link action listener. To queue a selection event, you need to know about the rowKey of the row that the command link that you clicked on is located in. To get to this information, you add an f:attribute tag to the command link as shown below <af:column sortProperty="#{bindings.DepartmentsView1.hints.DepartmentId.name}" sortable="false"    headerText="#{bindings.DepartmentsView1.hints.DepartmentId.label}" id="c1">   <af:commandLink text="#{row.DepartmentId}" id="cl1" partialSubmit="true"       actionListener="#{BrowseBean.onCommandItemSelected}">     <f:attribute name="rowKey" value="#{row.rowKey}"/>   </af:commandLink>   ... </af:column> The f:attribute tag references #{row.rowKey} wich in ADF translates to JUCtrlHierNodeBinding.getRowKey(). This information can be used in the command link action listener to compose the RowKeySet you need to queue the selected row. For simplicitly reasons, I created a table "binding" reference to the managed bean that executes the command link action. The managed bean code that is referenced from the af:commandLink actionListener property is shown next: public void onCommandItemSelected(ActionEvent actionEvent) {   //get access to the clicked command link   RichCommandLink comp = (RichCommandLink)actionEvent.getComponent();   //read the added f:attribute value   Key rowKey = (Key) comp.getAttributes().get("rowKey");     //get the current selected RowKeySet from the table   RowKeySet oldSelection = table.getSelectedRowKeys();   //build an empty RowKeySet for the new selection   RowKeySetImpl newSelection = new RowKeySetImpl();     //RowKeySets contain List objects with key objects in them   ArrayList list = new ArrayList();   list.add(rowKey);   newSelection.add(list);     //create the selectionEvent and queue it   SelectionEvent selectionEvent = new SelectionEvent(oldSelection, newSelection, table);   selectionEvent.queue();     //refresh the table   AdfFacesContext.getCurrentInstance().addPartialTarget(table); }

    Read the article

  • How to get selected row index in JSF datatable?

    - by Nitesh Panchal
    I have a databale on index.xhtml <h:dataTable style="border: solid 2px black;" value="#{IndexBean.bookList}" var="item" binding="#{IndexBean.datatableBooks}"> <h:column> <h:commandButton value="Edit" actionListener="#{IndexBean.editBook}"> <f:param name="index" value="#{IndexBean.datatableBooks.rowIndex}"/> </h:commandButton> </h:column> </h:dataTable> My bean: @ManagedBean(name="IndexBean") @ViewScoped public class IndexBean implements Serializable { private HtmlDataTable datatableBooks; public HtmlDataTable getDatatableBooks() { return datatableBooks; } public void setDatatableBooks(HtmlDataTable datatableBooks) { this.datatableBooks = datatableBooks; } public void editBook() throws IOException{ int index = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("index").toString()); System.out.println(index); } } My problem is that I always get the same index in server log even though I click the different edit buttons. Imagine that there is one collection which is supplied to the datatable. I have not shown that in bean. If I change scope from ViewScope to RequestScope it works fine. What can be the problem with @ViewScoped? Thanks in advance :) EDIT: <h:column> <h:commandButton value="Edit" actionListener="#{IndexBean.editBook}" /> </h:column> public void editBook(ActionEvent ev) throws IOException{ if (ev.getSource() != null && ev.getSource() instanceof HtmlDataTable) { HtmlDataTable objHtmlDataTable = (HtmlDataTable) ev.getSource(); System.out.println(objHtmlDataTable.getRowIndex()); } }

    Read the article

  • java TrayIcon using image with transparent background

    - by Jack
    I am using the following code to set a tray icon in Windows and Linux. It works wonderful in Windows and works okay in Linux. In Linux (Ubuntu) I have my panel set to be (somewhat) transparent and when I add a GIF (with a transparent background) the background of the icon shows up all grey and ugly (see image, green diamond "!")....Any ideas on how to make the GIF image I am adding "keep" its transparent background? and the image I am using, if you'd like to test: import java.awt.*; import java.awt.event.*; public class TrayFun { static class ShowMessageListener implements ActionListener { TrayIcon trayIcon; String title; String message; TrayIcon.MessageType messageType; ShowMessageListener( TrayIcon trayIcon, String title, String message, TrayIcon.MessageType messageType) { this.trayIcon = trayIcon; this.title = title; this.message = message; this.messageType = messageType; } public void actionPerformed(ActionEvent e) { trayIcon.displayMessage(title, message, messageType); } } public static void main(String args[]) { Runnable runner = new Runnable() { public void run() { if (SystemTray.isSupported()) { final SystemTray tray = SystemTray.getSystemTray(); Image image = Toolkit.getDefaultToolkit().getImage("green_info.png"); PopupMenu popup = new PopupMenu(); final TrayIcon trayIcon = new TrayIcon(image, "The Tip Text", popup); trayIcon.setImageAutoSize(true); MenuItem item = new MenuItem("Close"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tray.remove(trayIcon); } }); popup.add(item); try { tray.add(trayIcon); } catch (AWTException e) { System.err.println("Can't add to tray"); } } else { System.err.println("Tray unavailable"); } } }; EventQueue.invokeLater(runner); } }

    Read the article

  • Java: does the EDT restart or not when an exception is thrown?

    - by NoozNooz42
    (the example code below is self-contained and runnable, you can try it, it won't crash your system :) Tom Hawtin commented on the question here: http://stackoverflow.com/questions/3018165 that: It's unlikely that the EDT would crash. Unchecked exceptions thrown in EDT dispatch are caught, dumped and the thread goes on. Can someone explain me what is going on here (every time you click on the "throw an unchecked exception" button, a divide by zero is performed, on purpose): import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class CrashEDT extends JFrame { public static void main(String[] args) { final CrashEDT frame = new CrashEDT(); frame.addWindowListener(new WindowAdapter() { public void windowClosing( WindowEvent e) { System.exit(0); } }); final JButton jb = new JButton( "throw an unchecked exception" ); jb.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { System.out.println( "Thread ID:" + Thread.currentThread().getId() ); System.out.println( 0 / Math.abs(0) ); } } ); frame.add( jb ); frame.setSize(300, 150); frame.setVisible(true); } } I get the following message (which is what I'd expect): Exception in thread "AWT-EventQueue-0" java.lang.ArithmeticException: / by zero and to me this is an unchecked exception right? You can see that the thread ID is getting incremented every time you trigger the crash. So is the EDT automatically restarted every time an unchecked exception is thrown or are unchecked exceptions "caught, dumped and the thread goes on" like Tom Hawtin commented? What is going on here?

    Read the article

  • LookAndFeel not changing in Ubuntu

    - by Tom Brito
    Anyone knows Why the laf is not changing in the following code? (running in Ubuntu) import java.awt.Dialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; public class TEST extends JPanel { public TEST() { final LookAndFeelInfo[] lafArray = UIManager.getInstalledLookAndFeels(); String[] names = new String[lafArray.length]; for (int i = 0; i < names.length; i++) { names[i] = lafArray[i].getName(); } final JComboBox cb = new JComboBox(names); cb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { try { int index = cb.getSelectedIndex(); LookAndFeelInfo lafInfo = lafArray[index]; String lafClassName = lafInfo.getClassName(); System.out.println(lafClassName); UIManager.setLookAndFeel(lafClassName); } catch (Exception e) { e.printStackTrace(); } } }); add(cb); } public static void main(String[] args) throws Exception { System.out.println("start"); JDialog dialog = new JDialog(null, Dialog.ModalityType.APPLICATION_MODAL); dialog.setContentPane(new TEST()); dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setVisible(true); dialog.dispose(); System.out.println("end"); } }

    Read the article

  • Why I do not see a static variable in a loop?

    - by Roman
    I have a static method which sets a variable: static String[] playersNames; public static void setParameters(String[] players) { playersNames = players; } Then I have a static block: static { JRadioButton option; ButtonGroup group = new ButtonGroup(); // Wright a short explanation of what the user should do. partnerSelectionPanel.add(new JLabel("Pleas select a partner:")); // Generate radio-buttons corresponding to the options available to the player. // Bellow is the problematic line causing the null pointer exception: for (String playerName: playersNames) { final String pn = playerName; option = new JRadioButton(playerName, false); option.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { partner = pn; } }); partnerSelectionPanel.add(option); group.add(option); } partnerSelectionPanel.add(label); // Add the "Submit" button to the end of the "form". JButton submitButton = new JButton("Submit"); submitButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { partnerSelected(); } }); partnerSelectionPanel.add(submitButton); } Compiler does not complain about anything but when I try to execute the code I get problems. In this place SelectPartnerGUI.setParameters(players); I have: Exception in thread "main" java.lang.ExceptionInitializerError. and it is cause by java.lang.NullpointerException at this place for (String playerName: playersNames). Does my program do not see the palyersNames?

    Read the article

  • I have a problem with a4j:commandButton and a reredering ...

    - by ollie314
    The code below show whiche thing that is failing in my appliaction. It is a quick add information form, fill out the form and submit it add a new entry into a database and synchronize my a databasle.. This is all done with ajax. The first form submission happens correctly but the second one fails to run the desired ActionListener. The second form is posting to the server though but the saveAction isn't invoke. As you will see, I'm a real beginner with this technologies ... If someone see the problem, it will be very helpfull !! <rich:simpleTogglePanel id="quickaddActivitySimpleToogle" switchType="client" opened="false" label="#{lang.activityModule_quickAdd_panelTitle}"> <p><a4j:form id="quickAddForm"> <h:outputLabel for="activityNameInput" value="#{lang.activity_name_dp}" /> <h:inputText id="activityNameInput" value="#{activityController.quickActivityAdd.name}"> </h:inputText> <rich:spacer width="20px" /> <h:inputHidden id="activityInternalNameInput" value="#{activityController.quickActivityAdd.internalName}" /> <rich:spacer width="20px" /> <a4j:commandButton id="activityQuickAddFormSubmitBtn" reRender="activityListTable,quickAddForm" actionListener="#{activityController.saveActivity}" value="#{lang.saveBtn_header}" /> </a4j:form></p></rich:simpleTogglePanel> Thanks in advanced. ollie314

    Read the article

  • JSF2.0: variable list of custom component

    - by rattaman
    Hello Is there any way of using JSF2.0 in connection with variable lists of components? For example, lets say I have list o people that I would like to edit. They are presented on the page as list of components PersonEditor, which allow changing person data. Each editor is associated with single Person element. In order for this to work I need to perform following steps: On initial request: Get list of people For each person create PersonEditor and associate it with Person object. Fill editor's data. On user action: When user changes values and presses Save, data is processed by backing bean. I can either fill editor with data from list of people or bind it to the backing bean, but not at the same time, so I am stuck. I tried people.xhtml <ui:render value="#{bean.people}" var="person"> <example:personEditor person="#{person}"/> </ui:render> where personEditor.xhtml: a) proper association with person object, but no connection to backing bean <h:form> <h:outputText value="#{cc.attr.person.name}"/> <h:commandButton name="Save" actionListener="editorBean.save"> <f:ajax execute="@form" render="@form"/> </h:commandButton> </h:form> b) no association with person object, but there is connection to backing bean - there is no way to pass that person to the backing bean <h:form> <h:outputText value="#{editorBean.name}"/> <h:commandButton name="Save" actionListener="editorBean.save"> <f:ajax execute="@form" render="@form"/> </h:commandButton> </h:form> If I had each editor on separate page, I could pass the person id as url parameter (either using f:param or f:attribute) and initialize it accordingly. Is there any solution to this problem?

    Read the article

  • java , eclipse jar problem

    - by Raxvan
    Hello , i'm kind of new to java. I use eclipse and i imported some jar files with some classes by going to properties - Add External Jars; The problem is that when i try to use a class from the jar i get the following exception: Exception in thread "main" java.lang.NoClassDefFoundError: nextapp/echo2/app/event/ActionListener at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) at Program.main(Program.java:12) Caused by: java.lang.ClassNotFoundException: nextapp.echo2.app.event.ActionListener at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 13 more The class is supposed to create a window, i guess that the jar has to import somehow other stuff or something like that, How can i fix this? PS. Sorry for the bad code , i don't know tags here. thansk, Raxvan

    Read the article

  • Reading lines of data from text files using java

    - by razshan
    I have a text file with x amount of lines. each line holds a integer number. When the user clicks a button, an action is performed via actionlistener where it should list all the values as displayed on the text file. However, right now I have linenum set to 10 implying I already told the code that just work with 10 lines of the text file. So, if my text file has only 3 rows/lines of data...it will list those lines and for rest of the other 7 lines, it will spit out "null". I recall there is a way to use ellipsis to let the program know that you don't know the exact value but at the end it calculates it based on the given information. Where my given information will the number of lines with numbers(data). Below is part of the code. private class thehandler implements ActionListener{ public void actionPerformed(ActionEvent event){ BufferedReader inputFile=null; try { FileReader freader =new FileReader("Data.txt"); inputFile = new BufferedReader(freader); String MAP = ""; int linenum=10; while(linenum > 0) { linenum=linenum-1; MAP = inputFile.readLine();//read the next line until the specfic line is found System.out.println(MAP); } } catch( Exception y ) { y.printStackTrace(); } }}

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >