SetLocationRelativeTo(null) not working

I'm trying to use setLocationRelativeTo(null) to center a JFrame however it's not working?
I'm using it elsewhere to do the same and it works, but this doesn't and the only difference is that it's being run in a separate thread. Why isn't it working properly?
I say properly, because it's not displaying it in the top left, but is to the bottom right of the center.
Please help
Thanks

agehoops wrote:
... it's not displaying it in the top left, but is to the bottom right of the center.In other words, if you shrink the size of the frame to some extent by dragging in the lower right corner (possibly by a lot) then the frame will be centered, albeit sized too small?
It sounds as if the frame is getting modified after setLocationRelativeTo(null) is getting called. You mention that this is getting called on a thread? Why? And if really needed, how are you doing it? It's possible that the frame is being modified in another thread before it's shown.
Think of it this way: the frame is a certain size (really small), you then tell it to center itself (which it does properly while it still hasn't been shown yet), and then the frame gets bigger by adding components to it. What will happen is that the upper-left corner will remain in place, and the frame will grow out down and to the right.
Of course, this is all just a guess since you didn't provide an SSCCE.

Similar Messages

  • 'is null' not working in dynamic sql and SQl Query component (OBPM 10gr3)

    I'm using a SQL Query component with sql like this
    'select col1, col2 from table where col3 is null'
    for some reason this does not work.
    Has anybody faced this issue? Is there a known bug with handling nulls
    Thanks

    plz post which DB version u r working with
    dont use paramters in Procedure with : sign
    Write simply the name of the Paramters like p_userid etc etc
    this might help u as well
    http://baigsorcl.blogspot.com/2010/02/get-rid-of-addtional-quotes-with-quote.html

  • SET NULL not working in SQL*Plus

    DB Version: 10.2.0.4
    Question1.
    Won't SET NULL work with PL/SQL block?
    Question2.
    Why is <<>> appearing in several lines (one character per line) as shown below? Sorry about the "jive-quote" thing below, got that after i added code tags.
    SQL > show lines
    linesize 80
    SQL > show pages
    pagesize 14
    SQL > set null <<>>
    SQL > select null from dual;
    N
    <
    <
    >
    >
    SQL > set serveroutput on
    SQL > declare
      2  v_Val VARCHAR2(100) :='COCOJUMBO';
      3  BEGIN
      4  SELECT null INTO v_val from dual ;
      5  DBMS_output.put_line(v_val);
      6  EXCEPTION
      7  WHEN NO_DATA_FOUND THEN
      8  dbms_output.put_line('Exception:'||SQLERRM);
      9  END;
    10  /
    PL/SQL procedure successfully completed.
    SQL >

    user872043 wrote:
    DB Version: 10.2.0.4
    Question1.
    Won't SET NULL work with PL/SQL block?No. SET NULL is a SQL*Plus command, not a PL/SQL command.
    Question2.
    Why is <<>> appearing in several lines (one character per line) as shown below? Sorry about the "jive-quote" thing below, got that after i added code tags.That's due to default formatting. For example:
    SQL> SET NULL <<>>
    SQL> SELECT NULL FROM DUAL;
    N
    <
    <
    >
    >
    SQL> COLUMN col FORMAT A4
    SQL> SELECT NULL col FROM DUAL;
    COL
    <<>>

  • Left Outer Join & IS NULL Not Working

    In a Data Flow Query element I am using a Left Outer Join to correlate two tables. In order to eliminate rows in which the Left Outer Join found a match with the Right table I am using IS NULL in the Where clause. Unfortunately IS NULL doesn't seem to return true when the NULL is caused by a lack of a match on a Left Outer Join. Has anybody been able to work around this?

    Use not is NULL in next query after the join.
    A source 1 ---
                           C (join query) ----- D (filter condition IS NULL)
    B source 2 ---

  • TextField setText(null) not working

    Very simply put, I want a text field that when you type in it, it stores the character in a global String variable but doesn't actually display it. I know there are several ways of doing this, including a PasswordField, but this is purely for understanding purposes only.
    String str = "";
    private void txtLineKeyPressed(java.awt.event.KeyEvent evt) {
        char key = evt.getKeyChar();
        str = str + key;
        txtLine.setText(null);
    }When typing "asdf" produces (caret is represented by |):
    a|
    s|
    d|
    f|I want to understand why txtLine.setText(null) clears the field BEFORE the letter is added to the field and possibly find out if there's a way (using TextField only) to accomplish this. I had a problem earlier with the enter key producing a line break at the end of all my lines and realized I was using a TextArea that caused the problem. Am I doing something similarly wrong?
    --dorky                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I want to understand why txtLine.setText(null) clears the field BEFORE the letter is added to the field Read up on how KeyListeners work. Three events are fired. The Document is updated on keyTyped(), which is generated after the keyPressed() event.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
    Also, the better way to do this is to use a DocumentFilter, not a KeyListener then you wouldn't have this problem. Read the Swing tutorial which has a working example of how to use a filter.
    Edited by: camickr on Feb 20, 2009 9:16 PM

  • ForeignKeyDeleteAction=null not working with Kodo 4.1.2 and Mysql 5

    Hello,
    i am trying to use Kodo 4.1.2, together with mysql 5.0
    my kodo.properties says:
    openjpa.jdbc.MappingDefaults: jdo(ForeignKeyDeleteAction=null)
    and i am expecting an sql-statement something like:
    ALTER TABLE mytable ADD FOREIGN KEY (bar) REFERENCES othertable(foo) ON DELETE SET NULL;
    but all i got is:
    ALTER TABLE mytable ADD FOREIGN KEY (bar) REFERENCES othertable(foo);
    Kodo 4.0 didn't have any problems with that. Also, in Kodo 4.1.2 other ForeignKeyDeleteActions (like 'cascade' oder 'default') are working like expected.
    What am i doing wrong? Where can i find some upgrade instructions? Is this a bug?
    Thanks in advance,
    Markus

    If the same exact app and code works with 4.0 with the same ForeignKeyDeleteAction setting, I suggest that you open a case with support.
    This property hasn't changed since 4.0
    http://e-docs.bea.com/kodo/docs41/full/html/ref_guide_mapping_defaults.html
    Laurent

  • CustomAttributeX -ne $null not working in -RecipientFilter

    I am trying to create a dynamic distribution Group that will only return users who have CustomAttribute9 with numeric string and exclude any users who do not have that attribute populated. Here is my filter
    New-DynamicDistributionGroup -Name GCI-AaronPTest -RecipientFilter {(RecipientType -eq 'UserMailbox') -or (RecipientType -eq 'MailUser') -And (CustomAttribute9 -like '0*') -and (Customattribute9 -ne $null)}
    This is still returning users who have blank field for CustomAttribute9. Any help would be appreciated.

    Hi,
    I recommend you try the following command and check the result:
    New-DynamicDistributionGroup -Name GCI –Alias GCI -RecipientFilter {(RecipientType -eq 'UserMailbox' -or RecipientType -eq 'MailUser') –And (CustomAttribute9 -like '0*' -or Customattribute9 -ne $null)}
    Hope this helps!
    Thanks.
    Niko Cheng
    TechNet Community Support
    (RecipientType -eq 'UserMailbox' -or RecipientType -eq 'MailUser') –And (CustomAttribute9 -like '0*' -or Customattribute9 -ne $null)
    this will include  all mailbox or mail user which  have customattribute9 other than like '0*'   too .
    so , replace just    -or   with -and   in
    (CustomAttribute9 -like '0*' -or Customattribute9 -ne $null)
    to achieve the result.
    MCITP - Exchange 2010 | MCITP - Windows Server 2008 R2

  • EntityManager is not null then what can be the problem?findAll not working

    Hello,
    I am just a beginner trying to learn JPA. I successfully added record to database but when i tried to display it it throws me null pointer exception. This is the code
    index.xhtml
    <?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:f="http://java.sun.com/jsf/core">
        <h:head>
            <title>Facelet Title</title>
        </h:head>
        <h:body>
            <h:form>
                <h:outputLabel value="Username :"/>
                <h:inputText value="#{IndexManagedBean.userName}"/> <br />
                <h:outputLabel value="Password :"/>
                <h:inputText value="#{IndexManagedBean.password}"/> <br />
                <h:outputLabel value="Birthdate :"/>
                <h:inputText value="#{IndexManagedBean.birthdate}">
                    <f:convertDateTime dateStyle="medium" type="date"/>
                </h:inputText> <br />
                <h:commandButton value="Add User" actionListener="#{IndexManagedBean.addUser}"/>
                <br />
                <br/>
            </h:form>
        </h:body>
    </html>Users.java My Entity bean
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package BusinessFacade;
    import java.io.Serializable;
    import java.util.Date;
    import javax.persistence.Basic;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    @Entity
    @Table(name = "tblusers", catalog = "ssms", schema = "")
    @NamedQueries({
        @NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
        @NamedQuery(name = "Users.findByUserId", query = "SELECT u FROM Users u WHERE u.userId = :userId"),
        @NamedQuery(name = "Users.findByUserName", query = "SELECT u FROM Users u WHERE u.userName = :userName"),
        @NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password"),
        @NamedQuery(name = "Users.findByLastLoginDateTime", query = "SELECT u FROM Users u WHERE u.lastLoginDateTime = :lastLoginDateTime"),
        @NamedQuery(name = "Users.findByBirthdate", query = "SELECT u FROM Users u WHERE u.birthdate = :birthdate")})
    public class Users implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @Column(name = "UserId", nullable = false)
        private Integer userId;
        @Basic(optional = false)
        @Column(name = "UserName", nullable = false, length = 50)
        private String userName;
        @Basic(optional = false)
        @Column(name = "Password", nullable = false, length = 50)
        private String password;
        @Basic(optional = false)
        @Column(name = "LastLoginDateTime", nullable = false)
        @Temporal(TemporalType.TIMESTAMP)
        private Date lastLoginDateTime;
        @Column(name = "Birthdate")
        @Temporal(TemporalType.TIMESTAMP)
        private Date birthdate;
        public Users() {
        public Users(Integer userId) {
            this.userId = userId;
        public Users(String userName, String password, Date birthDate) {
            this.userName = userName;
            this.password = password;
            this.lastLoginDateTime = new Date();
            this.birthdate = birthDate;
        public Integer getUserId() {
            return userId;
        public void setUserId(Integer userId) {
            this.userId = userId;
        public String getUserName() {
            return userName;
        public void setUserName(String userName) {
            this.userName = userName;
        public String getPassword() {
            return password;
        public void setPassword(String password) {
            this.password = password;
        public Date getLastLoginDateTime() {
            return lastLoginDateTime;
        public void setLastLoginDateTime(Date lastLoginDateTime) {
            this.lastLoginDateTime = lastLoginDateTime;
        public Date getBirthdate() {
            return birthdate;
        public void setBirthdate(Date birthdate) {
            this.birthdate = birthdate;
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (userId != null ? userId.hashCode() : 0);
            return hash;
        @Override
        public boolean equals(Object object) {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(object instanceof Users)) {
                return false;
            Users other = (Users) object;
            if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
                return false;
            return true;
        @Override
        public String toString() {
            return "BusinessFacade.Users[userId=" + userId + "]";
    }UsersFacade.java my Stateless session bean
    package BusinessFacade;
    import java.util.List;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    import javax.persistence.criteria.CriteriaQuery;
    import javax.persistence.criteria.Root;
    @Stateless
    public class UsersFacade {
        @PersistenceContext(unitName = "FirstJpaExamplePU")
        private EntityManager em;
        public void create(Users users) {
            em.persist(users);
        public void edit(Users users) {
            em.merge(users);
        public void remove(Users users) {
            em.remove(em.merge(users));
        public Users find(Object id) {
            return em.find(Users.class, id);
        public List<Users> findAll() {
            return em.createNamedQuery("Users.findAll").getResultList();
        public List<Users> findRange(int[] range) {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Users.class));
            Query q = em.createQuery(cq);
            q.setMaxResults(range[1] - range[0]);
            q.setFirstResult(range[0]);
            return q.getResultList();
        public int count() {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Users> rt = cq.from(Users.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
    }If entitymanager is null then even create should not work, but here findall is not working, create is working perfect!

    oops, sorry about that!
    here is stack trace :
    com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: IndexManagedBean.
         at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193)
         at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
         at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:405)
         at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:267)
         at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:86)
         at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175)
         at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
         at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:99)
         at com.sun.el.parser.AstValue.getValue(AstValue.java:158)
         at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
         at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:102)
         at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
         at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
         at javax.faces.component.UIOutput.getValue(UIOutput.java:168)
         at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
         at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:338)
         at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
         at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:878)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1620)
         at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
         at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1613)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
         at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:380)
         at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
         at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
         at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
         at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
         at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
         at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
         at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
         at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233)
         at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
         at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
         at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
         at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
         at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
         at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
         at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
         at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
         at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
         at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
         at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
         at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
         at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
         at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
         at java.lang.Thread.run(Thread.java:619)
    Caused by: java.lang.NullPointerException
         at BusinessFacade.UsersFacade.findAll(UsersFacade.java:47)
         at IndexManagedBean.<init>(IndexManagedBean.java:23)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
         at java.lang.Class.newInstance0(Class.java:355)
         at java.lang.Class.newInstance(Class.java:308)
         at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
         ... 53 moreEventually, i found out the EntityManager is null! But how can it be null. I created a persistence context and gave it proper name in code. Then how it be null?

  • Coldfusion 10. cfmenu not working. error is 'this.body.firstChild' is null or not an object

    I am using coldfusion 10. cfmenu not working. Error is 'this.body.firstChild' is null or not an object in menu-min.js file.
    Error in line oNode=this.body.firstChild.
    Any body faced same issue? What is the fix of this error.

    I have used the same code.
    <cfmenu name="menu" type="horizontal" fontsize="14" bgcolor="##CCFFFF">
        <cfmenuitem name="acrobat" href="http://www.adobe.com/acrobat" display="Acrobat"/>
        <cfmenuitem name="aftereffects" href="http://www.adobe.com/aftereffects"
            display="After Effects"/>
        <!--- The ColdFusion menu item has a pop-up menu. --->
        <cfmenuitem name="coldfusion"
                href="http://www.adobe.com/products/coldfusion" display="ColdFusion">
            <cfmenuitem name="buy"
                href="http://www.adobe.com/products/coldfusion/buy/" display="Buy"/>
            <cfmenuitem name="devcenter"
                href="http://www.adobe.com/devnet/coldfusion/" display="Developer Center"/>
            <cfmenuitem name="documentation"
                href="http://www.adobe.com/support/documentation/en/coldfusion/"
                    display="Documentation"/>
            <cfmenuitem name="support" href="http://www.adobe.com/support/coldfusion/"
                display="Support"/>
        </cfmenuitem>
        <cfmenuitem name="flex" href="http://www.adobe.com/flex" display="Flex"/>
    </cfmenu>

  • Help with After Effects? Null Layer and Text not working?

    In after effects cs5.5 on mac, im motion tracking as normal, and the track works fine, then when i add the null layer and edit the tracking target to the null layer, the screen goes black, and all i can see is the null layer as a red box moving along the motion track path (i cant see the path) also, whenever i try to add text, (which im trying to motion track via attatching to the null layer) the text is invisible, when the screens black, all i can see is the wire frame of the text next to the square null layer, im pretty new to after effects, but im following tutorials as i should, and its just not working as it shows in all the videos ive tried, please help!

    Check whether you have wireframe mode enabled/ Live Update disabled. Sounds like one of those cases. Other than that this could be OpenGL issues, so turn it off in the prefs. Also check your comp size vs. the size of the footage you are tracking. Tracking works relative to the layer, so if the comp is too small, the values would be so large they end up being outside the comp.
    Mylenium

  • Function to change Boarder Look and feel of Jframe - Not working

    Hi all,
    In the given SSCE, the functionpublic void changeButtonColor(Component[] comps) to change the border look and feel of JFrame is not working.Please help.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import java.util.Vector;
    import javax.swing.AbstractButton;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    import javax.swing.SwingConstants;
    import javax.swing.UIManager;
    public class ScrollableWrapTest {
        public static void main(String[] args) {
            try {
                final JPanel mainPanel = new JPanel(new WrapScollableLayout(FlowLayout.LEFT, 10, 10));
                mainPanel.setBackground(Color.WHITE);
                JScrollPane pane = new JScrollPane(mainPanel);
                pane.setPreferredSize(new Dimension(320, 200));
                Vector v = new Vector();
                v.add("first");
                JButton button = null;
                for(int i =0;i<v.size();i++){
                        JPanel panel = new JPanel(new BorderLayout());
                        panel.setBackground(Color.WHITE);
                        int num = mainPanel.getComponentCount()+1;
                        button = new JButton("button" + num);
                        button.setPreferredSize(new Dimension(90, 25));
                        JLabel label = new JLabel((String)v.elementAt(i));
                        label.setHorizontalAlignment(SwingConstants.CENTER);
                        panel.add(button, BorderLayout.NORTH);
                        panel.add(label, BorderLayout.SOUTH);
                        mainPanel.add(panel);
                        mainPanel.revalidate();
                ScrollableWrapTest st = new ScrollableWrapTest();
                st.buildGUI(pane);
            } catch (Exception e) {e.printStackTrace();}
        public void buildGUI(JScrollPane scrollPane)
             JFrame frame = new JFrame("Scrollable Wrap Test");
             JFrame.setDefaultLookAndFeelDecorated(true);
            UIManager.put("activeCaption", new javax.swing.plaf.ColorUIResource(Color.LIGHT_GRAY));
            changeButtonColor(frame.getComponents());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.setLocationRelativeTo(null);
            frame.pack();
            frame.setVisible(true);
        public void changeButtonColor(Component[] comps)
          for(int x = 0, y = comps.length; x < y; x++)
            if(comps[x] instanceof AbstractButton)
              ((AbstractButton)comps[x]).setBackground(Color.LIGHT_GRAY);
              ((AbstractButton)comps[x]).setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
            else if (comps[x] instanceof Container)
              changeButtonColor(((Container)comps[x]).getComponents());
        private static class WrapScollableLayout extends FlowLayout {
            public WrapScollableLayout(int align, int hgap, int vgap) {
                super(align, hgap, vgap);
            public Dimension preferredLayoutSize(Container target) {
                synchronized (target.getTreeLock()) {
                    Dimension dim = super.preferredLayoutSize(target);
                    layoutContainer(target);
                    int nmembers = target.getComponentCount();
                    for (int i = 0 ; i < nmembers ; i++) {
                        Component m = target.getComponent(i);
                        if (m.isVisible()) {
                            Dimension d = m.getPreferredSize();
                            dim.height = Math.max(dim.height, d.height + m.getY());
                    if (target.getParent() instanceof JViewport)
                        dim.width = ((JViewport) target.getParent()).getExtentSize().width;
                    Insets insets = target.getInsets();
                    dim.height += insets.top + insets.bottom + getVgap();
                    return dim;
    }Please help.
    Rony

    You are calling changeButtonColor(frame.getComponents()) before you add the JScrollPane to the content pane.
    But why not just move this to the button creation loop?
    button = new JButton("button" + num);
    button.setBackground(Color.LIGHT_GRAY);
    button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));

  • Esc key not working with JDialog

    Hi,
    We are facing a KeyListening problem with JDialog. We developed an application using JRE 1.4.0. When we migrate from 1.4.0 to 1.4.2.The Esc keys(All keys) associated with the JDialog is not listening. Following is code piece is showing the Esc key. The same piece of code is working with 1.4.0 and with lesser versions. U'r help will be appriciated.
    import java.awt.Container;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    public class EscDialog extends JDialog implements KeyListener {
         static EscDialog ed = new EscDialog();
         public static void main(String[] args) {
              ed.setSize(200, 300);
              ed.addKeyListener(ed);
              JButton jb = new JButton("Test");
              JPanel jp = new JPanel();
              jp.add(jb);
              Container cp = ed.getContentPane();
              cp.add(jp);
              ed.show();
         public void keyPressed(KeyEvent anEvent) {
              if (anEvent.getKeyCode() == KeyEvent.VK_ESCAPE)
                   System.exit(0);
         public void keyTyped(KeyEvent anEvent) {
         public void keyReleased(KeyEvent anEvent) {
    }

    An example:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JDialog {
        public Test () {
            getContentPane ().setLayout (new FlowLayout ());
            getContentPane ().add (new JLabel ("Press escape to exit..."));
            getRootPane ().getInputMap ().put (KeyStroke.getKeyStroke (KeyEvent.VK_ESCAPE, 0), "dispose");
            getRootPane ().getActionMap ().put ("dispose", new AbstractAction () {
                public void actionPerformed (ActionEvent event) {
                    dispose ();
            pack ();
            setDefaultCloseOperation (DO_NOTHING_ON_CLOSE);
            setLocationRelativeTo (null);
            setTitle ("Test");
            setVisible (true);
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
      Levi

  • The sound file not work

    HI,
    Here i want to get sound file then i want to play it . I did that but when i play it , it's not work .why ??
    my code :
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
    import java.io.*;
    import javax.sound.sampled.*;
    import javax.sound.sampled.UnsupportedAudioFileException;
    import javax.swing.*;
    public class SoundTest extends JFrame {
        private JPanel panel, mainPanel;
        //   private JTextField textField;
        private JButton getButton, playButton;
        private JFileChooser fileChooser;
        private MyActionListener myActionListener;
        public SoundTest() {
            myActionListener = new MyActionListener();
            panel = new JPanel(new BorderLayout());
            mainPanel = new JPanel(new FlowLayout());
            //       textField = new JTextField(10);
            getButton = new JButton("get audio file");
            getButton.addActionListener(myActionListener);
            playButton = new JButton("play");
            playButton.addActionListener(myActionListener);
            //     mainPanel.add(textField);
            mainPanel.add(getButton);
            mainPanel.add(playButton);
            panel.add(mainPanel, BorderLayout.WEST);
            getContentPane().add(panel);
            fileChooser = new JFileChooser();
        public static void main(String[] args) {
            SoundTest soundTest = new SoundTest();
            soundTest.setDefaultCloseOperation(SoundTest.EXIT_ON_CLOSE);
            soundTest.setSize(new Dimension(600, 300));
            soundTest.setLocationRelativeTo(null);
            soundTest.setVisible(true);
        private class MyActionListener implements ActionListener {
            SourceDataLine sourceDataLine = null;
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == getButton) {
                    int returnValue = fileChooser.showOpenDialog(SoundTest.this);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        File file = fileChooser.getSelectedFile();
                        crateAudio(file);
                } else if (e.getSource() == playButton) {
                    playAudio();
            private void crateAudio(File file) {
                AudioInputStream audioInputStream = null;
                try {
                    audioInputStream = AudioSystem.getAudioInputStream(file);
                } catch (UnsupportedAudioFileException ex) {
                    ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
                AudioFormat audioFormat = audioInputStream.getFormat();
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
                try {
                    sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
                    sourceDataLine.open(audioFormat);
                } catch (LineUnavailableException ex) {
                    ex.printStackTrace();
            private void playAudio() {
                sourceDataLine.start();
    }Thanks in advnce

    beshoyatefw wrote:
    Here i want to get sound file then i want to play it . I did that but when i play it , it's not work .why ??Because there's no code that actually plays the file? Source data lines don't play the file when you open them, you have to manually read data from the AudioInputStream and write it to the SourceDataLine...and you're not doing that.
    You essentially walked into the bathroom, lifted the toilet seat and unzipped your pants...and wondered why the toilet wasn't making that "I'm peeing" sound. It's because you didn't start actually moving urine from your bladder to the toilet...

  • TableChanged() does not work with parrent table reference

    Hi,
    I used this example http://www.javalobby.org/articles/jtable/ where the cells refocus after updating, but I have rewrote it to my needs and the program throws nullpointerexception when I update any cell:(
    here is the tableChanged part of code:
        public class InteractiveTableModelListener implements TableModelListener {
            public void tableChanged(TableModelEvent evt) {
                if (evt.getType() == TableModelEvent.UPDATE) {
                    int column = evt.getColumn();
                    int row = evt.getFirstRow();
                    System.out.println("updated row: " + row + " column: " + column);
                   if((column + 1) >= model.getRowCount()){
                      table.removeColumnSelectionInterval(column,column);
                    }else{
                      table.setColumnSelectionInterval(column + 1, column + 1);
                    table.setRowSelectionInterval(row,row);
    }the table reference worked in the exaple but doesnt work in my program:(
    here is the init of the table in function initComponent:
            tableModel.addTableModelListener(new InteractiveTableModelListener());
            TableSorter sorter = new TableSorter(tableModel);
            JTable table = new JTable(sorter);the class is on the same level as the function
    i have searched all the internet for this with no results:(
    thank you for your advice!

    Yes, you are right, I wrote this post in a hurry and exhaused, that it does not work.
    I'm trying to write out a data file (now only a vector of data) in a JTable and I want to edit the rows and after I submit text in a cell, I want the caret to move one cell right, so the user can write another text, just like in MS Excel. At the end of the row the caret disapears but does not create another row.
    And I have problems with variable JTable table in the inner class that contains method tableChanged().
    Well After making an example I realized it worked and then I checked the example line by line and found out that I declare another JTable with the same name in the table initializing method,
    Then the variable couldnt work in tableChanged method... It was empty...
    I used your example from thread, you advised me:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableProcessing extends JFrame implements TableModelListener
         // here I declare the table
            protected JTable table;
         public TableProcessing()
              String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
              Object[][] data =
                   {"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
                   {"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
                   {"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
                   {"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              model.addTableModelListener( this );
                    // here I declare it again, which is a MISTAKE
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                   //  The Cost is not editable
                   public boolean isCellEditable(int row, int column)
                        int modelColumn = convertColumnIndexToModel( column );
                        return (modelColumn == 3) ? false : true;
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
          *  The cost is recalculated whenever the quantity or price is changed
         public void tableChanged(TableModelEvent e)
              System.out.println(e.getSource());
              if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2)
                                   // AND here is not initialised - throws NullPointerException
                        TableModel model = table.getModel();
                        int     quantity = ((Integer)model.getValueAt(row, 1)).intValue();
                        double price = ((Double)model.getValueAt(row, 2)).doubleValue();
                        Double value = new Double(quantity * price);
                        model.setValueAt(value, row, 3);
         public static void main(String[] args)
              TableProcessing frame = new TableProcessing();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • .jar file is not working properly :developed in NETBEANS

    Hi Gurus,
    i am using NETBEANS IDE 7.2.
    i am developing a project that interacts with databases 10g and COM ports of machine , these all processes are performed by .bat file which i am trying to run from jFramform , code works perfectly .bat file is also called perfectly when i run the project using F6 from the NETBEANS, for testing i placed some dialogue boxes on the form to test it ,
    but when i run executable .jar  file , form run successfully and dialogue box works perfectly but .bat file is not called by executable .jar file.
    this is how i call the .bat file...
      String filePath = "D:/pms/Libraries/portlib.bat";  
            try { 
              Process p = Runtime.getRuntime().exec(filePath); 
            } catch (Exception e) { 
                e.printStackTrace(); 
    and below is the contents of portlib.bat file
    java -jar "D:\SMS\SMS\dist\SMS.jar" 
    you must probably ask why i am calling a .jar file using .bat file .
    reason is that this .jar project sends message using GSM mobile , System.exit(); is compulsory to complete a job and then do the next one ,
    if i use the same file to execute this job it makes exit to entire the application (hope you can understand my logic).
    that's why i use extra .jar file in .bat file , when single job is completed .bat exits itself and new command is given.
    Problem is that code is working perfectly in NETBEANS when i run the project but when i run .jar then .bat file is not working  ,
    thanks.

    Thanks Sir ,
    You need to first test an example that works like the one in the article.
    There are plenty of other examples on the web - find one you like:
    http://javapapers.com/core-java/os-processes-using-java-processbuilder/
    I tried this one.
      try {
                ProcessBuilder dirProcess = new ProcessBuilder("D:/SMS/SMS/Send_message.bat");
                 File commands = new File("D:/SMS/SMS/Send_message.bat");
                 File dirOut = new File("C:/process/out.txt");
                 File dirErr = new File("C:/process/err.txt");
               dirProcess.redirectInput(commands);
                 dirProcess.redirectOutput(dirOut);
               dirProcess.redirectError(dirErr);
                 dirProcess.start();
            } catch (IOException ex) {
                Logger.getLogger(mainform.class.getName()).log(Level.SEVERE, null, ex);
    as instructed in the article i compiled  both the projects at same version or sources and libraries which is 1.7
    here is my version details
    C:\>javac -version
    javac 1.7.0_07
    C:\>java -version
    java version "1.7.0_07"
    Java(TM) SE Runtime Environment (build 1.7.0_07-b11)
    Java HotSpot(TM) Client VM (build 23.3-b01, mixed mode, sharing)
    inside the NETBEANS IDE c:\process\err.txt  remains empty and code works perfectly , but when I run executable .jar file( by double clicking on that file in dist directry) then c:\process\err.txt becomes full with this error text and there is no response from calling D:\SMS\SMS\send_message.bat
    here is the error text
    java.lang.UnsupportedClassVersionError: sms/SMSMAIN (Unsupported major.minor version 51.0)
      at java.lang.ClassLoader.defineClass0(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$100(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)
    Exception in thread "main"
    here is /SMS/SMS
    unknown source ?

Maybe you are looking for

  • Should i delete my photos from iPhoto after I import to aperture

    should i delete my photos from iPhoto after I import to aperture? What is the easiest way to do this?

  • How do i save an email on my ipad to a file on the ipad?

    This is the second time I have submitted this question.  I cannot now find where the original question went or any replies. I have an ipad 2 and I need to know how to save an email from my inbox on the ipad to a file, for later reading outside of the

  • Query SQ01/ SQ02.

    Hi all, Can anyone provide me material / related links to SQL query. Thanks in advance. Needful will be rewarded points.

  • Screen fuzzy when touch is connected to TV

    I purchased the apple cable to be able to watch my movies and such on my TV. When I connected it the sound comes through perfectly, but the pictures is very distorted and fuzzy. You cannot see the movie. What am I doing wrong, or what is wrong with m

  • Movement Type 511 when  stock in the Inventory is nil

    Hello Sir / Madam  , I have some queries regarding 511 Movement type : Free-of-charge delivery from vendor. When this movement type is posted it updates the Stock (MARD-LABST) as well as the Valuation Table (MBEW-LBKUM). (Unrestricted movement) But t