简体   繁体   中英

How can i pass value in a class?? JAVA

How can I pass value in a class?

I try to draw bar-charts for each key-value of the array.

So, I have to pass (int) len through class Grid . How can I find a solution here? Thanks in advance :)

So here is my code:

int len; 

public void HistogramGen() {

    JFrame framegraph = new JFrame("Terms Histogram");  
    framegraph.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
    framegraph.pack(); 
    framegraph.setVisible(true); 

    JPanel p= new JPanel( new GridLayout(finalnumber, 3) );

    for(int m=0; m<finalnumber; ++m) {
        p.add( new JLabel((String)keys[m]) );
        p.add( new JLabel( ((Integer)values[m]).toString() ) );
        String bar= "";
        for(int n=0; n<(Integer)values[m]; ++n) {
            bar= bar + "_";
        }
        len=bar.length();
        p.add( new Grid() ); 
    }

    JScrollPane pane= new JScrollPane( p );
    framegraph.add( pane );
}


public static class Grid extends JComponent {
    public void paint(Graphics g) {
        g.drawRect(0, 0, len, 10);
        g.setColor(Color.MAGENTA);
        g.fillRect(0, 0, len, 10);
    }
}

add constructor to your Grid class like this:

public static class Grid extends JComponent {
    private final int len;
    public Grid(final int len) {
        super();

        this.len = len;
    }
    public void paint(Graphics g) {
    ...
}

then change you caller code

p.add( new Grid(bar.length()) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM