Jcheckbox and actionlistener

  if (bathroom.isSelected()){ bathroom is a jcheckbox, why doesnt that work.
if (bathroom.isSelected()){
g1.remove(namelabel);
g1.remove(namelabel);
g1.remove(bathroom);
g1.remove(office);
g1.remove(nurse);
g1.remove(other);
g1.setBackground(Color.red);
p2.add(returnbutton);
namelabel.setText(namearray[0]+" is currently using the pass the time left was ");
g1.add(namelabel);
g1.add(time);
f1.dispose();
f1.show();
Edited by: HermTheWorm on Oct 21, 2007 7:28 PM

Ok! I misinterpreted your problem. I thought if you want to select or deselect a check box it will execute a command. Am I right?
So you already have a jbutton with an actionListener and once click it will check what check box is selected and it will execute a certain command.
e.g.
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == myButton) {
        if(myCheckBox.isSelected()) {
            // your code
}just follow the example and if it doesn't work please post your Short, Self Contained, Compilable Example or SSCCE so that we can determine the problem.

Similar Messages

  • Commandbutton onclick and actionlistener happen at same time

    I started a thread previously with a similar issue, but the title of that thread really doesn't describe the current problem. Sorry for double posting, but I would delete that thread if I could.
    I have a command button as:
    <h:commandButton id="saveCloseFoil" type="submit"
    onclick="javascript:saveText();"
    action="#{Item.saveOptionAction}"
    value="#{propertiesBundle.saveCloseSubmitLabel}"
    actionListener="#{Item.setFoilTextToBean}" />
    The saveText() javascript function copies the text from a text editor to a field defined as:
    <h:inputHidden id="hiddenTextField" value="" />
    The actionlistener should take the value from the hidden field, and put it in the backing bean. The Action then saves that value in its correct place in the database.
    The problem is that the onclick and actionlistener are firing at the exact same time(i am verifying this by using the firefox javascript debugger breakpoints for the javascript and JDeveloper breakpoints for the actionlistener. Both breakpoints stop at the same time.)
    The strange thing is that in another place in our applicate we have an almost identical button:
    <h:commandButton tabindex="3" type="submit" id="submit"
    onclick="javascript:setBrowserSettings();"
    action="#{Login.loginAction}"
    actionListener="#{Login.setBrowserOSSettings}"
    value="#{propertiesBundle.loginLabel}">
    </h:commandButton>
    in which the onclick is run first, then the actionlistener, then the action. I verified this using the exact same method as with the button I am working on now.

    I use both IE6 and Firefox. I mentioned FF because I am unable to debug the problem as accurately in IE6 due to the very limited javascript debugging available for it.
    I also have tried the return true; in the onclick, and tried it again, with no change.

  • Keep focus and actionlistener

    I open as a popup a custom JPanel but
    I want to keep focus and actionlistener on it
    while it is opened.
    is there a way?
    thanks for any clue

    I tried removing all the pattern validations on the field and added this below code in the validate event of the text field and it works..
    var strCode;
    var f = /^([A-Z]{2}[1-9]{5}[A-Z])$/;
    if(this.rawValue != null && String(this.rawValue) != "") {
                        strCode = String(this.rawValue);
                        if (f.test(strCode) == false) {
                                            xfa.host.messageBox("Invalid pattern!");
                                            xfa.host.resetData();
                                            xfa.host.setFocus(this);
    xfa.host.setFocus(this);

  • UICommand action and actionListener - invoke in different phases

    Hi,
    I am trying to get the action and actionListener methods of a command button invoked in different phases. When the button is pressed I would like the actionListener to be invoked immediately, but the action method only in the "invoke applications phase", unless the form validation failed.
    Setting immediate to "true" doesn't work, as I can't get the action method to be queued for later processing. I also can't make them both actionListeners as the action method controls navigation.
    Any way round this?
    Thanks!

    Action = Executed in the invoke application phase. Runs a method in a bean that returns a String object. The String is used by the navigation system to determine which page to render next. The rules for this are set up in the faces-config.xml file, in the navigation-rule sections.
    ActionListener = Executed in the invoke application phase. Is triggered when the action event occurs for the component the listener is attached too. This listener can perform miscellaneous actions required when the button is clicked, but does not return a String that affects the navigation.
    What order do they get called? Try this out!
    http://www.jsftutorials.net/faces-config/phaseTracker.html
    It'll help you understand the JSF lifecycle. Which is VERY important, especially when those weird errors start occurring (or JSF seems to be ignoring your commands).
    CowKing

  • Regarding JCheckBox and JRadioButton

    hi,
    I have a screen which contains JCheckBox and JRadioButton component on it. when focus is on checkbox i wanted the background color to be green. But once the focus is lost, the background color should be changed to normal.
    Is it possible? Please help me out.. I need it very urgently.
    regards,
    Deepa Raghuraman

    Hello!
    If you mean keyboard focus:
    yourCheckBox.addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent e) {
                 // change color to green
            public void focusLost(FocusEvent e) {
                 // change color to 'normal'
    });I hope it helps you.
    regards
    Feri

  • ItemListemer and ActionListener...and others...how can they live together?

    Hi,
    I want to have a couple of DropDown Menus, some Buttons and some Checkboxes in the same class....How can I do that knowing that my class needs to implement ItemListener and ActionListener ?
    I've tried something like:
    "public class extends Applet implements ItemListener implements ActionListener"
    but not surprisingly it doesn't work....
    and what if on top of that I want a MouseListener, a WindowListener or God knows what else...?
    Thanks in advance for your help...
    Tom

    You need to read the basics about Swing events.
    For starters, you do not implement listeners in your Applet class. Instead, you add new listeners to specific components that you want to listen on. For example, if you need to perform certain actions when a JComboBox's selection changes, you would do something like:
    my_combo.addActionListener(  new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("selection changed to: " + my_combo.getSelectedItem());
    });And for buttons:
    my_button.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("You clicked " + ((JButton) e.getSource()).getText() " button);
    }MoustListener and other listeners can be similarily added. See JDK Documentation or Tutorials

  • Af:commandMenuItem action and actionListener are not executing

    Hello all!
    I use JDeveloper Studio Edition Version 11.1.1.2.0. Here's the problem. I have a popup menu like this
    <af:popup id="someMenu" animate="default">
    <af:menu id="pt_m1">
    <af:forEach var="item" items="#{ContextMenuHelperBean.availableUserRoles}">
    <af:commandMenuItem text="#{item.roleName}"
    action="#{ContextMenuHelperBean.changeUserRole_Action}"
    actionListener="#{ContextMenuHelperBean.changeUserRole_ActionListener}"
    immediate="true"
    partialSubmit="false"
    id="pt_cmi1" rendered="true">
    <f:attribute name="userRole" value="#{item}"/>
    </af:commandMenuItem>
    </af:forEach>
    </af:menu>
    </af:popup>
    The problem is that action and actionListener are not executing, when the menu item is selected (but the page is reloaded with no changes). ContextMenuHelperBean has a "session" scope set in adfc-config.xml. What can be wrong with this?

    Now I've encountered a new kind of error. I create a menu in a managed bean like this:
    In JSPX
    <f:view beforePhase="#{RolesMenuSupportBean.createMenus}">
    <af:popup id="cxtMenu" animate="default">
                            <af:menu id="pt_m1"
                                     binding="#{RolesMenuSupportBean.rolesMenu}">
                            </af:menu>
                          </af:popup>In com\cs\webb2\view\utils\menu\RolesMenuSupport.java
        public void createMenus(PhaseEvent phaseEvent) {                       
            List<IUserRole> rolesList = getAvailableUserRoles();
            for (IUserRole role: rolesList) {           
                Boolean hasItem = false;           
                for (Iterator iter = rolesMenu.getChildren().iterator(); iter.hasNext(); ) {
                    RichCommandMenuItem item = (RichCommandMenuItem) iter.next();
                    if (!hasItem)
                        hasItem = item.getText().equalsIgnoreCase(role.getRoleName());
                if (!hasItem) {
                    RichCommandMenuItem newItem = new RichCommandMenuItem();                                                       
                    newItem.getAttributes().put("userRole", role);
                    newItem.setText(role.getRoleName());
                    newItem.setId(ITEM_ID);               
                    newItem.setActionExpression(getActionExpression("#{RolesMenuSupportBean.changeUserRole_Action}"));                           
                    newItem.addActionListener(getExpressionActionListener("#{RolesMenuSupportBean.changeUserRole_ActionListener}"));                               
                    rolesMenu.getChildren().add(newItem);  
        } The menu is created successfully, but when I click on any item, I get an exception
    <b>javax.servlet.ServletException: Method not found: com.cs.webb2.view.utils.menu.RolesMenuSupport@d4702.changeUserRole_Action(void)</b>
    But of course I have such a method in my com.cs.webb2.view.utils.menu.RolesMenuSupport:
    In com\cs\webb2\view\utils\menu\RolesMenuSupport.java
        public String changeUserRole_Action()
            System.out.println("Action!");
            // no code yet
            return "adfMenu_Main";
        }And there <b>is</b> a managed bean named RolesMenuSupportBean, which is associated with class com.cs.webb2.view.utils.menu.RolesMenuSupport.
    Can anyone tell me, what can be wrong?

  • Learning SQL Query with JCheckBox and JButton

    Hello,
    I am learning how to access a very simple Access table. I am able to connect to the database and return a simple query. As I make it more complicated is where I have confused myself. The program is suppose to allow the user to pick any field they want to query using JCheckBox. After they have checked the fields off, the run query button is hit and outputs the results in a JOPtion Pane with a JTable. I am trying to do a test run and I can't make the query at least output something. If I can get any clues to the right direction would be appreciated. Thanks.
    package mypackage25;
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class QueryAddressBook extends JFrame
        private JLabel selectQueryLabel;
        private JCheckBox firstName, lastName,
                       telephone, addressI, addressII, city,
                       state, zip;
        private JPanel selectQueryPanel, checkBoxPanel, executePanel;
        private JButton runQueryButton, clearSQLButton;
        private Connection connection;
        private Statement statement;
        private ResultSet resultSet;
        public QueryAddressBook()
          super("Query an Address Book");
          //Driver and Connection
          try
          //Driver for MicrosoftAccess
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          //Inform the user that the Driver was loaded successfully
          System.out.println("Driver Loaded");
          //Connect to specific database(i.e. MyAddress3) in Access
          Connection connection=DriverManager.getConnection("jdbc:odbc:MyAddress3");
          //Inform User
          System.out.println("Database connected");
          }//end try
          catch(ClassNotFoundException cnfe)
            cnfe.printStackTrace();
          }//end catch
          catch(SQLException sqle)
            sqle.printStackTrace();
          }//end catch
          //get content pane and set its layout
          Container container=getContentPane();
          container.setLayout(new BorderLayout());
          //GUI Components
          selectQueryLabel=new JLabel("Select Fields to be Queried");
          firstName=new JCheckBox("First Name");
          lastName=new JCheckBox("Last Name");
          telephone=new JCheckBox("Telephone");
          addressI=new JCheckBox("Address I");
          addressII=new JCheckBox("Address II");
          city=new JCheckBox("City");
          state=new JCheckBox("State");
          zip=new JCheckBox("Zipcode");
          //register listeners for JCheckBoxes
          CheckBoxHandler handler=new CheckBoxHandler();
          firstName.addItemListener(handler);
          lastName.addItemListener(handler);
          telephone.addItemListener(handler);
          addressI.addItemListener(handler);
          addressII.addItemListener(handler);
          city.addItemListener(handler);
          state.addItemListener(handler);
          zip.addItemListener(handler);
          //set up selectQueryPanel
          selectQueryPanel=new JPanel();
          selectQueryPanel.setLayout(new FlowLayout());
          selectQueryPanel.add(selectQueryLabel);
          //set up CheckBox Panel
          checkBoxPanel=new JPanel();
          checkBoxPanel.setLayout(new FlowLayout());
          checkBoxPanel.add(firstName);
          checkBoxPanel.add(lastName);
          checkBoxPanel.add(telephone);
          checkBoxPanel.add(addressI);
          checkBoxPanel.add(addressII);
          checkBoxPanel.add(city);
          checkBoxPanel.add(state);
          checkBoxPanel.add(zip);
          //set up execute panel
          executePanel=new JPanel();
          executePanel.setLayout(new FlowLayout());
          //set up buttons
          runQueryButton=new JButton("Run Query");
          clearSQLButton=new JButton("Clear SQL");
          runQueryButton.addActionListener
            new ActionListener()
              public void actionPerformed(ActionEvent event)
                if(event.getSource().equals(runQueryButton))
                  runSQLQuery();
          executePanel.add(runQueryButton);
          executePanel.add(clearSQLButton);
          container.add(selectQueryPanel, BorderLayout.NORTH);
          container.add(checkBoxPanel, BorderLayout.CENTER);
          container.add(executePanel, BorderLayout.SOUTH);
          setSize(800,150);
          setVisible(true);
        public static void main(String args[])
          QueryAddressBook dwgui=new QueryAddressBook();
          dwgui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }//end main
        //private inner class for ItemListener event handling
        private class CheckBoxHandler implements ItemListener
          public void itemStateChanged(ItemEvent event)
          }//end method itemStateChanged
        }//end private inner class CheckBoxHandler
        private void runSQLQuery()
          String output="";
          try
            statement=connection.createStatement();
            resultSet=statement.executeQuery("select firstName from address");
            while(resultSet.next())
              output+=resultSet.getString(1)+"\n";
            JOptionPane.showMessageDialog(null,output);
            System.out.println(output);
          }//end try
          catch(SQLException sqle)
            sqle.printStackTrace();
          }//end catch
        }//end runSQLQuery
    }//end class

    At present your query string is
    "Select firstName from Address"
    Instead of using the above hardcoded string, try to build the
    query String using logic that checks which check boxes are selected
    by the user.
    Example..
    String query = "SELECT ";
    if (firstName.isSelected()) {
    query = query + " firstName";
    Be sure, you add the comma properly between two fields :-)

  • Having trouble with JCheckBox and JTree

    I am trying to render the JTree to display JCheckBox's instead of just ordinary JLabels.
    It's fine, compiles, and when you view it it looks normal, until you try to check one.
    You can't check it at all.
    What am i doing wrong with this?
    Thanks

    OK, here it is...
    public class EmotiTreeCellRenderer extends DefaultTreeCellRenderer {
         protected JCheckBox label;
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
              if ( value instanceof DefaultMutableTreeNode ) {
                   label = new JCheckBox();
                   label.setOpaque( false );
                   if ( selected && hasFocus ) {
                        label.setForeground( Color.blue );
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
                   Object userObject = node.getUserObject();
                   if ( userObject instanceof Emoticon ) {
                        Emoticon emoticon = (Emoticon)userObject;
                        String icon = emoticon.getIconKeys();
                        try {
                             label.setText( "<html><body><img src=\"" + new File( emoticon.getRealPathToEmoticon() ).toURL().toString() + "\" alt=\"" + parseAlt( icon ) + "\"> " + parseAlt( icon ) + "</body></html>" );
                        } catch ( MalformedURLException mfe ) {
                             label.setText( "<html><body>" + parseAlt( icon ) + "</body></html>" );
                        return label;
                   } else if ( userObject instanceof EmotiPack ) {
                        EmotiPack pack = (EmotiPack)userObject;
                        label.setText( pack.getName() );
                        return label;
              return super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus );
         protected String parseAlt(String html) {
              return html.replace( "<", "<" ).replace( ">", ">" ).replace( "\"", "&#34;" );
    }

  • H:commandButton and actionListener

    Hi all,
    I'm trying to add an ActionListener to a commandButton, but there is something wrong. This is my (very simple) jsp page:
    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
         <title>My JSF 'index.jsp' starting page</title>
    </head>
    <body>
         <f:view>
              <h:form>
              hello world
              <br>
              <h:commandButton value="click me" action="none" >
                   <f:actionListener type="it.hostingjava.MyListener" />
              </h:commandButton>
              </h:form>
              <br>          
         </f:view>
    </body>
    </html>And this is the (basic) MyListener:
    package it.hostingjava;
    import javax.faces.event.AbortProcessingException;
    import javax.faces.event.ActionEvent;
    import javax.faces.event.ActionListener;
    public class MyListener implements ActionListener {
         public void processAction(ActionEvent arg0) throws AbortProcessingException {
              System.out.println("MyListener.processAction");
    }And, last but not least this is the rendered HTML:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
         <title>My JSF 'index.jsp' starting page</title>
    </head>
    <body>
              <form id="_idJsp0" name="_idJsp0" method="post" action="/myjsf/index.faces" enctype="application/x-www-form-urlencoded">
              hello world
              <br>
              <input id="_idJsp0:_idJsp1" name="_idJsp0:_idJsp1" type="submit" value="click me" onclick="clear__5FidJsp0();" />
              <input type="hidden" name="_idJsp0_SUBMIT" value="1" /><input type="hidden" name="jsf_sequence" value="11" /><input type="hidden" name="_idJsp0:_link_hidden_" /><script type="text/javascript"><!--
    function clear__5FidJsp0() {
      var f = document.forms['_idJsp0'];
      f.elements['_idJsp0:_link_hidden_'].value='';
      f.target='';
    clear__5FidJsp0();
    //--></script></form>
              <br>          
    <!-- MYFACES JAVASCRIPT -->
    </body>
    </html>So, when i click the button in output window is printed (correctly) "MyListener.processAction" but the same behaviour is obtained when i refresh the page. Is there a way to make that the refresh doesn't fire the actionListener ?
    I'm using MyFaces implementation on Tomcat 5.5.17. I'm using the latest release available. I have the same problem on Firefox and Internet Explorer.

    I think the problem is that you have an action and an actionListener. Put only one of them.

  • Observable and ActionListener.. help

    Is there anyway to pause update method and continue after I click the �Add Student� button?
    The update method is called automatically when my observable object is changed, so I can�t display previous observable information via the button�s ActionListener.
    Anyway to do that?
    Thanks
    import java.util.Observable;
    import java.util.Observer;
    import java.awt.event.*; //package for event handeler
    import java.awt.*;
    import javax.swing.*;
    public class Lab5Frame extends JFrame implements Observer {     
         private JLabel label;
         private String name;     
         public TestFrame(Observable observable) {
              System.out.println("Windows created.");
              observable.addObserver(this);
         public Lab5Frame(String title) throws HeadlessException {
              super(title);          
              Container c = getContentPane();
              JPanel panel = new JPanel();
              label = new JLabel(name);
              panel.add(this.label);
              JButton button = new JButton("Add Studnet");
              button.addActionListener(new ListName());           
              c.add(button, BorderLayout.NORTH);
              c.add(panel, BorderLayout.CENTER);
              //*** window adapter
              addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent we){
                        System.exit(0);
         private class ListName implements ActionListener{
              public void actionPerformed(ActionEvent event){                    
                   //what should I write here to performe the updated information
    vai the update method?
         //oberver update     
         public void update(Observable arg0, Object arg1) {     
              System.out.println("LogConsole: " + arg1);
         }

    Is there anyway to pause update method and continue after I click the �Add Student� button?
    The update method is called automatically when my observable object is changed, so I can�t display previous observable information via the button�s ActionListener.
    Anyway to do that?
    Thanks
    import java.util.Observable;
    import java.util.Observer;
    import java.awt.event.*; //package for event handeler
    import java.awt.*;
    import javax.swing.*;
    public class Lab5Frame extends JFrame implements Observer {     
         private JLabel label;
         private String name;     
         public TestFrame(Observable observable) {
              System.out.println("Windows created.");
              observable.addObserver(this);
         public Lab5Frame(String title) throws HeadlessException {
              super(title);          
              Container c = getContentPane();
              JPanel panel = new JPanel();
              label = new JLabel(name);
              panel.add(this.label);
              JButton button = new JButton("Add Studnet");
              button.addActionListener(new ListName());           
              c.add(button, BorderLayout.NORTH);
              c.add(panel, BorderLayout.CENTER);
              //*** window adapter
              addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent we){
                        System.exit(0);
         private class ListName implements ActionListener{
              public void actionPerformed(ActionEvent event){                    
                   //what should I write here to performe the updated information
    vai the update method?
         //oberver update     
         public void update(Observable arg0, Object arg1) {     
              System.out.println("LogConsole: " + arg1);
         }

  • Buttons and actionlistener help.

    the following code has 2 buttons, how would i use a button to get me differnt graphics but inside the same window,
    say i clicked next the graphics would be slightly altered which I will do but it wont open a new window it will be in the same window, but different shapes.
    I am having trouble with action listeners and really need help in how they work iv read up but dont understand, and how this would be implemented for this.
    much help would be appreciated.
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.RenderingHints;
    import java.awt.Stroke;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class square extends JPanel
        public square()
            setPreferredSize(new Dimension(800, 700));
            int eb = 80;
            setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
            setLayout(new BorderLayout(5, 10));
           JPanel buttonPanel = createButtonPanel();
             add(buttonPanel, BorderLayout.SOUTH);
        private JPanel createButtonPanel()
            JPanel bp = new JPanel();
            bp.setOpaque(false);
                   JButton btn2 = new JButton("<-  Back Step ");
                    JButton btn = new JButton("Next Step   ->");
                    bp.add(btn2);
                    bp.add(btn);
            return bp;
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            Rectangle2D rect = new Rectangle2D.Double(250, 150, 100, 100);
            Rectangle2D     rect2 = new Rectangle2D.Double(400, 150, 100, 100);
             Rectangle2D     rect3 = new Rectangle2D.Double(550, 150, 100, 100);
             Rectangle2D     rect4 = new Rectangle2D.Double(250, 300, 100, 100);
             Rectangle2D     rect5 = new Rectangle2D.Double(400, 300, 100, 100);
             Rectangle2D     rect6 = new Rectangle2D.Double(550, 300, 100, 100);
             Rectangle2D     rect7 = new Rectangle2D.Double(250, 450, 100, 100);
             Rectangle2D     rect8 = new Rectangle2D.Double(400, 450, 100, 100);
             Rectangle2D     rect9 = new Rectangle2D.Double(550, 450, 100, 100);
             g.drawString("b0,0", 300, 130);
            g.drawString("b1,0", 300, 110);
             g.drawString("b2,0", 300, 90);
                 g.drawString("b0,1", 450, 110);
            g.drawString("b1,1", 450, 90);
            g.drawString("b2,1", 450, 70);
                 g.drawString("b0,2", 600, 90);
            g.drawString("b1,2", 600, 70);
            g.drawString("b2,2", 600, 50);
             g.drawString("a0,0", 200, 200);
            g.drawString("a1,0", 150, 200);
             g.drawString("a2,0", 100, 200);
                 g.drawString("a0,1", 150, 350);
            g.drawString("a1,1", 100, 350);
            g.drawString("a2,1", 50, 350);
                   g.drawString("a0,2", 100, 500);
            g.drawString("a1,2", 50, 500);
            g.drawString("a2,2", 15, 500);
            g2.setPaint(Color.black);
            g2.draw(rect);
            g2.draw(rect);
              g2.draw(rect2);
             g2.draw(rect3);
              g2.draw(rect4);
             g2.draw(rect5);
              g2.draw(rect6);
             g2.draw(rect7);
              g2.draw(rect8);
              g2.draw(rect9);
            Stroke oldStroke = g2.getStroke();
            g2.setStroke(new BasicStroke(5));
            g2.setStroke(oldStroke);
        private static void createAndShowUI()
            JFrame frame = new JFrame("Matrix Multiplication - Step by Step ");
            frame.getContentPane().add(new square());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

    ok I had a look over it, I got this
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.RenderingHints;
    import java.awt.Stroke;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class square extends JPanel implements ActionListener
        public square()
            setPreferredSize(new Dimension(800, 700));
            int eb = 80;
            setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
            setLayout(new BorderLayout(5, 10));
           JPanel buttonPanel = createButtonPanel();
             add(buttonPanel, BorderLayout.SOUTH);
      public void actionPerformed(ActionEvent e) {
            System.out.println("hello");
        private JPanel createButtonPanel()
            JPanel bp = new JPanel();
            bp.setOpaque(false);
                   JButton btn2 = new JButton("<-  Back Step ");
                    JButton btn = new JButton("Next Step   ->");
                    bp.add(btn2);
                    bp.add(btn);
             btn.addActionListener(this);
            return bp;
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            Rectangle2D rect = new Rectangle2D.Double(250, 150, 100, 100);
            Rectangle2D     rect2 = new Rectangle2D.Double(400, 150, 100, 100);
             Rectangle2D     rect3 = new Rectangle2D.Double(550, 150, 100, 100);
             Rectangle2D     rect4 = new Rectangle2D.Double(250, 300, 100, 100);
             Rectangle2D     rect5 = new Rectangle2D.Double(400, 300, 100, 100);
             Rectangle2D     rect6 = new Rectangle2D.Double(550, 300, 100, 100);
             Rectangle2D     rect7 = new Rectangle2D.Double(250, 450, 100, 100);
             Rectangle2D     rect8 = new Rectangle2D.Double(400, 450, 100, 100);
             Rectangle2D     rect9 = new Rectangle2D.Double(550, 450, 100, 100);
             g.drawString("b0,0", 300, 130);
            g.drawString("b1,0", 300, 110);
             g.drawString("b2,0", 300, 90);
                 g.drawString("b0,1", 450, 110);
            g.drawString("b1,1", 450, 90);
            g.drawString("b2,1", 450, 70);
                 g.drawString("b0,2", 600, 90);
            g.drawString("b1,2", 600, 70);
            g.drawString("b2,2", 600, 50);
             g.drawString("a0,0", 200, 200);
            g.drawString("a1,0", 150, 200);
             g.drawString("a2,0", 100, 200);
                 g.drawString("a0,1", 150, 350);
            g.drawString("a1,1", 100, 350);
            g.drawString("a2,1", 50, 350);
                   g.drawString("a0,2", 100, 500);
            g.drawString("a1,2", 50, 500);
            g.drawString("a2,2", 15, 500);
            g2.setPaint(Color.black);
            g2.draw(rect);
            g2.draw(rect);
              g2.draw(rect2);
             g2.draw(rect3);
              g2.draw(rect4);
             g2.draw(rect5);
              g2.draw(rect6);
             g2.draw(rect7);
              g2.draw(rect8);
              g2.draw(rect9);
            Stroke oldStroke = g2.getStroke();
            g2.setStroke(new BasicStroke(5));
            g2.setStroke(oldStroke);
        private static void createAndShowUI()
            JFrame frame = new JFrame("Matrix Multiplication - Step by Step ");
            frame.getContentPane().add(new square());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }it produces hello once I click the button, but how would I produce the same frame once the button is clicked, not a new frame, the same one iv got with slight adjustments inside it..which i will do.

  • How to disable a JCheckBox and leave the text the original color?

    When a JCheckBox is disabled, its text gets dim (gray). I need to just dim the checkbox but leave the text the original color.
    I can't find the code where the text color changes when the box is disabled...
    (I have found the code that draws the square and the box at: com.sun.java.swing.plaf.windows.WindowsIconFactory .)
    Any ideas?

    Try this checkbox, i think you could customize to achieve exact behaviour:
    import java.awt.Graphics;
    import javax.swing.JCheckBox;
    import javax.swing.JToggleButton;
    public class KCheckBox extends JCheckBox
        private boolean clickable;
        private boolean enabled2;
        public KCheckBox()
            super();
            init();
         * @param text
        public KCheckBox( String text )
            super( text );
            init();
        private void init()
            setModel( new MyButtonModel() );
            this.clickable = true;
            this.enabled2 = true;
        public void paint( Graphics g )
            // store existing state
            boolean e = ((MyButtonModel)getModel()).isEnabled();
            // if !enabled - set not enabled
            // otherwise - set enabled
            ((MyButtonModel)getModel()).setEnabledNoFire( this.enabled2 );
            super.paint( g );
            // restore previous state
            ((MyButtonModel)getModel()).setEnabledNoFire(e);
        public void setClickable(boolean clickable)
            this.clickable = clickable;
            super.setEnabled(clickable && this.enabled2);
        public boolean isClickable()
            return this.clickable;
        public void setEnabled(boolean enabled)
            this.enabled2 = enabled;
            super.setEnabled(enabled && this.clickable);
        public boolean isEnabled()
            return this.enabled2;
        private class MyButtonModel extends JToggleButton.ToggleButtonModel
            public void setEnabledNoFire( boolean b )
                if (b) {
                    stateMask |= ENABLED;
                } else {
                    stateMask &= ~ENABLED;
    }Edited by: unvadim on Sep 5, 2008 4:41 PM

  • JCheckBox and identation of sub-elements

    I wonder how I can layout a list of checkboxes with sub elements, like a list of checkboxes again (see my ASCII art figure). The sub elements should be indented like the label of the checkbox above.
    I can't use a static value for this indentation, since the size of the icon depends on the L'n'F. On the other side I don't want to loose the connection between the label and the checkbox (means I want to select the checkbox by clicking on the label).
    Any suggestions?
    o First choice
       o Sub choice 1
       o Sub choice 2
    o Second choiceRegards,
    Leif

    Joerg22 wrote:
    leif.bladt wrote:
    The arrangement is indeed fixed. But as I create the checkbox with the following code, I don't know, where the icon ends and where the label starts.
    new JCheckBox("Description")
    In your example your don't use an icon at all. But I assume the icons vary with each checkbox, do they?
    @Kevin
    How do you apply horizontal glue when the components are added in BoxLayout.Y_AXIS? Or do you mean to add a panel for each checkbox?I meant to add a Panel for each JCheckBox. But upon further thought, the Box.createGlue() is an unnecessary step. Just use the X alignment discussed in the BoxLayout [features |http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html#features] section of the tutorial.

  • Difference between action and actionListener

    I would like to tell me which is the difference between an action and an actionListener in the following example:
    <h:form style="text-align:center">
    <h:commandButton image="mountrushmore.jpg"
    actionListener="#{rushmore.listen}"
    action="#{rushmore.act}"/>     
    </h:form>Which method of the rushmore bean is invoked first the listen() or the act()? Based on the JSF lifecycle the action events are invoked in the Invoke Application Phase correct?So first we have the process of validation and then the action is invoked right?And then the listener?
    Thanks in advance.

    Action = Executed in the invoke application phase. Runs a method in a bean that returns a String object. The String is used by the navigation system to determine which page to render next. The rules for this are set up in the faces-config.xml file, in the navigation-rule sections.
    ActionListener = Executed in the invoke application phase. Is triggered when the action event occurs for the component the listener is attached too. This listener can perform miscellaneous actions required when the button is clicked, but does not return a String that affects the navigation.
    What order do they get called? Try this out!
    http://www.jsftutorials.net/faces-config/phaseTracker.html
    It'll help you understand the JSF lifecycle. Which is VERY important, especially when those weird errors start occurring (or JSF seems to be ignoring your commands).
    CowKing

Maybe you are looking for

  • Using VO Attribute in destination URI of Item Style LINK in OAF Personalization

    Extended the VO in iReceivables to have a Transaction link (external URL) as additional view attribute 'InvoiceUri' (i.e. each TRX will have a unique URL from 3rd party) Now trying to add a LINK type Item in the same and proving the VO Attribute as D

  • Is there any way to email photos from my 2g without compressing the file?

    My wife's 2g stopped being able to sync to her PC some time ago.  She emails photos to get them on her computer. The photos seem to loose resolution in emailing.  Is there a way to get these photos without the degredation?  All the wifi apps require

  • Display in editable alv grid.

    Hi, This is my source code of uploading excel into sap and displaying the list.Please give the code for displaying the excel  data in editable alv. <<The code came from [here|https://wiki.sdn.sap.com/wiki/display/Snippets/ABAP-UploaddatafromExceltoSa

  • Trying to use the fillInStackTrace method

    Hello, The following code generates an error when I try to compile it.   private void divide() throws Exception     try       double a = 50/0;     catch (Exception error)       throw error.fillInStackTrace(); And it's called from:   void jButton1_act

  • Creating a FM Book and then Flash RoboHelp starting from PDF

    At our business we have an SOP (Standard Operating Procedures). There are about 20 chapters. We create them in Publisher and then convert to PDF and then post on our internal Wiki for all to see. This works for us. However, one of the chapters is 49