Categories
discuss

Filling an array with objects

I need some help with a homework question I am working on. I need to create a “Library” class that contains an array of Song objects.(capacity of 10). Then make a method addSong. Here’s what I have so far:

public class Library{

    Song[] arr = new Song[10];

    public void addSong(Song s){
        for(int i=0; i<10; i++)
            arr[i] = s;
    }
}

My question is: Is there another way to fill the array? i will later need to search for a song based on a index value. So i will create a method like: public Song getSong(int idx) Thank you in anticipation for your answers!

Answer

If you really have to use an array (and not an ArrayList or LinkedList), this solution may be the right for you:

public class Library{

    private Song[] arr = new Song[10];
    private int songNumber = 0; //the number of Songs already stored in your array

    public void addSong(Song s){
        arr[songNumber++] = s;
    }
}

If you want to avoid a runtime-exeption if you add more then 10 songs:

public void addSong(Song s){
    if(songNumber<10)
    {
       arr[songNumber++] = s;
    }else{
       //what to do if more then 10 songs are added
    }
}
Categories
discuss

Obtain field (td) values by clicking on table row

I need your help.

I have the following table as detailed below. What I would like to do is to click on one of the rows in the table (headers excluded) and obtain the column values of the selected row.

How do I populate the textboxes with the information from the selected row in the table?

No libraries please.

<!DOCTYPE html>

<html>

<head>

</head>

<body>


<table id="myTable" cellspacing="1">             
    <thead>> 
        <tr> 
            <th>first name</th> 
            <th>last name</th> 
            <th>age</th> 
            <th>total</th> 
            <th>discount</th> 
            <th>diff</th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>peter</td> 
            <td>parker</td> 
            <td>28</td> 
            <td>9.99</td> 
            <td>20.3%</td> 
            <td>+3</td> 
        </tr> 
        <tr> 
            <td>john</td> 
            <td>hood</td> 
            <td>33</td> 
            <td>19.99</td> 
            <td>25.1%</td> 
            <td>-7</td> 
        </tr> 
        <tr> 
            <td>clark</td> 
            <td>kent</td> 
            <td>18</td> 
            <td>15.89</td> 
            <td>44.2%</td> 
            <td>-15</td> 
        </tr> 
        <tr> 
            <td>bruce</td> 
            <td>almighty</td> 
            <td>45</td> 
            <td>153.19</td> 
            <td>44%</td> 
            <td>+19</td> 
        </tr> 
        <tr> 
            <td>bruce</td> 
            <td>evans</td> 
            <td>56</td> 
            <td>153.19</td> 
            <td>23%</td> 
            <td>+9</td> 
        </tr> 
    </tbody> 
</table>

Firstname is:<input type="text" id="firstname" />
<br>
Lastname is:<input type="text" id="lastname" />
<br>
Age is:<input type="text" id="age" />
<br>
Total is:<input type="text" id="total" />
<br>
Discount is:<input type="text" id="discount" />
<br>
Diff is:<input type="text" id="diff" />
</body>

</html>

Answer

Here is one example how to use event delegation in javascript (it’s especially convenient for dynamically added content) . The event handler is attached to TABLE element’s onclick attribute:

function run(){
    document.getElementById('myTable').onclick = function(event){
        event = event || window.event; //for IE8 backward compatibility
        var target = event.target || event.srcElement; //for IE8 backward compatibility
        while (target && target.nodeName != 'TR') {
            target = target.parentElement;
        }
        var cells = target.cells; //cells collection
        //var cells = target.getElementsByTagName('td'); //alternative
        if (!cells.length || target.parentNode.nodeName == 'THEAD') { // if clicked row is within thead
            return;
        }
        var f1 = document.getElementById('firstname');
        var f2 = document.getElementById('lastname');
        var f3 = document.getElementById('age');
        var f4 = document.getElementById('total');
        var f5 = document.getElementById('discount');
        var f6 = document.getElementById('diff');
        f1.value = cells[0].innerHTML;
        f2.value = cells[1].innerHTML;
        f3.value = cells[2].innerHTML;
        f4.value = cells[3].innerHTML;
        f5.value = cells[4].innerHTML;
        f6.value = cells[5].innerHTML;
    }
}

JSFIDDLE: code / result page

The alternative solution, where the event handler is directly attached to each TR element can look like this:

function run() {
    var t = document.getElementById('myTable');
    var rows = t.rows; //rows collection - https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement
    for (var i=0; i<rows.length; i++) {
        rows[i].onclick = function () {
            if (this.parentNode.nodeName == 'THEAD') {
                return;
            }
            var cells = this.cells; //cells collection
            var f1 = document.getElementById('firstname');
            var f2 = document.getElementById('lastname');
            var f3 = document.getElementById('age');
            var f4 = document.getElementById('total');
            var f5 = document.getElementById('discount');
            var f6 = document.getElementById('diff');
            f1.value = cells[0].innerHTML;
            f2.value = cells[1].innerHTML;
            f3.value = cells[2].innerHTML;
            f4.value = cells[3].innerHTML;
            f5.value = cells[4].innerHTML;
            f6.value = cells[5].innerHTML;
        };
    }
}

JSFIDDLE: code / result page

Categories
discuss

How to perform action on OK of JOptionPane.showMessageDialog

I am working on my first desktop based Java project. I have 2 questions actually

1) How to perform action on OK button of JOptionPane.showMessageDialog.I want to navigate to a new Jframe say x.java on clicking ok.

2) I have a table named as user. This table has 8 columns userid (Primary Key), name, password,emailid, dob, mobileno ,city, date. Four column entries has to be fetched from a Jframe x and remaining four from other Jframe y.

I wrote the following code

For Frame X

PreparedStatement stm = con.prepareStatement("insert into user  

(userrid,name,password,emailid))values (?,?,?,?) ");

      stm.setString(1,id); // id is a public variable
      stm.setString(2,name);
      stm.setString(3,ps);
      stm.setString(4,email);
     stm.executeUpdate();

And for Frame Y. (userid is primary key)

public class Y extends javax.swing.JFrame
{  
    X o = new X(); // to access id variable from frame X

} 



PreparedStatement stm = con.prepareStatement(" update user set  dob ='? ', mobileno 
='?' ,city='?', date='?'  where userid= 'o.id' ");  

It keeps throwing exceptions for the above sql query

java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

Answer

1) How to perform action on OK button of JOptionPane.showMessageDialog.I want to navigate to a new Jframe say x.java on clicking ok.

int input = JOptionPane.showOptionDialog(null, "Hello World", "The title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);

if(input == JOptionPane.OK_OPTION)
{
    // do something
}
Categories
discuss

Should the constructor of a private inner class be declared public or private?

Is there any actual difference between this

public class OuterClass {
    private class InnerClass {
        public InnerClass() {}
    }
}

and this?

public class OuterClass {
    private class InnerClass {
        private InnerClass() {}
    }
}

Answer

Accessing private members from another class is slightly more complicated because the JVM doesn’t actually allow this. As a result the compiler injects accessor methods which makes it slightly slower or your stack trace more complicated.

For these reason I leave it as package local.

BTW The constructor of an abstract class doesn’t need to be public either. It may as well be protected or package local

private static class A {
    private A() {
        throw new Error();
    }
}
public static void main(String... ignored) {
    new A();
}

prints an extra stack trace element.

Exception in thread "main" java.lang.Error
    at Main$A.<init>(Main.java:8)
    at Main$A.<init>(Main.java:6)
    at Main.main(Main.java:12)

Make the constructor package local and the second one disappears.

Categories
discuss

Difference between offsetParent and parentElement or parentNode

I have a following DOM structure

<body>
    <div>
       <table>
          <outerElement>
              <innerElement />  
          </outerElement>
       <table>
    </div>
</body>

DIV has its overflow set to auto so if table grows bigger – it scrolls within the DIV.

In this scenario why table.offsetParent returns the body while both table.parentNode and parentElement return the Div?

I need to calculate current position of the innerElement within the window, so I traverse from it up thru all parent elements, collecting their offsetTop and offsetLeft values. Up until the DIV offsetParent works fine and then it skips it directly to the body. The problem if there’s scrolling involved at some point, I need to account for scrollTop and scrollLeft as well – like in the DIV in the above example. The problem is if I use offsetParent I never encounter the DIV as one of the parents.

UPDATE

This is part of the code that does the traversing:

while (oElem && getStyle(oElem, 'position') != 'absolute' && getStyle(oElem, 'position') != 'relative') { 
   curleft += oElem.offsetLeft;
   curtop += oElem.offsetTop;
   oElem = oElem.offsetParent;
}

where getStyle is a custom function that in this case retrieves the position style.

Answer

Stay clear of offsetParent, you’ll have to add lots of hacks and checks to ensure you get it right.

Try using getBoundingClientRect instead.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..