Icon in JLabel

I tried to add a JLabel on a Panel(of Border Layout). The icon in the Label is not shown. Same problem occurs when I tried to add a JButton, I can see only the text not the icon. I tried different iconTextGap values also. The icons doesn't showup

Actually Iam using Forte4j, I add my controls in the form itself and set the properties also through form.
jLabel1.setIcon (new javax.swing.ImageIcon ("F:\\try_panel_glcanvas\\src\\images\\logo.gif"));
added to java.awt.Panel ,
myTitleBar.add (jLabel1, java.awt.BorderLayout.WEST);
regards

Similar Messages

  • Location of Icon in JLabel

    I am writing an application that responds to a mouse click in a JLabel. This Icon has to move as the window resizes (as default in GridLayout). Despite this I need to be able to translate clicking on the top corner of the ImageIcon to clicking on (0,0).
    I know that this top corner will be red, so I could search the JLabel for the first pixel of that color. I'm not sure how to do that though.
    If there is an easier way to figure out where the top corner of a particular icon in a label is, though, it would be greatly appreciated.
    Thanks in advance,
    Sarah

    This is the function from BasicLabelUI that is used to position the icon.
    iconR is the icon Rectangle.
        protected String layoutCL(
            JLabel label,                 
            FontMetrics fontMetrics,
            String text,
            Icon icon,
            Rectangle viewR,
            Rectangle iconR,
            Rectangle textR)
            return SwingUtilities.layoutCompoundLabel(
                (JComponent) label,
                fontMetrics,
                text,
                icon,
                label.getVerticalAlignment(),
                label.getHorizontalAlignment(),
                label.getVerticalTextPosition(),
                label.getHorizontalTextPosition(),
                viewR,
                iconR,
                textR,
                label.getIconTextGap());
        }This is the call to this method:
            JLabel label = (JLabel)c;
            String text = label.getText();
            Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();
            if ((icon == null) && (text == null)) {
                return;
            FontMetrics fm = SwingUtilities2.getFontMetrics(label, g);
            Insets insets = c.getInsets(paintViewInsets);
            paintViewR.x = insets.left;
            paintViewR.y = insets.top;
            paintViewR.width = c.getWidth() - (insets.left + insets.right);
            paintViewR.height = c.getHeight() - (insets.top + insets.bottom);
            paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
            paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
            String clippedText =
                layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);

  • Custom Icon in JLabel - center?

    I have a custom Icon that I am placing in a JLabel, but I can't get it to be centered!
    I can put an ImageIcon in the JLabel, and it will be centered, but my custom Icon doesn't seem to follow the setVerticalAlignment/setHorizontalAlignment properties.
    I am using java 1.3.1.
    Any suggestions?

    The first thing I would do is check the frame of the custom icon to see if it is bigger than the picture...that could be the problem.

  • Heavyweight object of an Icon and JLabel

    Hi there,
    I would like to know how can I create a heavyweight object that has a JLabel and an Icon and then add it to a JFrame. this heavyweight object would be something like this
    public class TestObject extends JPanel
    ..public TestObject( String LabelName )
    ....theLabel = new JLabel( LabelName );
    ....add( theIcon ); // I cant add the Icon here, because it's not a Component
    ....add( theLabel );
    ..private JLabel theLabel;
    ..private Icon theIcon = new ImageIcon( "littleIcon.gif" );
    Thanks,
    Andre

    Using the following class I could draw a JLabel that has an ImageIcon, but it doesn't matter what the value of the horizontalAlignment ( LEFT, CENTER, RIGHT, LEADING or TRAILING ) the icon was always at the left side and the string at the right. Is there a way to put the Icon on the top and the String at the button of the Label?
    public class TestObject extends JPanel
    public TestObjectent( String LabelName )
    theIcon = new ImageIcon( "littleIcon.gif" );
    theLabel = new JLabel( LabelName theIcon, SwingConstants.TRAILING );
    add( theLabel );
    private Icon theIcon;
    private JLabel theLabel;
    Thanks,
    Andre

  • Draw image icon on JLabel

    Does anyone know how I can paint an icon on an already existing JLabel image without having the original image disappear partially or completely?
    The way I have it set up right now is that the original image listens to MouseListener, and displays information on a textArea when I click on the map.
    What I wish to do is to display an icon on the map image whenever I click on it.
    I'm a rather amateur with Java, and don't know how to make interfaces interact with eachother, no matter how hard I try. I need to know if I can add something to my current code to get what I want. I have had tried to interact different classes with eachother, but I haven't been getting what I wanted. Please help me out!
    I know how to display the icon on another panel, and make it move. but not on the same panel on the original picture.
    Here's my code:
    package screem.netrol.communication.event;
    * @author Nazli
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.Component;
    import java.awt.Image;
    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.ImageIcon;
    import java.net.*; // For class URL.
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.border.TitledBorder;
    import javax.swing.event.MouseInputAdapter;
    import java.applet.*;
    public class MyMapPanel extends JPanel implements DataTurbineListener, MouseListener, ImageObserver
    final static String newline = "\n";
    JTextArea textArea; //= new JTextArea();
    public static String url;
    public static ImageIcon ic;
    public static ImageIcon ic2 = new ImageIcon("http://www-jkn.ee.uec.ac.jp/tnklab/96/nakazawa/icons/colorball/small/BALL120.gif");
    public static JLabel mapArea;
    //public static JApplet mapArea;
    //public static File output = new File("results.txt");
    public static boolean showPoint;
    public static int x;
    public static int y;
    private BufferedImage bufImg ;
    private Image smallImg ;
    int w;
    int h;
    /*public static BufferedImage bufImg ;
    public static Image smallImg ; */
    /* GeneralPath path;
    final int PAD = 20;
    final int N = 8; */
    public static MyJFrame f;
    public MyMapPanel() {}
    public MyMapPanel(ImageIcon ic)
    super(new FlowLayout (FlowLayout.CENTER, 0,0));
    textArea = new JTextArea();
    setImageIcon(ic);
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea);
    add(scrollPane);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(700,100));
    //getContentPane().add(new MyPanel(), BorderLayout.CENTER);
    //addMouseListener( new MusClk() ) ;
    protected class MusClk extends MouseAdapter {
    public void mouseClicked ( MouseEvent musEvt ) {
    if( musEvt.getX() > bufImg.getWidth() || musEvt.getY() > bufImg.getHeight() ) {
    return ;
    Graphics g = bufImg.getGraphics() ;
    int w = smallImg.getWidth( null ) ;
    int h = smallImg.getHeight( null ) ;
    g.drawImage( smallImg , musEvt.getX() - w / 2 , musEvt.getY() - h / 2 , null ) ;
    MyMapPanel.this.repaint( musEvt.getX() - w / 2 , musEvt.getY() - h / 2 , w , h ) ;
    public ImageIcon getImageIcon()
    setImageIcon(ic);
    return ic;
    public void setImageIcon(ImageIcon ic)
    //MyPanel panel = new MyPanel();
    try{
    URL u = new URL(url);
    ic = new ImageIcon(u);
    } catch (MalformedURLException e) {
    System.out.println (e);
    mapArea = new JLabel(ic, JLabel.CENTER);
    add(mapArea);
    mapArea.addMouseListener(this);
    try {
    URL u = new URL(url);
    ic = new ImageIcon(u);
    } catch (MalformedURLException e){
    System.out.println(e);
    mapArea = new JApplet();
    add(mapArea);
    mapArea.addMouseListener(this); */
    /* public void setMouseEvent(MouseEvent e)
    x = e.getX();
    y = e.getY();
    showPoint = true;
    protected void paintComponent(Graphics g){ }
    public void dataTurbineOutputEvent(DataTurbineEvent event){}
    public void dataTurbineInputEvent(DataTurbineEvent event){}
    public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) { }
    public void mouseClicked(MouseEvent e)
    //setMouseEvent(e);
    //System.out.println("x="+x+" y="+y);
    showPoint = true;
    ImageIcon icon = new ImageIcon("C:/Documents and Settings/Nazli/My Documents/My Pictures/ball.gif");
    w = icon.getIconWidth();
    h = icon.getIconHeight();
    bufImg = new BufferedImage(w , h , BufferedImage.TYPE_INT_RGB ) ;
    Graphics g = bufImg.getGraphics();
    g.drawImage( icon.getImage() , 0 , 0 , null ) ;
    //MyMapPanel.this.repaint(e.getX() - w / 2 , e.getY() - h / 2 , w , h ) ;
    /*Point p = e.getPoint();
    Rectangle tag;
    final int SIDE = 6;
    tag = new Rectangle(0, 0, SIDE, SIDE);
    float x = e.getX();
    float y = e.getY();
    tag.setLocation(p.x - SIDE/2, p.y - SIDE/2);
    if(tag.contains(p.x,y))
    showPoint = true;
    setPoint(p);
    //System.out.println("e.getX="+e.getX()+""+"e.getY="+e.getY());
    saySomething("Position in pixels:(" + e.getX() + ", " + e.getY() + ")", e);
    String s1 = computeLatLong(e.getX());
    String s2 = computeLatLong(e.getY());
    saySomething("Position in Lat/Long: (" + s1 + ", " + s2 + ")", e);
    //g.drawImage(img, e.getX(), e.getY(), this);
    //DrawImage d = new DrawImage();
    //public void mouseClicked ( MouseEvent musEvt ) {
    //DrawImage d = new DrawImage();
    void saySomething(String eventDescription, MouseEvent e)
    textArea.append(eventDescription + " detected on " + e.getComponent().getClass().getName() + "." + newline);
    textArea.setCaretPosition(textArea.getDocument().getLength());
    public String computeLatLong(double d)
    double d1;
    double seconds;
    double minutes;
    double m;
    double s;
    String rval;
    d1 = d - Math.floor(d);
    seconds = d1 / 3600;
    minutes = seconds / 60;
    m = minutes - Math.floor(minutes);
    s = m * 60; //minutes converted to seconds
    rval = (int)Math.floor(d) + "deg " + (int)minutes + "' " + (int)s + '"';
    return rval;
    public MyJFrame getFrame()
    return f;
    public static void main(String[] args) throws IOException {
    //DrawImage d = new DrawImage();
    System.out.println("x="+x+" y="+y);
    ArrayList file = new ArrayList();
    File input = new File("lat_lon.txt");
    FileReader in = new FileReader(input);
    File output = new File("archive3.txt");
    FileWriter out = new FileWriter(output);
    //FileWriter in2 = new FileWriter(input);
    FileOutputStream outdata = new FileOutputStream(output);
    PrintStream p = new PrintStream(outdata);
    BufferedReader br = new BufferedReader(in, 4096);
    BufferedWriter bw = new BufferedWriter(new FileWriter("lat_lon.txt", true));
    String line; //each line in input file
    String s=null; //Main string containing points information, to be written to the output file
    while ((line = br.readLine()) != null )
    file.add(line);
    StringTokenizer st = new StringTokenizer(line,";");
    while(st.hasMoreTokens())
    s = st.nextToken();
    p.println(s);
    p.println("FINISHED DATA TRANSFER");
    p.println("\n");
    bw.write("DATA TRANSFERRED TO OUTPUT FILE");
    bw.newLine();
    bw.flush();
    p.close();
    //pops up the input dialogue window for the user to enter the image URL
    url = JOptionPane.showInputDialog(null,"Provide image URL:\n","Map Image", JOptionPane.PLAIN_MESSAGE);
    MyMapPanel panel = new MyMapPanel();
    if(url != null)
    panel.setImageIcon(ic);
    MyMapPanel mp = new MyMapPanel(ic);
    MyPanel panel2 = new MyPanel();
    //MyMapPanel mp2 = new MyMapPanel();
    JFrame jf = new JFrame();
    f = new MyJFrame(700,400);
    f.getContentPane().add(mp);
    //f.getContentPane().add(panel2);
    public static class MyJFrame extends JFrame {
    // Constructor.
    public MyJFrame (int width, int height)
    // Set the title and other frame parameters.
    this.setTitle ("GPS Map");
    this.setResizable (true);
    this.setSize (width, height);
    // Create and add the panel.
    MyMapPanel panel = new MyMapPanel();
    //MyPanel p = new MyPanel();
    //this.getContentPane().add (panel);
    this.getContentPane().add(panel);
    // Show the frame.
    this.setVisible (true);
    }

    Hi,
    I'm sorry that I didn't use the buttons to make the code readable for you. and I'm sure you don't want to hear how hectic my mind has been for the past few weeks, so I'm not going to explain why I didn't pay attention to the formatting. Although, I think it could have been possible to address my mistake in a less aggressive manner.
    Here's my code in a better readable format. I appreciate your advice, it looks so much better now. I'd very much appreciate it if you can go over it.
    In regards to your previous solution, I have to say that I've tried it before, but it hasn't worked for me, possibly because I'm not sure how to use it.
    * @author Nazli
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.Component;
    import java.awt.Image;
    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.ImageIcon;
    import java.net.*; // For class URL.
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.border.TitledBorder;
    import javax.swing.event.MouseInputAdapter;
    import java.applet.*;
    public class MyMapPanel extends JPanel implements DataTurbineListener, MouseListener, ImageObserver
    final static String newline = "\n";
    JTextArea textArea; //= new JTextArea();
    public static String url;
    public static ImageIcon ic;
    public static ImageIcon ic2 = new ImageIcon("http://www-jkn.ee.uec.ac.jp/tnklab/96/nakazawa/icons/colorball/small /BALL120.gif");
    public static JLabel mapArea;
    //public static JApplet mapArea;
    //public static File output = new File("results.txt");
    public static boolean showPoint;
    public static int x;
    public static int y;
    private BufferedImage bufImg ;
    private Image smallImg ;
    int w;
    int h;
    /*public static BufferedImage bufImg ;
    public static Image smallImg ; */
    /* GeneralPath path;
    final int PAD = 20;
    final int N = 8; */
    public static MyJFrame f;
    public MyMapPanel() {}
    public MyMapPanel(ImageIcon ic)
    super(new FlowLayout (FlowLayout.CENTER, 0,0));
    textArea = new JTextArea();
    setImageIcon(ic);
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea);
    add(scrollPane);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(700,100));
    //getContentPane().add(new MyPanel(), BorderLayout.CENTER);
    //addMouseListener( new MusClk() ) ;
    protected class MusClk extends MouseAdapter {
    public void mouseClicked ( MouseEvent musEvt ) {
    if( musEvt.getX() > bufImg.getWidth() || musEvt.getY() > bufImg.getHeight() ) {
    return ;
    Graphics g = bufImg.getGraphics() ;
    int w = smallImg.getWidth( null ) ;
    int h = smallImg.getHeight( null ) ;
    g.drawImage( smallImg , musEvt.getX() - w / 2 , musEvt.getY() - h / 2 , null ) ;
    MyMapPanel.this.repaint( musEvt.getX() - w / 2 , musEvt.getY() - h / 2 , w , h ) ;
    public ImageIcon getImageIcon()
    setImageIcon(ic);
    return ic;
    public void setImageIcon(ImageIcon ic)
    //MyPanel panel = new MyPanel();
    try{
    URL u = new URL(url);
    ic = new ImageIcon(u);
    } catch (MalformedURLException e) {
    System.out.println (e);
    mapArea = new JLabel(ic, JLabel.CENTER);
    add(mapArea);
    mapArea.addMouseListener(this);
    try {
    URL u = new URL(url);
    ic = new ImageIcon(u);
    } catch (MalformedURLException e){
    System.out.println(e);
    mapArea = new JApplet();
    add(mapArea);
    mapArea.addMouseListener(this); */
    /* public void setMouseEvent(MouseEvent e)
    x = e.getX();
    y = e.getY();
    showPoint = true;
    protected void paintComponent(Graphics g){ }
    public void dataTurbineOutputEvent(DataTurbineEvent event){}
    public void dataTurbineInputEvent(DataTurbineEvent event){}
    public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) { }
    public void mouseClicked(MouseEvent e)
    //setMouseEvent(e);
    //System.out.println("x="+x+" y="+y);
    showPoint = true;
    ImageIcon icon = new ImageIcon("C:/Documents and Settings/Nazli/My Documents/My Pictures/ball.gif");
    w = icon.getIconWidth();
    h = icon.getIconHeight();
    bufImg = new BufferedImage(w , h , BufferedImage.TYPE_INT_RGB ) ;
    Graphics g = bufImg.getGraphics();
    g.drawImage( icon.getImage() , 0 , 0 , null ) ;
    //MyMapPanel.this.repaint(e.getX() - w / 2 , e.getY() - h / 2 , w , h ) ;
    /*Point p = e.getPoint();
    Rectangle tag;
    final int SIDE = 6;
    tag = new Rectangle(0, 0, SIDE, SIDE);
    float x = e.getX();
    float y = e.getY();
    tag.setLocation(p.x - SIDE/2, p.y - SIDE/2);
    if(tag.contains(p.x,y))
    showPoint = true;
    setPoint(p);
    //System.out.println("e.getX="+e.getX()+""+"e.getY="+e.getY());
    saySomething("Position in pixels:(" + e.getX() + ", " + e.getY() + ")", e);
    String s1 = computeLatLong(e.getX());
    String s2 = computeLatLong(e.getY());
    saySomething("Position in Lat/Long: (" + s1 + ", " + s2 + ")", e);
    //g.drawImage(img, e.getX(), e.getY(), this);
    //DrawImage d = new DrawImage();
    //public void mouseClicked ( MouseEvent musEvt ) {
    //DrawImage d = new DrawImage();
    void saySomething(String eventDescription, MouseEvent e)
    textArea.append(eventDescription + " detected on " + e.getComponent().getClass().getName() + "." + newline);
    textArea.setCaretPosition(textArea.getDocument().getLength());
    public String computeLatLong(double d)
    double d1;
    double seconds;
    double minutes;
    double m;
    double s;
    String rval;
    d1 = d - Math.floor(d);
    seconds = d1 / 3600;
    minutes = seconds / 60;
    m = minutes - Math.floor(minutes);
    s = m * 60; //minutes converted to seconds
    rval = (int)Math.floor(d) + "deg " + (int)minutes + "' " + (int)s + '"';
    return rval;
    public MyJFrame getFrame()
    return f;
    public static void main(String[] args) throws IOException {
    //DrawImage d = new DrawImage();
    System.out.println("x="+x+" y="+y);
    ArrayList file = new ArrayList();
    File input = new File("lat_lon.txt");
    FileReader in = new FileReader(input);
    File output = new File("archive3.txt");
    FileWriter out = new FileWriter(output);
    //FileWriter in2 = new FileWriter(input);
    FileOutputStream outdata = new FileOutputStream(output);
    PrintStream p = new PrintStream(outdata);
    BufferedReader br = new BufferedReader(in, 4096);
    BufferedWriter bw = new BufferedWriter(new FileWriter("lat_lon.txt", true));
    String line; //each line in input file
    String s=null; //Main string containing points information, to be written to the output file
    while ((line = br.readLine()) != null )
    file.add(line);
    StringTokenizer st = new StringTokenizer(line,";");
    while(st.hasMoreTokens())
    s = st.nextToken();
    p.println(s);
    p.println("FINISHED DATA TRANSFER");
    p.println("\n");
    bw.write("DATA TRANSFERRED TO OUTPUT FILE");
    bw.newLine();
    bw.flush();
    p.close();
    //pops up the input dialogue window for the user to enter the image URL
    url = JOptionPane.showInputDialog(null,"Provide image URL:\n","Map Image", JOptionPane.PLAIN_MESSAGE);
    MyMapPanel panel = new MyMapPanel();
    if(url != null)
    panel.setImageIcon(ic);
    MyMapPanel mp = new MyMapPanel(ic);
    MyPanel panel2 = new MyPanel();
    //MyMapPanel mp2 = new MyMapPanel();
    JFrame jf = new JFrame();
    f = new MyJFrame(700,400);
    f.getContentPane().add(mp);
    //f.getContentPane().add(panel2);
    public static class MyJFrame extends JFrame {
    // Constructor.
    public MyJFrame (int width, int height)
    // Set the title and other frame parameters.
    this.setTitle ("GPS Map");
    this.setResizable (true);
    this.setSize (width, height);
    // Create and add the panel.
    MyMapPanel panel = new MyMapPanel();
    //MyPanel p = new MyPanel();
    //this.getContentPane().add (panel);
    this.getContentPane().add(panel);
    // Show the frame.
    this.setVisible (true);
    }

  • How can you get  the public variables from object that extends JLabel?

    I'm using the mouseClickedListener method e.getComponent(); to get the component that is clicked on the sceen. The component i clicked is type "object" and extends a jlabel, and i really need to acces a variable from it. Heres the code i'm using-
    MouseListener listenerDown=new java.awt.event.MouseListener() {
            public void mousePressed(MouseEvent e){
                paintAll();
                mX=e.getX();
                mY=e.getY();
            public void mouseClicked(MouseEvent e) {
                Component c = e.getComponent();
                drawResizeBox(c);
                selected=c;
            public void mouseReleased(MouseEvent e) {
            public void mouseEntered(MouseEvent e) {
            public void mouseExited(MouseEvent e) {
    package javapoint;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.geom.Line2D;
    import java.awt.image.BufferedImage;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    public class object extends JLabel{
        public object(Rectangle rect,int id){
            idNum=id;
            Rect=rect;
            BufferedImage image = new BufferedImage((int)rect.getWidth()+1, (int)rect.getHeight()+1, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = (Graphics2D) image.getGraphics();       
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.drawRect((int)rect.getX(), (int)rect.getY(), (int)rect.getWidth(), (int)rect.getHeight());
            Icon icon = new ImageIcon((Image)image);
            setIcon(icon);
            setBounds((int)rect.getX()-1, (int)rect.getY()-1, (int)rect.getWidth()+1, (int)rect.getHeight()+1);
            mainFrame.slideArr[mainFrame.sIndx].add(this);
            setVisible(true);
            r=true;       
        object(Oval oval,int id){
            idNum=id;       
            setBounds(oval.getX(), oval.getY(), oval.getWidth(), oval.getHeight());
            getGraphics().drawOval(oval.getX(), oval.getY(), oval.getWidth(), oval.getHeight());
            o=true;
            setVisible(true);
        object(Line2D line,int id){
            idNum=id;       
            setBounds((int)line.getX1(), (int)line.getY1(), (int)line.getX2(), (int)line.getY2()); //Not gunna work
            getGraphics().drawLine((int)line.getX1(), (int)line.getY1(), (int)line.getX2(), (int)line.getY2());
            l=true;
            setVisible(true);
        object(Icon icon,int id){
            idNum=id;
            setIcon(icon);
            setBounds(50,50,icon.getIconWidth(),icon.getIconHeight());
            i=true;
            setVisible(true);
        void drawObject(object obj){
            if(r){
                Rectangle rect=obj.Rect;
                setBounds((int)rect.getX()-1, (int)rect.getY()-1, (int)rect.getWidth()+1, (int)rect.getHeight()+1);          
                Rect=rect;
                BufferedImage image = new BufferedImage((int)rect.getWidth()+1, (int)rect.getHeight()+1, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g = (Graphics2D) image.getGraphics();           
                g.setColor(Color.red);
                g.drawRect(0, 0, (int)rect.getWidth(), (int)rect.getHeight());           
                Icon icon = new ImageIcon((Image)image);
                setIcon(icon);
            }else if(l){
            }else if(o){
            }else if(i){
        public boolean r=false;
        public Rectangle Rect;
        public boolean o=false;
        public Oval Oval;
        public boolean l=false;
        public Line2D Line;
        public boolean i=false;
        public Icon Icon;
        public JLabel label;
        public int idNum;
    }Edited by: ghostbust555 on Feb 12, 2010 2:14 PM

    ghostbust555 wrote:
    Well see the problem is i have an array of 200 objects.What does that have to do with anything? And if it does, why isn't it in the code you posted?
    I dont understand what you mean in your "Edit..." part. could you show some code/ explain farther? sorry if its a dumb question I'm still a bit of a novice at java.Yeah.
    object yuck = (object) e.getComponent(); // That's a cast.
    boolean yucksR = yuck.r; // Get the "r" variable from the object.

  • JLabel on JButton does always show ...

    Hi guys, i tried the following stuff
    myButton.setPreferredSize(new Dimension(100,60));
              myLabel = new JLabel("");
              myLabel.setPreferredSize(myButton.getPreferredSize());
              myButton.add(myLabel);the problem is whenever i access the
    myButton.myLabel.setText("sometext"); via my actionlistener it sets its text to ... instead of showing me its content
    and i am sure the content would fit as its a THREE CHAR code...
    thanks in advance
    PS: i generate a grid of buttons with " " caption, when someone clicks the button the text on the button changes! (i use JLabels cause i want to exchange the changing text to images later!)

    i moved one step further and put the images in already
    works like charm and does what i expect it to do
    i saw that JButton can hold an icon without jlabel (dunno why i overlooked this the day before...)
    you are right, i can add the actionlistener to the class and assign the class itself.
    further i replaced Applet by JApplet and the refrehs works with any more line of code... only had to change the import and add the J infront of Applet nice
    thanks for your help!!
    here is my 'final' code
    package wii.tanks.leveleditor.view;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    //import java.awt.Component;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.awt.Color;
    import java.awt.event.*;
    import javax.swing.ImageIcon;
    import java.net.URL;
    import java.awt.Dimension;
    // information from normal wii.tanks.model.Entity
    class lvlEntity extends JButton implements ActionListener {
         final static long serialVersionUID = 1;
         public int currentEntity = 1;
         private JLabel myLabel;
         public int height = 0;
         public int destroyable = 0;
         public static final int NORMAL = 0; // floor
         public static final int BOX_NORMAL = 1;
         public static final int BOX_REFLECTS = 2;
         public static final int BOX_EXPLODES = 3;
         public static final int BOX_CRUSHER = 4;
         public static final int HOLE = 10;     // can't pass you will die instantly
         public static final int MUD = 11;       // pass-able but will slow you down
         public static final int[]       i_entities = {lvlEntity.NORMAL,     lvlEntity.BOX_NORMAL,     lvlEntity.BOX_REFLECTS,     lvlEntity.BOX_EXPLODES, lvlEntity.BOX_CRUSHER, lvlEntity.HOLE, lvlEntity.MUD};
         //public static final String[] s_entities = {"  ",                    "",                         "<B>",                         ">B<",                          "}B{",                          "(O)",                "MUD"};
         public static final String[] s_entities = {"1","2","3","4","5","6","7"};
         public static final String[] src_entities = {"FLOOR_1.png", "BOX_NORMAL_1.png","BOX_REFLECT_1.png","BOX_EXPLODES_1.png","BOX_CRUSHER_1.png","HOLE.png","MUD.png"};
         public static ImageIcon icon_entities[] = null;     
         public lvlEntity() {
              JPanel pane = (JPanel)this.getParent();
              this.setIcon(createImageIcon("file:///"+System.getProperty("user.dir")+"\\wii\\tanks\\leveleditor\\res\\"+src_entities[0], src_entities[0]));
              this.addActionListener(this);
         /** Returns an ImageIcon, or null if the path was invalid. */
         protected ImageIcon createImageIcon(String path, String description) {
              try {
              URL imgURL = new URL(path);
              if (imgURL != null) {
              return new ImageIcon(imgURL, description);
              } else {
              System.err.println("Couldn't find file: " + path);
              return null;
              } catch (Exception e) {System.out.print(e.getLocalizedMessage());}
              return null; // you never reach this
         public void actionPerformed(ActionEvent e) {
              lvlEntity src = (lvlEntity)e.getSource();
              src.setIcon(createImageIcon("file:///"+System.getProperty("user.dir")+"\\wii\\tanks\\leveleditor\\res\\"+src_entities[currentEntity], src_entities[currentEntity]));
              System.out.println("file:///"+System.getProperty("user.dir")+"\\wii\\tanks\\leveleditor\\res\\"+src_entities[currentEntity]);
              currentEntity = (currentEntity+1)%(s_entities.length);
    /*public*/
    class BattlefieldGui extends JPanel{
         final static long serialVersionUID = 0;
         Font font;
         public BattlefieldGui(int aSizeHeight, int aSizeWidth) {
         setLayout(new GridLayout(aSizeHeight, aSizeWidth));
         font = new Font("Helvetca", Font.PLAIN, 12);
         for (int i =1; i<=aSizeHeight;i++) {
              for (int j =1; j<=aSizeWidth;j++) {
                   addEntity(i+"|"+j);
         void addEntity(String name) {
              lvlEntity entity = new lvlEntity();
         entity.setBackground(new Color(120,120,120));
         entity.setName(name);
         setFont(font);
         add(entity);
         public class Battlefield extends JApplet {
         public void init() {
         add(new BattlefieldGui(17,17));
         this.setSize(440, 600);
    Edited by: [email protected] on Dec 31, 2007 3:47 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Drawing a rectangle on an Image embedded in a JLabel

    hey everybody,
    I'm trying to implement a program that can select parts of an image using a rectangle that's formed while the mouse is dragging. The image is embedded within the JLabel and I have already overriden the paintcomponents method. So far, I'm able to draw lines and shapes on the image before the program runs. But I need to be able to draw in real time and I don't know how to do that. Can someone please help me? Thanks a lot.
    Here's my code if anyone wants to look at it:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    import javax.imageio.*;
    public class test{
         static int x1, y1, x2,y2;
         static boolean drawing;     
         static Graphics gr;
         public static void main(String[] args){
         JFrame jframe = new JFrame();
         jframe.setSize(1000,800);
         jframe.setVisible(true);
              WindowListener c = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              jframe.addWindowListener(c);
         ImageIcon icon = new ImageIcon("c:/60.jpg");
         Image i = icon.getImage();
         JLabel lab = new JLabel(icon)
              public void paintComponent(Graphics gr) {
                        super.paintComponent(gr);               
                        paints(gr);          
         MouseMotionListener drag = new MouseMotionAdapter() {
                        public void mouseDragged(MouseEvent e) {
                             x2 = e.getX();
                             y2 = e.getY();
                             drawing = true;
                             //System.out.println(e.getX()+" "+e.getY());
         MouseListener click = new MouseAdapter() {
                   public void mousePressed(MouseEvent e) {
                        x1 = e.getX();
                        y1 = e.getY();
                        drawing = true;
                   public void mouseReleased(MouseEvent e) {
                        x2 = e.getX();
                        y2 = e.getY();
                        drawing = false;
         lab.addMouseMotionListener(drag);
         lab.addMouseListener(click);
         JPanel pan = new JPanel();
         pan.add(lab);
         jframe.getContentPane().add(pan);
         jframe.setVisible(true);
    public static void paints (Graphics gr)
         Graphics2D write = (Graphics2D)gr;
                   write.setColor(Color.BLUE);
                   int x3 = Math.abs(x1-x2);
                   int y3 = Math.abs(y1-y2);
                   write.drawRect(x1,y1,x3,y3);
    }

    hey everybody,
    I'm trying to implement a program that can select parts of an image using a rectangle that's formed while the mouse is dragging. The image is embedded within the JLabel and I have already overriden the paintcomponents method. So far, I'm able to draw lines and shapes on the image before the program runs. But I need to be able to draw in real time and I don't know how to do that. Can someone please help me? Thanks a lot.
    Here's my code if anyone wants to look at it:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    import javax.imageio.*;
    public class test{
         static int x1, y1, x2,y2;
         static boolean drawing;     
         static Graphics gr;
         public static void main(String[] args){
         JFrame jframe = new JFrame();
         jframe.setSize(1000,800);
         jframe.setVisible(true);
              WindowListener c = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              jframe.addWindowListener(c);
         ImageIcon icon = new ImageIcon("c:/60.jpg");
         Image i = icon.getImage();
         JLabel lab = new JLabel(icon)
              public void paintComponent(Graphics gr) {
                        super.paintComponent(gr);               
                        paints(gr);          
         MouseMotionListener drag = new MouseMotionAdapter() {
                        public void mouseDragged(MouseEvent e) {
                             x2 = e.getX();
                             y2 = e.getY();
                             drawing = true;
                             //System.out.println(e.getX()+" "+e.getY());
         MouseListener click = new MouseAdapter() {
                   public void mousePressed(MouseEvent e) {
                        x1 = e.getX();
                        y1 = e.getY();
                        drawing = true;
                   public void mouseReleased(MouseEvent e) {
                        x2 = e.getX();
                        y2 = e.getY();
                        drawing = false;
         lab.addMouseMotionListener(drag);
         lab.addMouseListener(click);
         JPanel pan = new JPanel();
         pan.add(lab);
         jframe.getContentPane().add(pan);
         jframe.setVisible(true);
    public static void paints (Graphics gr)
         Graphics2D write = (Graphics2D)gr;
                   write.setColor(Color.BLUE);
                   int x3 = Math.abs(x1-x2);
                   int y3 = Math.abs(y1-y2);
                   write.drawRect(x1,y1,x3,y3);
    }

  • Jlabel

    HI ,
    I want to put icon on Jlabel , But icon image is bigger then the label size . I am not able to make the image fitting on the label .
    can any body help .
    Thanks

    The label must match the size of the ImageIcon it hosts. Alternatives are:
    1 &#8212; put the label in a JScrollPane whose preferredSize is set to the size you originally had the label set to
    2 &#8212; scale the image to the size of the label.

  • How to show icon  when draggin

    HI m
    my requirement is to show the icon of the dragging component's icon(currently jlabel with gif as icon )during drag and drop operations
    how to achieve this objective, as DnD api donot suppurt this thing
    [email protected]

    I normally use a calculated attribute inside the table's data source node for this.
    Add an attribute "Icon", type=string, calculated=true, read-only=true, under the data source node.
    (If the data source node uses structure binding and does not allow to add an attribute, add a helper value node instead, cardinality=1:1, selection=1:1, and add the attribute to this node.)
    In the get-method for the calculated attribute, you get the node element corresponding to the table row as parameter. Depending on other attributes in this node element, select an icon URL and return it.
    If you put your icons inside the src/mimes/<component> folder, you can simply return the file name of the icon.
    Don't use a Button as table cell editor but rather an Image or LinkToAction.
    Armin

  • Update Jcombobox 's label in render

    hi ,everybody, i have a problem about combobox, any body can help me!
    thank you!
    I want to have a combobox with checkbox as item, I rewrite a render writen by ice, because the combobox has three state, when I click diferent checkbox in this combobox , the label of combobox will update rightly, but if I click one checkbox to change the checkbox state ,the label will no update , it seem that when I click one checkbox many times .the menthod
    getListCellRendererComponent(JList list, Object value, int index,
                        boolean isSelected, boolean cellHasFocus)
    will no update label
    my code :
    mainclass:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.plaf.basic.BasicComboBoxEditor;
    public class mainclass {
          public static void main(String[] args) {
                 final testbox myComboBox = new testbox();
                 myComboBox.addItem("SelectAll");
                 myComboBox.addItem("ClearAll");
                 myComboBox.addItem("GrayedAll");
                 for(int i = 0; i < 5; i++) {
                     myComboBox.addItem("Item " + i);
                 JFrame frame = new JFrame("My ComboBox");
                 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                 frame.setSize(150, 60);
                 frame.setLocation(300, 300);
                 //frame.setJMenuBar( menubar );
                 JPanel panel=new JPanel();
                 panel.setLayout(new BorderLayout());
                 panel.add(myComboBox,BorderLayout.NORTH);        
                 frame.getContentPane().add(panel);
                 frame.setVisible(true);
                 final IconedCellRendererField renderer = IconedCellRendererField.getCheckBoxRendererInstance();
                 myComboBox.setRenderer(renderer);
                 myComboBox.addActionListener(new ActionListener()
                     public void actionPerformed(ActionEvent e)
                          if(myComboBox.getSelectedItem().toString().equals("SelectAll")){
                               renderer.selectAll(true);                         
                          if(myComboBox.getSelectedItem().toString().equals("ClearAll")){
                               renderer.clearAll(true);
                          if(myComboBox.getSelectedItem().toString().equals("GrayedAll")){
                               renderer.grayedAll(true);
    }renderer:
    import java.awt.*;
    import java.awt.event.*;
    //import java.io.*;
    //import java.net.*;
    import java.util.*;
    import javax.swing.*;
    //import javax.swing.event.*;
    import javax.swing.border.*;
    //import javax.swing.table.*;
    public class IconedCellRendererField extends DefaultListCellRenderer implements MouseListener {
         public Icon icon, selIcon;
         Icon[] icons = null;
         public boolean useIconBackground = true, useIndexSensitiveIcons = false,
                   useCheckBoxAsIcon = false, useLinkState = false;
         Dimension labelDim = null;
         public JLabel iconLabel;
         public JCheckBox box = null;
         public JPanel noback;
         public SelectionStateHandler selStateHandler = null;     
         private JList theList = null;
         public boolean[] selState = null, enableState = null;
         int offset = 5;
         Rectangle rect = null;
         int currentLinkRow = -1;
         boolean isOnRow = false, paintDivider = false;
         private Icon dividerImage = null;     
         private Color linkColor = Color.blue, hoverColor = Color.red, selectedLinkColor = Color.green;
         /* Initialises the renderer with one icon that is displayed without the
          * cell background.
         public IconedCellRendererField(Icon icon) {
              this(icon,false);
         /* Initialises the renderer with two icons that provide a switch capability
          * when a row is selected/deselected
         public IconedCellRendererField(Icon icon, Icon selIcon) {
              this.icon = icon;
              this.selIcon = selIcon;
              //addMouseListener(this);
         /* Initialises the renderer with two icons that provide a switch capability
          * when a row is selected/deselected. The boolean argument enables the icon
          * to either use the renderer background or appear transparent.
         public IconedCellRendererField(Icon icon, Icon selIcon, boolean useIconBackground) {
              this(icon, selIcon);
              setIconHasBackground(useIconBackground);
              createNoBackgroundPanel();
         /* Initialises the renderer with a single no siwthing icon. The boolean
          * argument enables the icon to either use the renderer background
          * or appear transparent.
         public IconedCellRendererField(Icon icon, boolean useIconBackground) {
              this(icon, icon, useIconBackground);
         /* Initialises the renderer to load two icons from the provided image locations.
          * This enables icon switching on selection.
         public IconedCellRendererField(String iconLoc, String selIconLoc) {
              icon = new ImageIcon(iconLoc);
              selIcon = new ImageIcon(selIconLoc);
              //addMouseListener(this);
         /* Initialises the renderer to load a single icon from the provided image location.
          * The icon can either have the renderer background or not based on the
          * boolean property.
         public IconedCellRendererField(String iconLoc, boolean iconBackground) {
              this(iconLoc, iconLoc, iconBackground);
         /* Initialises the renderer to load two icons from the provided image locations.
          * This enables icon switching on selection. The icon can either have the renderer
          * background or not based on the boolean property.
         public IconedCellRendererField(String iconLoc, String selIconLoc, boolean iconBackground) {
              this(iconLoc, selIconLoc);
              setIconHasBackground(iconBackground);
              createNoBackgroundPanel();
         /* Initialises the renderer to load a single icon from the provided image location.
         public IconedCellRendererField(String iconLoc) {
              this(iconLoc, true);
         /* Initialises the renderer with an array of image icons that are repeated for
          * each row in the list.
         public IconedCellRendererField(Icon[] icons, boolean useIconBackground) {
              this(icons[0], icons[0], useIconBackground);
         public void createNoBackgroundPanel() {
              iconLabel = new JLabel((Icon)null, JLabel.CENTER);
              if(labelDim != null) {      iconLabel.setPreferredSize(labelDim); }
              iconLabel.setBorder( new EmptyBorder(1,5,1,5) );
              noback = new JPanel( new BorderLayout() ) {
                  * Overridden for performance reasons.
                  * See the <a href="#override">Implementation Note</a>
                  * for more information.
                  //public void validate() {}
                 // public void invalidate() {}          
                  public void repaint() {}
                  //public void revalidate() {}
                  public void repaint(long tm, int x, int y, int width, int height) {}
                  public void repaint(Rectangle r) {}
                  protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
                        // Strings get interned...
                        if (propertyName == "text"
                                   || ((propertyName == "font" || propertyName == "foreground")
                                       && oldValue != newValue)) {
                            super.firePropertyChange(propertyName, oldValue, newValue);
                  public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {}
                  public void firePropertyChange(String propertyName, char oldValue, char newValue) {}
                  public void firePropertyChange(String propertyName, short oldValue, short newValue) {}
                  public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
                  public void firePropertyChange(String propertyName, long oldValue, long newValue) {}
                  public void firePropertyChange(String propertyName, float oldValue, float newValue) {}
                  public void firePropertyChange(String propertyName, double oldValue, double newValue) {}
                  public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
              if(useCheckBoxAsIcon()) {
                   box = new JCheckBox();
                   //box.addMouseListener(this);
                   box.setOpaque(false);
                   noback.add( box, BorderLayout.WEST );
                   //noback.addMouseListener(this);
                   rect = box.getBounds();
                   //list.addMouseListener(this);
              } else {
                   noback.add( iconLabel, BorderLayout.WEST );
              noback.add( this, BorderLayout.CENTER );
              noback.setBorder( new EmptyBorder(1,1,1,1) );
              noback.setOpaque(false);
         public Component getListCellRendererComponent(JList list, Object value, int index,
                        boolean isSelected, boolean cellHasFocus) {
              System.out.println(value+"+"+index+"+"+isSelected+"+"+cellHasFocus);
              if(theList == null || theList != list) {
                   theList = list;
                   if(useLinkState) {
                        attachLinkSimulationListener();
              setOpaque(true);
              setText( value == null ? "" : value.toString());
              if(useIndexSensitiveIcons) {
                   icon = getIcon(index);
              if(useIconBackground)
                   setIcon(icon);          
              setFont( list.getFont() );
              setToolTipText(value.toString() );
              if(list.isEnabled())
                   setEnabled( isEnabled(index) );
              else
                   setEnabled( list.isEnabled() );
              if(isSelected && isEnabled(index) ) {
                   setForeground( Color.black );
                   setBackground( new Color(223, 235, 245) );
                   if(useIndexSensitiveIcons) {
                        selIcon = getIcon(index);
                   if(useIconBackground)
                        setIcon(selIcon);
              } else {
                   setForeground(Color.black);
                   setBackground(Color.white);
                   setBorder(null);
              if(cellHasFocus) {
                   setBorder( new CompoundBorder( new LineBorder( new Color(150, 150, 220) ),
                                                      new EmptyBorder(2,2,2,2)  ) );
              } else {
                   setBorder( new EmptyBorder(2,2,2,2));
              if(useLinkState) {
                   if(currentLinkRow == index) {
                        setText("<html><u>" + value.toString()+"</u></html>" );     
                        setForeground( getHoverLinkColor() );               
                   } else {
                        setForeground( getLinkColor() );
                   if(isSelected) {
                        setForeground( getSelectedLinkColor() );
                   setBackground(Color.white);
                   setBorder( new EmptyBorder(1,1,1,1) );
              if( shdPaintDivider() ) {
                   Border border = null;
                   if(dividerImage != null) {
                        border = new MatteBorder(0,0,1,0, dividerImage);
                   } else {
                        border = new MatteBorder(0,0,1,0, getLinkColor() );
                   if(index < theList.getModel().getSize() - 1 ) {
                        setBorder( new CompoundBorder(getBorder(),border) );
                   } else {
                        setBorder( new EmptyBorder(1,1,1,1) );
              if(useIconBackground == false) {
                  if(isSelected)
                      iconLabel.setIcon(selIcon);
                  else
                      iconLabel.setIcon(icon);
                  if(useCheckBoxAsIcon()) {
                      if(selState == null) {
                          updateSelectionStateTrackers(list);
                      if(selStateHandler == null) {
                          list.addMouseListener( selStateHandler = new SelectionStateHandler(list) );
                      try {
                          box.setSelected( selState[index] );
                      } catch(Exception e) {}
                  if( shdPaintDivider() ) {              
                      //if(index < theList.getModel().getSize() - 1 ) {
                          noback.setBorder( getBorder() );
                          setBorder( new EmptyBorder(1,1,1,1) );
                      //} else {
                      //  noback.get
                  // this should cause a JComboBox to paint the Label instead of the
                  // check box + label combination
                  if(index == -1) {
                       Vector<Object> v=new Vector<Object>();
                       v=getSelectedObjects();
                        String val=generateString();
                       JLabel label=new JLabel(val);                    
                      if(iconLabel.getIcon() != null) {
                           label.setIcon( iconLabel.getIcon() );
                      System.out.println("label");
                      return label;
                  return noback;
              return this;
         public String generateString()
              String val = "";
              if(selState[0]==true&&selState[1]==false&&selState[2]==false){
                    for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(val.length()==0){
                                  val=val+curString+"-1";
                           } else {                              
                                  val=val+"&"+curString+"-1";
               //clear all     
               if(selState[1]==true&&selState[0]==false&&selState[2]==false ){                                   
                      for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(val.length()==0){
                                  val=val+curString+"-0";
                           } else {                              
                                  val=val+"&"+curString+"-0";
              //grayedall
               if(selState[2]==true&&selState[0]==false&&selState[1]==false ){                                   
                      val="";                      
               if(selState[0]==false&&selState[1]==false&&selState[2]==false ){
                    for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(selState==true&&enableState[i]==false){
                             continue;
                        if(selState[i]==true&&enableState[i]==true){
                             if(val.length()==0){
                                       val=val+curString+"-1";
                             } else {                              
                                       val=val+"&"+curString+"-1";
                        if(selState[i]==false&&enableState[i]==true){
                             if(val.length()==0){
                                       val=val+curString+"-0";
                             } else {                              
                                       val=val+"&"+curString+"-0";
              return val;
         public void updateSelectionStateTrackers(JList list) {
              selState = new boolean[ list.getModel().getSize() ];
              enableState = new boolean[ list.getModel().getSize() ];
              for(int i = 0; i < selState.length; i++) {
                   selState[i] = false;
                   enableState[i] = true;
         public int[] getSelectedIndices() {
              if(!useCheckBoxAsIcon()) {
                   return new int[0];
              int length = 0;
              if(selState==null){
                   return null;
              for(int i = 0; i < selState.length; i++) {
                   if(selState[i]) {
                        length++;
              int[] indices = new int[length];
              for(int i = 0, n = 0; i < selState.length; i++) {
                   if(selState[i]) {
                        indices[n++] = i;
              //System.out.println("Selected Indices.length = " + indices.length);
              return indices;
         public Vector<Object> getSelectedObjects() {
              int[] indices = getSelectedIndices();
              Vector<Object> objects = new Vector<Object>();
              if(indices==null){
                   return null;
              for(int i = 0; i < indices.length; i++) {
                   objects.addElement( theList.getModel().getElementAt(indices[i]) );
              return objects;
         public void setIconHasBackground(boolean b) {
              useIconBackground = b;
         public Icon[] getIcons() {
              return icons;
         public Icon getIcon(int index) {
              if(icons != null && icons.length == 0) {
                   return icon;
              if(icons != null && index > icons.length) {
                   index = index - (icons.length - 1);
              return icons[index];
         public void setIcons(Icon[] icons) {
              if(icons != null) {
                   useIndexSensitiveIcons = true;
              this.icons = icons;
         public void setIcon(Icon icon, int index) {
              if(icons != null && icons.length > 0) {
                   icons[index] = icon;
         public void setIconLabelDimension(Dimension dim) {
              labelDim = dim;
         public static IconedCellRendererField getCheckBoxRendererInstance() {
              IconedCellRendererField cr = new IconedCellRendererField(new EmptyIcon());
                   cr.setUseCheckBoxAsIcon(true);
              return cr;
         public void setUseCheckBoxAsIcon(boolean use) {
              useCheckBoxAsIcon = use;
              createNoBackgroundPanel();
         public boolean useCheckBoxAsIcon() {
              return useCheckBoxAsIcon;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
         public void setDisplayItemsAsLinks(boolean use) {
              useLinkState = use;
         public void setLinkColor(Color color) {
              linkColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getLinkColor() {
              return linkColor;
         public void setHoverLinkColor(Color color) {
              hoverColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getHoverLinkColor() {
              return hoverColor;
         public void setSelectedLinkColor(Color color) {
              selectedLinkColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getSelectedLinkColor() {
              return selectedLinkColor;
         public void attachLinkSimulationListener() {
              theList.setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) );
              theList.addMouseListener( new MouseAdapter() {
                   public void mouseEntered(MouseEvent e) {
                        isOnRow = true;                    
                   public void mouseExited(MouseEvent e) {
                        isOnRow = false;
    currentLinkRow = -1;
    theList.repaint();
              theList.addMouseMotionListener( new MouseMotionAdapter() {
                   public void mouseMoved(MouseEvent e) {
    isOnRow = true;
    currentLinkRow = theList.locationToIndex( e.getPoint() );
    theList.repaint();
              /*table.addMouseListener(new MouseAdapter() {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    isOnRow = false;
    currentHighlightRow = -1;
    table.repaint();
    table.addMouseMotionListener( new MouseMotionAdapter() {
    public void mouseMoved(MouseEvent e) {
    isOnRow = true;
    currentHighlightRow = table.rowAtPoint( e.getPoint() );
    table.repaint();
         public boolean shdPaintDivider() {
              return paintDivider;
         public void setPaintDivider(boolean paintDivider) {
              this.paintDivider = paintDivider;
         public void setDividerImage(Icon icon) {
              this.dividerImage = icon;
              setPaintDivider(true);
         private void dispatchEvent(MouseEvent me) {
    if(rect != null && box != null && rect.contains(me.getX(), me.getY())){
    Point pt = me.getPoint();
    pt.translate(0,0);
    box.setBounds(rect);
    box.dispatchEvent(new MouseEvent(box, me.getID()
    , me.getWhen(), me.getModifiers()
    , pt.x, pt.y, me.getClickCount()
    , me.isPopupTrigger(), me.getButton()));
    if(!box.isValid()) {
         repaint();
         System.out.println("Dispatch Event: Box.invalid called");
    System.out.println("Dispatch Event called");
    } else {
         System.out.println("Dispatch Event Called, rect null");
    public void mouseClicked(MouseEvent me){
    dispatchEvent(me);
    public void mouseEntered(MouseEvent me){
    dispatchEvent(me);
    public void mouseExited(MouseEvent me){
    dispatchEvent(me);
    public void mousePressed(MouseEvent me){
    dispatchEvent(me);
    public void mouseReleased(MouseEvent me){
    dispatchEvent(me);
    public class SelectionStateHandler extends MouseAdapter {
         JList list = null;
         public SelectionStateHandler(JList list) {
              this.list = list;
         public void mouseClicked(MouseEvent e)
              * Handles the checkbox selection process. Uses the bounds property of the
              * check box within the selected cell to determine whether the checkbox should
              * be selected or not
              public void mouseReleased(MouseEvent e) {
                   /*if(list == null || list.getSelectedIndex() == -1
         || !isEnabled( list.locationToIndex(e.getPoint()) ) ) {
         return;
              if(list == null || list.getSelectedIndex() == -1){
                   return;
         int[] indices = list.getSelectedIndices();
         // get the current relative position of the check box
         //rect = box.getBounds(rect);
         for(int i = 0; i < indices.length; i++) {
         // get the current relative position of the check box
         int loc = list.locationToIndex( e.getPoint() );
         rect = list.getCellBounds(loc,loc);
         // ensure the point clicked in within the checkBox
         if(e.getX() < (rect.getX() + 20) ) {
              Object obj=list.getModel().getElementAt(i);
              //if(!obj.equals("SelectAll")&&!obj.equals("ClearAll")&&!obj.equals("GrayedAll")){
                   if(indices[i]>2){
                        selState[0]=false;
                        selState[1]=false;
                        selState[2]=false;
                        //����
                        if(!this.isEnabled(indices[i])&&selState[indices[i]]==true){
                             this.setEnabled(indices[i],true);
                             selState[indices[i]]=false;
                        } else if(this.isEnabled(indices[i])&&selState[indices[i]]==true){
                             //����
                             selState[indices[i]]=true;
                             this.setEnabled(indices[i],false);                              
                        }else if(this.isEnabled(indices[i])&&selState[indices[i]]==false){
                             //����
                             selState[indices[i]]=true;
                             this.setEnabled(indices[i],true);
                   } else {
                        selState[indices[i]] = !selState[indices[i]];
         list.revalidate();
         list.repaint();
         public void selectAll(boolean b) {
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        this.enableAll(true);
                        Object obj=list.getModel().getElementAt(i);
                        if(!obj.equals("ClearAll")&&!obj.equals("GrayedAll")){
                             selState[i] = b;
                        } else{
                             selState[i]=!b;
                        selState[0]=false;
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void clearAll(boolean b){
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        Object obj=list.getModel().getElementAt(i);
                        this.enableAll(true);
                        if(!obj.equals("ClearAll")){
                             selState[i] = !b;
                        } else{
                             selState[i]=b;
                        selState[1]=false;
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void grayedAll(boolean b){
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        Object obj=list.getModel().getElementAt(i);
                        if(!obj.equals("SelectAll")&&!obj.equals("ClearAll")){
                             if(i==2){
                                  selState[i] = !b;
                             }else{                             
                                  selState[i] = b;
                             this.setEnabled(i,false);
                        } else{
                             selState[i]=!b;                          
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void setSelectedIndex(int index) {
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   selState[i] = false;
              selectIndex(index);
         public void selectIndex(int index) {
              try {
                   selState[index] = true;
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   selectIndex(index);
                   return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void setEnabled(int index, boolean b) {
              try {
                   enableState[index] = b;
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   setEnabled(index, b);
         public boolean isEnabled(int index) {
              if(index == -1) {
                   return true;
              boolean isEnabled = true;
              try {
                   isEnabled = enableState[index];
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   return isEnabled(index);
              return isEnabled;
         public void enableAll(boolean b) {
              for(int i = 0; i < enableState.length; i++) {
                   enableState[i] = b;
    public void selectAll(boolean b) {
         if(selStateHandler == null) {
              return;
         selStateHandler.selectAll(b);
    public void clearAll(boolean b){
         if(selStateHandler == null) {
              return;
         selStateHandler.clearAll(b);
    public void grayedAll(boolean b){
         if(selStateHandler == null) {
              return;
         selStateHandler.grayedAll(b);
    public void setSelectedIndex(int index) {
         if(selStateHandler == null) {
              return;
         selStateHandler.setSelectedIndex(index);
    public void selectIndex(int index) {
         if(selStateHandler == null) {
              return;
         selStateHandler.selectIndex(index);
    public void enableAll(boolean b) {
         if(selStateHandler == null) {
              return;
         selStateHandler.enableAll(b);
    public void setEnabled(int index, boolean enable) {
         if(selStateHandler == null) {
              return;
         selStateHandler.setEnabled(index, enable);
    public boolean isEnabled(int index) {
         if(selStateHandler == null) {
              return true;
         return selStateHandler.isEnabled(index);
    public boolean isEnabledAll() {
         if(enableState == null) return true;
         for(int i = 0; i < enableState.length; i++) {
              if(!isEnabled(i)) {
                   return false;
         return true;
    // EmptyIcon implementation
    public static class EmptyIcon implements Icon {
         int width = 16, height = 16;
         public EmptyIcon() {
         setSize(16,16);
         public EmptyIcon(int width, int height) {
         setSize(width, height);
         public void setSize(int width, int height) {
         this.width = width;
         this.height = height;
         public int getIconWidth() {  return width; }
         public int getIconHeight() { return height; }
         public void paintIcon(Component c, Graphics g, int x, int y) {}
    public int getItemCount(){
         if(theList!=null){
              return theList.getModel().getSize();
         } else {
              return 0;
         public boolean[] getEnableState() {
              return enableState;
         public boolean[] getSelState() {
              return selState;
         public JList getTheList() {
              return theList;
    testbox :import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    public class testbox extends JComboBox
    * @param args
    JComboBox myComboBox;
    public testbox()
    myComboBox = new JComboBox();
    public void setPopupVisible(boolean b)
         if(b)
              myComboBox.showPopup();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

    You are updating the label value when (index == -1), let change into (index<=0).
    like below
    // this should cause a JComboBox to paint the Label instead of the
                // check box + label combination
                if (index <= 0) {
                    Vector v = new Vector();
                    v = getSelectedObjects();
                    String val = generateString();
                    JLabel label = new JLabel(val);
                    if (iconLabel.getIcon() != null) {
                        label.setIcon(iconLabel.getIcon());
                    System.out.println("label");
                    return label;
                }

  • Trying to do something very strange with layouts and painting components

    I'm trying to do something very strange with changing the layout of a container, then painting it to a bufferedImage and changing it back again so nothing has changed. However, I am unable to get the image i want of this container in a new layout. Consider it a preview function of the different layouts. Anyway. I've tried everything i know about swing and have come up empty. There is probably a better way to do what i am trying to do, i just don't know how.
    If someone could have a look perhaps and help me out i would be much appreciative.
    Here is a self contained small demo of my conundrum.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.BoxLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.border.LineBorder;
    // what is should do is when you click on the button "click me" it should place a image on the panel of the buttons in a
    // horizontal fashion. Instead it shows the size that the image should be, but there is no image.
    public class ChangeLayoutAndPaint
         private static JPanel panel;
         private static JLabel label;
         public static void main(String[] args)
              // the panel spread out vertically
              panel = new JPanel();
              panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
              // the buttons in the panel
              JButton b1, b2, b3;
              panel.add(b1 = new JButton("One"));
              panel.add(b2 = new JButton("Two"));
              panel.add(b3 = new JButton("Three"));
              b1.setEnabled(false);
              b2.setEnabled(false);
              b3.setEnabled(false);
              // the label with a border around it to show size in a temp panel with flowlayout to not stuff around
              // with the actual size we want.
              JPanel thingy = new JPanel();
              label = new JLabel();
              label.setBorder(new LineBorder(Color.black));
              thingy.add(label);
              // the button to make things go
              JButton button = new JButton("click me");
              button.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e)
                        //change layout
                        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
                        panel.doLayout();
                        //get image
                        BufferedImage image = new BufferedImage(panel.getPreferredSize().width, panel.getPreferredSize().height, BufferedImage.TYPE_INT_ARGB);
                        Graphics2D g = image.createGraphics();
                        panel.paintComponents(g);
                        g.dispose();
                        //set icon of jlabel
                        label.setIcon(new ImageIcon(image));
                        //change back
                        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
                        panel.doLayout();
              // the frame
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(400,200);
              frame.setLocation(100,100);
              frame.getContentPane().add(panel, BorderLayout.NORTH);
              frame.getContentPane().add(thingy, BorderLayout.CENTER);
              frame.getContentPane().add(button, BorderLayout.SOUTH);
              frame.setVisible(true);
    }

    Looks like you didn't read the API for Container#doLayout().
    Causes this container to lay out its components. Most programs should not call this method directly, but should invoke the validate method instead.
    There's also a concurrency issue here in that the panel's components may be painted to the image before revalidation completes. And your GUI, like any Swing GUI, should be constructed and shown on the EDT.
    Try this for size -- it could be better, but I've made the minimum possible changes in your code:import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.BoxLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.border.LineBorder;
    public class ChangeLayoutAndPaint {
      private static JPanel panel;
      private static JLabel label;
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            // the panel spread out vertically
            panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            // the buttons in the panel
            JButton b1, b2, b3;
            panel.add(b1 = new JButton("One"));
            panel.add(b2 = new JButton("Two"));
            panel.add(b3 = new JButton("Three"));
            b1.setEnabled(false);
            b2.setEnabled(false);
            b3.setEnabled(false);
            // the label with a border around it to show size in a temp panel with flowlayout to not stuff around
            // with the actual size we want.
            JPanel thingy = new JPanel();
            label = new JLabel();
            // label.setBorder(new LineBorder(Color.black));
            thingy.add(label);
            // the button to make things go
            JButton button = new JButton("click me");
            button.addActionListener(new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent e) {
                //change layout
                panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
                //panel.doLayout();
                panel.revalidate();
                SwingUtilities.invokeLater(new Runnable() {
                  @Override
                  public void run() {
                    //get image
                    BufferedImage image = new BufferedImage(panel.getPreferredSize().width,
                        panel.getPreferredSize().height, BufferedImage.TYPE_INT_ARGB);
                    Graphics2D g = image.createGraphics();
                    panel.paintComponents(g);
                    g.dispose();
                    //set icon of jlabel
                    label.setIcon(new ImageIcon(image));
                    //change back
                    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
                    //panel.doLayout();
                    panel.revalidate();
            // the frame
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 200);
            frame.setLocation(100, 100);
            frame.getContentPane().add(panel, BorderLayout.NORTH);
            frame.getContentPane().add(thingy, BorderLayout.CENTER);
            frame.getContentPane().add(button, BorderLayout.SOUTH);
            frame.setVisible(true);
    }db
    edit I prefer this:import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class LayoutAndPaint {
      JPanel panel;
      JLabel label;
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new LayoutAndPaint().makeUI();
      public void makeUI() {
        JButton one = new JButton("One");
        JButton two = new JButton("Two");
        JButton three = new JButton("Three");
        one.setEnabled(false);
        two.setEnabled(false);
        three.setEnabled(false);
        panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(one);
        panel.add(two);
        panel.add(three);
        label = new JLabel();
        JButton button = new JButton("Click");
        button.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            layoutAndPaint();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.add(panel, BorderLayout.NORTH);
        frame.add(label, BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      private void layoutAndPaint() {
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        panel.revalidate();
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            BufferedImage image = new BufferedImage(panel.getPreferredSize().width,
                panel.getPreferredSize().height, BufferedImage.TYPE_INT_ARGB);
            Graphics g = image.createGraphics();
            panel.paintComponents(g);
            g.dispose();
            label.setIcon(new ImageIcon(image));
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            panel.revalidate();
    }db
    Edited by: DarrylBurke

  • The logical problem in turnover in  for ?

    Welcome
    wrote this code, everything is true but there is a logical problem to be solved first idea of this program is a moving train to the contrary, it can stop and operated once again and that can add cars and locomotives and can delete it but there is a problem when adding that the train carriages have remained stable cart after the first turnover Thus ...
    THAT shows us the error ..
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Train extends JFrame implements ActionListener{
        private boolean check = false;
        private boolean stopped = true;
        private boolean add = false;
        private int trainPlace = 0;
        private int INDEX_START = 0;
        public int speed = 300;
        private ImageIcon CurrentImage ;
        private boolean front=true, back=false ;
        private int carrNum = 0 ;
        private JPanel screen, area , controlroom;
        private JButton[][] street;
        public JButton[] keybord;
        private String s[] = {"Start","Back","Fast","Slow","Add Carriage","Delete Carriage","Rest","Check","Desiners"};
        private ImageIcon images[][] ={{
                        new ImageIcon("images/UpRight.jpg"),
                        new ImageIcon("images/RightDown.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        {new ImageIcon("images/Vert.jpg"),
                        new ImageIcon("images/DownRight.jpg"),
                        new ImageIcon("images/Horiz.jpg"),
                        new ImageIcon("images/RightDown.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/Vert.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/Vert.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/Vert.jpg"),
                        new ImageIcon("images/UpRight.jpg"),
                        new ImageIcon("images/Horiz.jpg"),
                        new ImageIcon("images/RightUp.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/DownRight.jpg"),
                        new ImageIcon("images/RightUp.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg")}};
        private ImageIcon frontImagesTrain[]={
                        new ImageIcon("images/TrainDown.jpg"),
                        new ImageIcon("images/TrainDown.jpg"),
                        new ImageIcon("images/TrainLeft.jpg"),
                        new ImageIcon("images/TrainLeft.jpg"),
                        new ImageIcon("images/TrainDown.jpg"),
                        new ImageIcon("images/TrainLeft.jpg"),
                        new ImageIcon("images/TrainUp.jpg"),
                        new ImageIcon("images/TrainUp.jpg"),
                        new ImageIcon("images/TrainUp.jpg"),
                        new ImageIcon("images/TrainUp.jpg"),
                        new ImageIcon("images/TrainRight.jpg"),
                        new ImageIcon("images/TrainDown.jpg"),
                        new ImageIcon("images/TrainRight.jpg"),
                        new ImageIcon("images/TrainDown.jpg")};
            private ImageIcon trackImagesTrain[]={
                    new ImageIcon("images/Vert.jpg"),
                    new ImageIcon("images/RightUp.jpg"),
                    new ImageIcon("images/Horiz.jpg"),
                    new ImageIcon("images/UpRight.jpg"),
                    new ImageIcon("images/RightUp.jpg"),
                    new ImageIcon("images/DownRight.jpg"),
                    new ImageIcon("images/Vert.jpg"),
                    new ImageIcon("images/Vert.jpg"),
                    new ImageIcon("images/Vert.jpg"),
                    new ImageIcon("images/UpRight.jpg"),
                    new ImageIcon("images/RightDown.jpg"),
                    new ImageIcon("images/DownRight.jpg"),
                    new ImageIcon("images/Horiz.jpg"),
                    new ImageIcon("images/RightDown.jpg")};
              private ImageIcon carrinImagesTrain[]={
                        new ImageIcon("images/Carriage1Down.jpg"),
                        new ImageIcon("images/Carriage1Down.jpg"),
                        new ImageIcon("images/Carriage1Left.jpg"),
                        new ImageIcon("images/Carriage1Left.jpg"),
                        new ImageIcon("images/Carriage1Down.jpg"),
                        new ImageIcon("images/Carriage1Left.jpg"),
                        new ImageIcon("images/Carriage1Up.jpg"),
                        new ImageIcon("images/Carriage1Up.jpg"),
                        new ImageIcon("images/Carriage1Up.jpg"),
                        new ImageIcon("images/Carriage1Up.jpg"),
                        new ImageIcon("images/Carriage1Right.jpg"),
                        new ImageIcon("images/Carriage1Down.jpg"),
                        new ImageIcon("images/Carriage1Right.jpg"),
                        new ImageIcon("images/Carriage1Down.jpg")};
        private int[]frontPath={13, 18,17,16,21,20,15,10,5,0,1,6,7,8};
      private int[]frontPath2={8, 13,18,17,16,21,20,15,10,5,0,1,6,7};  
        private ImageIcon icon;
        private JLabel labelInfo;
        public Train () {  
           screen = new JPanel(new GridLayout(1,1));
           Font f =new Font ("Sanserif",Font.BOLD,18);
           labelInfo = new JLabel("WELCOM" ,JLabel.CENTER);
           labelInfo.setFont(f);
           screen.setBackground(Color.red);
           screen.add(labelInfo);
           getContentPane().add(BorderLayout.NORTH,screen );
            street = new JButton[5][5];
            area = new JPanel (new GridLayout(5,5));
            for(int r=0; r<5; r++) 
                for (int c=0; c<5; c++){
                    street[r][c] = new JButton("", images[r][c]);
                    area.add(street[r][c]);
            getContentPane().add(BorderLayout.CENTER,area );   
            keybord = new JButton[9];
            controlroom = new JPanel(new GridLayout(5,2));   
    //        ActionHandler handler = new ActionHandler();
            for (int i=0; i <9; i++)
                keybord[i] = new JButton(s);
    keybord[i].addActionListener(this);
    controlroom.add(keybord[i]);
              keybord[i].setEnabled(false);
              keybord[7].setEnabled(true);
    getContentPane().add(BorderLayout.SOUTH,controlroom );
    public void moveTrainFront(){
    int trainPlace1 = trainPlace;
    try{
    if (trainPlace == frontPath.length-1) trainPlace = 0;
    else trainPlace ++;
                   if (carrNum == 0 )
         int i = frontPath[trainPlace]/5;
         int j = frontPath[trainPlace] - i * 5;
         int r = frontPath[trainPlace1]/5;
         int c = frontPath[trainPlace1] - r * 5;
         street[i][j].setIcon(frontImagesTrain[trainPlace]);
         street[r][c].setIcon(trackImagesTrain[trainPlace1]);
                   else
                        int i1 = frontPath[trainPlace]/5;
                        int j1 = frontPath[trainPlace] - i1 * 5;
                        street[i1][j1].setIcon(frontImagesTrain[trainPlace]);     
                        int trainPlace2 = trainPlace;
                        for (int z = 1; z <= carrNum; z++)
    if (trainPlace2 - z < 0) trainPlace2 = 13;
                                  int i2 = frontPath[trainPlace2 - z]/5;
                                  int j2 = frontPath[trainPlace2 - z] - i2 * 5;
                                  street[i2][j2].setIcon(carrinImagesTrain[trainPlace2 - z]);
              int r1 = frontPath[trainPlace1 - carrNum]/5;
                        int c1 = frontPath[trainPlace1 - carrNum] - r1 * 5;
                        street[r1][c1].setIcon(trackImagesTrain[trainPlace1 - carrNum]);
    }catch(ArrayIndexOutOfBoundsException aiex){System.out.println("the array out of index");}
    // Move train Back
    public void moveTrainBack(){
    int trainPlace1 = trainPlace;
    try{
    if (trainPlace == 0) trainPlace = 13;
    else trainPlace--;
    int i = frontPath[trainPlace]/5;
    int j = frontPath[trainPlace] - i * 5;
    int r = frontPath[trainPlace1]/5;
    int c = frontPath[trainPlace1] - r * 5;
    street[i][j].setIcon(frontImagesTrain[trainPlace]);
    street[r][c].setIcon(trackImagesTrain[trainPlace1]);
    }catch(ArrayIndexOutOfBoundsException aiex){System.out.println("the array out of index");}
    public void setRest(){
    setStop(true);
              setSpeed(300);
    int i = frontPath[trainPlace]/5;
    int j = frontPath[trainPlace] - i * 5;
    street[i][j].setIcon(trackImagesTrain[trainPlace]);
    trainPlace = 0;
    i = frontPath[trainPlace]/5;
    j = frontPath[trainPlace] - i * 5;
    street[i][j].setIcon(frontImagesTrain[0]);
    public void setCheck (boolean c)
    int i = frontPath[trainPlace]/5;
    int j = frontPath[trainPlace] - i * 5;
    street[i][j].setIcon(frontImagesTrain[0]);
    check = c ;
    public boolean getCheck (){ return  check ;}
    public void setSpeed (int s){speed = s ;}
    public int getSpeed(){return  speed;}
    public void setStop(boolean s){stopped = s ;}
    public boolean getStop(){return  stopped ;}
    public void setBack(boolean s){back = s ;}
    public boolean getBack(){return  back;}
         public void setAdd(){carrNum++ ;}
    public boolean getAdd(){return  add;}
    // Action
         public void actionPerformed(ActionEvent e){
              if(e.getSource()==keybord[0])//Start
              if (stopped)
              keybord[0].setText("Stop");
                   setStop(false);
                   labelInfo.setText("Running");
    else      
                   {    setStop(true);
                   keybord[0].setText("Start");
                        labelInfo.setText("Stop");
              if(e.getSource()==keybord[1])//Front And Back
              if (!back)
                   setBack(true);
              keybord[1].setText("Front");
                   labelInfo.setText("Back");
              else      
                   setBack(false);
              keybord[1].setText("Back");
                   labelInfo.setText("Front");
              }     else if (e.getSource()==keybord[2])//Fast
              if (speed <= 0)
              labelInfo.setText("You've arrived the maximum speed : " + getSpeed());
              else {      setSpeed(speed  - 10);
                   labelInfo.setText("The Train speed is slow down to : " + getSpeed());
         else if(e.getSource()==keybord[3])//Slow
              {setSpeed(speed + 10);
                    labelInfo.setText("The Train speed is pulled up to : "+getSpeed());
    else if(e.getSource()==keybord[4]) //ADD carrin
                        setAdd();
                        labelInfo.setText("Add Carriage");
              //setStop(false);
    else if(e.getSource()==keybord[5]) //Delete carrin
                   labelInfo.setText("Delete Carrin");
         else if(e.getSource()==keybord[6]) //Rest
                   setRest();     
              labelInfo.setText("Rest");
         else if (e.getSource()==keybord[7]) //Check
         setCheck(true);
         keybord[7].setEnabled(false);
         keybord[0].setEnabled(true);
         keybord[1].setEnabled(true);
         keybord[2].setEnabled(true);
         keybord[3].setEnabled(true);
         keybord[4].setEnabled(true);
         keybord[5].setEnabled(true);
         keybord[6].setEnabled(true);
         keybord[8].setEnabled(true);
         labelInfo.setText("The Train is Checked");
    else if(e.getSource()==keybord[8]) //desiners
         String x = "";
                   labelInfo.setText("Desiners About");
                   JOptionPane.showMessageDialog(null,"The Progect is Under The Auspices of:"
                   + "\n??" + "\n" + "\n ??" +
                   "\n ??" + "\n??" + "\n ??" + "\n" + "\n" + "\n?? " + "\n C 2007");     }     
    This main ..
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.lang.Thread;
    public class TestTrain{     
        public static void main(String[]args){
            Train train = new Train ();
              MoveTrain mt = new MoveTrain(train);
            train.setTitle("Train");
            train.setSize(421,550);
            train.setVisible(true);
            train.addWindowListener (
            new WindowAdapter (){
                 public void windowClosing(WindowEvent e ){
                      System.exit(0);
              mt.start();
    }This Threads
    import java.lang.Thread;
    public class MoveTrain extends Thread {
         Train train ;
        public MoveTrain (Train train){
               this.train= train;
         public void run(){
               while(!train.getCheck());
               while (train.getCheck()){
                    try {sleep (train.getSpeed()); }
                    catch (InterruptedException e ){System.out.println("unknown error");}
                     if (!train.getStop())
                        if(!train.getBack())
                                {train.moveTrainFront();
                          else  train.moveTrainBack();
    }This Link image icon ..
    http://www.geocities.com/alhairan_2003/as/777/UpRight.jpg
    http://www.geocities.com/alhairan_2003/as/777/Vert.jpg
    http://www.geocities.com/alhairan_2003/as/777/TrainUp.jpg
    http://www.geocities.com/alhairan_2003/as/777/TrainRight.jpg
    http://www.geocities.com/alhairan_2003/as/777/TrainLeft.jpg
    http://www.geocities.com/alhairan_2003/as/777/TrainDown.jpg
    http://www.geocities.com/alhairan_2003/as/777/Train.jpg
    http://www.geocities.com/alhairan_2003/as/777/RightUp.jpg
    http://www.geocities.com/alhairan_2003/as/777/RightDown.jpg
    http://www.geocities.com/alhairan_2003/as/777/NoTrack.jpg
    http://www.geocities.com/alhairan_2003/as/777/Horiz.jpg
    http://www.geocities.com/alhairan_2003/as/777/DownRight.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage3Up.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage3Right.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage3Left.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage3Down.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage2Up.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage2Right.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage2Left.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage2Down.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage1Right.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage1Left.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage1Down.jpg
    thanks :)

            String[] car1Names = {
                "Carriage1Down", "Carriage1Left", "Carriage1Down", "Carriage1Right"
            };The first image name should be "Carriage1Up" but it is missing in your directory.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class MC6 implements Runnable, ActionListener {
        JLabel[] grid;
        BufferedImage[] trackImages;
        BufferedImage[] trainImages;
        BufferedImage[][] carImages;
        int[] imageKeys;
        int[] trackKeys;
        int[] forwardKeys;
        int[] reverseKeys;
        int keyIndex = 0;
        int carCount = 0;           // [0 - 3]
        boolean goingAhead = true;
        boolean changeDirections = false;
        Thread thread = null;
        boolean moving = false;
        final int DELAY = 1000;
        public MC6() {
            loadImages();
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            if(ac.equals("START"))
                changeDirections = false;
                start();
            if(ac.equals("STOP"))
                stop();
            if(ac.equals("FORWARD") || ac.equals("REVERSE"))
                changeDirections = true;
            if(ac.equals("ADD CARRIAGE"))
                carCount += (carCount+1 <= 3) ? 1 : 0;
            if(ac.equals("REMOVE CARRIAGE")) {
                int carIndex = getCarIndex(carCount);
                int trackIndex = trackKeys[carIndex];
                int imageIndex = imageKeys[carIndex];
                grid[trackIndex].setIcon(new ImageIcon(trackImages[imageIndex]));           
                carCount -= (carCount-1 >=0 ) ? 1 : 0;
        public void run() {
            while(moving) {
                // Clear track in preparation for next advance.
                if(changeDirections) {
                    clearTrack();
                    // Adjust keyIndex by one increment in the direction of travel
                    // to allow it to return it to its current position after the
                    // next advance in position (further below).
                    advance();
                    goingAhead = !goingAhead;
                    changeDirections = false;
                } else {
                    // Replace last car with track image before train advances.
                    int carIndex = getCarIndex(carCount);
                    int trackIndex = trackKeys[carIndex];
                    int imageIndex = imageKeys[carIndex];
                    grid[trackIndex].setIcon(new ImageIcon(trackImages[imageIndex]));
                // Move to next position on the track.
                advance();
                // Set locomotive.
                setLocomotive();
                // Set the cars following the locomotive.
                setCars();
                try {
                    Thread.sleep(DELAY);
                } catch(InterruptedException e) {
                    System.out.println("interrupted");
                    stop();
        private int getCarIndex(int carNumber) {
            int n = carNumber;
            int index;
            if(goingAhead) {
                index = keyIndex-n;
                if(index < 0)
                    index += trackKeys.length;
            } else {
                index = (keyIndex+n) % trackKeys.length;
            return index;
        private void advance() {
            keyIndex = goingAhead ?
                           (keyIndex+1 > trackKeys.length-1) ? 0 : keyIndex+1
                           (keyIndex-1 < 0) ? trackKeys.length-1 : keyIndex-1;
        private void clearTrack() {
            // Remove all cars from track before direction change.
            for(int j = 0; j < carCount; j++) {
                int carIndex = getCarIndex(j+1);
                int trackIndex = trackKeys[carIndex];
                int imageIndex = imageKeys[carIndex];
                grid[trackIndex].setIcon(new ImageIcon(trackImages[imageIndex]));
        private void setLocomotive() {
            int trackIndex = trackKeys[keyIndex];
            int imageIndex = goingAhead ? forwardKeys[keyIndex]
                                        : reverseKeys[keyIndex];
            grid[trackIndex].setIcon(new ImageIcon(trainImages[imageIndex]));
        private void setCars() {
            for(int j = 0; j < carCount; j++) {
                int carIndex = getCarIndex(j+1);
                int trackIndex = trackKeys[carIndex];
                int imageIndex = goingAhead ? forwardKeys[carIndex]
                                            : reverseKeys[carIndex];
                grid[trackIndex].setIcon(new ImageIcon(carImages[j][imageIndex]));
        private void start() {
            if(!moving) {
                moving = true;
                thread = new Thread(this);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.start();
        public void stop() {
            moving = false;
            if(thread != null)
                thread.interrupt();
            thread = null;
        private void loadImages() {
            String[] trackNames = {
                "UpRight", "RightDown", "Vert", "DownRight", "Horiz", "RightUp", "NoTrack"
            String[] trainNames = { "TrainUp", "TrainLeft", "TrainDown", "TrainRight" };
            String[] car1Names = {
                "Carriage1Down", "Carriage1Left", "Carriage1Down", "Carriage1Right"
            String[] car2Names = {
                "Carriage2Up", "Carriage2Left", "Carriage2Down", "Carriage2Right"
            String[] car3Names = {
                "Carriage3Up", "Carriage3Left", "Carriage3Down", "Carriage3Right"
            trackImages = getImages(trackNames);
            trainImages = getImages(trainNames);
            BufferedImage[] car1Images = getImages(car1Names);
            BufferedImage[] car2Images = getImages(car2Names);
            BufferedImage[] car3Images = getImages(car3Names);
            carImages = new BufferedImage[][]{ car1Images, car2Images, car3Images };
        private BufferedImage[] getImages(String[] ids) {
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int j = 0; j < ids.length; j++) {
                String path = "images/" + ids[j] + ".jpg";
                try {
                    images[j] = ImageIO.read(new File(path));
                } catch(IOException e) {
                    System.out.println("Read error for " + path +
                                       ": " + e.getMessage());
                    images[j] = null;
            return images;
        private JPanel getCenterComponent() {
            imageKeys = new int[] {
                0, 1, 3, 4, 1,  2,  5,  4,  0,  5,  3,  2,  2, 2
            trackKeys = new int[] {
                0, 1, 6, 7, 8, 13, 18, 17, 16, 21, 20, 15, 10, 5
            forwardKeys = new int[] {
                0, 3, 2, 3, 3,  2,  2,  1,  1,  2,  1,  0,  0, 0
            reverseKeys = new int[] {
                1, 0, 1, 1, 0,  0,  3,  3,  0,  3,  2,  2,  2, 2
            grid = new JLabel[25];
            JPanel panel = new JPanel(new GridLayout(5,0));
            for(int j = 0; j < grid.length; j++) {
                ImageIcon icon;
                int index = getIndexForValue(j);
                if(index != -1) {
                    icon = new ImageIcon(trackImages[imageKeys[index]]);
                } else {
                    icon = new ImageIcon(trackImages[6]);
                grid[j] = new JLabel(icon);
                panel.add(grid[j]);
            return panel;
        private int getIndexForValue(int value) {
            for(int j = 0; j < trackKeys.length; j++) {
                if(value == trackKeys[j])
                    return j;
            return -1;
        private JPanel getControls() {
            String[] ids = {
                "Start", "Stop", "Forward", "Reverse", "Add Carriage", "Remove Carriage"
            JPanel panel = new JPanel(new GridLayout(0,2));
             for(int j = 0; j < ids.length; j++) {
                JButton button = new JButton(ids[j]);
                button.setActionCommand(ids[j].toUpperCase());
                button.addActionListener(this);
                panel.add(button);
            return panel;
        public static void main(String[] args) {
            MC6 test = new MC6();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getCenterComponent());
            f.getContentPane().add(test.getControls(), "Last");
            f.pack();
            f.setLocation(200,100);
            f.setVisible(true);
    }

  • Install Application - TextArea inside JScrollPane

    I've been working on an install application to install another one of my programs (next/accept/next/ finish type of thing) and had a couple questions and would appreciate any help anyone can give.
    Some Background info:
    I made images and have them display as image icons through jlabels for the buttons and background. The labels have classes applying various mouselisteners (Mousepressed, MouseEntered, MouseExited, etc) changing the images and moving from screen to screen. I have my layout set to null, not for any particular reason, but because I have no formal education in layout managers.
    1) Is there a conical solution to moving through various windows? That is, right now I move through the various 'screens' with a check on an int called state, that gets incremented and decremented through forward and back buttons. I looked at some code given to us on a test by our teacher (we had to find bugs) and saw that he had implemented a fake "state" interface, with constants like "Account_State" to control where you were in the program. This seems a bit easier to read than ints, but is there a correct built in version of his states?
    2) On the second screen I have a license agreement (actually required for the application that gets installed), and a checkbox. The license is held inside of a JTextArea(scroll) inside a JScrollPane(textscroll). The JScrollPane is extending in weird ways. The following is a stripped down version of my code (it runs and demonstrates the problem):
    InstalleApp
    import javax.swing.*;
    import java.awt.*;
    public class InstalleApp {
        public static void main(String args[]) {
            InstalleFrame m = new InstalleFrame();
               Container content = m.getContentPane();
            m.setDefaultCloseOperation(3);
            m.setSize(550, 400);
            m.setUndecorated(true);
            m.setVisible(true);
            m.setTitle("Install");
    }InstalleFrame
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.awt.Rectangle;
    import java.awt.Font;
    import java.awt.BorderLayout;
    import java.util.*;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import java.awt.event.ActionEvent;
    import javax.swing.text.BadLocationException;
    import javax.swing.JSlider;
    import java.awt.Dimension;
    public class InstalleFrame
        extends JFrame implements ActionListener {
      public InstalleFrame() {
        try {
          jbInit();
        catch (Exception ex) {
          ex.printStackTrace();
      public void actionPerformed(ActionEvent e) {
      JScrollPane textscroll;
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(null);
        this.getContentPane().setBackground(UIManager.getColor("window"));
        background.setBounds(new Rectangle(0, 0, 550, 400));
        readcheck.setOpaque(false);
        readcheck.setText("I have read and accept the license agreement");
        readcheck.setBounds(new Rectangle(31, 357, 319, 32));
        scroll.setWrapStyleWord(true);
        scroll.setLineWrap(true);
        scroll.setText(
            "Copyright ? 2006-2007 GonZor228.com \n\nBy using or distributing this " +
            "software (or any work based on the software) you shall be deemed " +
            "to have accepted the terms and conditions set out below.\n\nGonZor228.com " +
            "(\"GonZor\") is making this software freely available on the basis " +
            "that it is accepted as found and that the user checks its fitness " +
            "for purpose prior to use.\n\nThis software is provided \'as-is\', without " +
            "any express or implied warranties whatsoever. In no event will the " +
            "authors, partners or contributors be held liable for any damages, " +
            "claims or other liabilities direct or indirect, arising from the " +
            "use of this software.\n\nGonZor will from time to time make software " +
            "updates available.  However, GonZor accepts no obligation to provide " +
            "any support to free license holders.\n\nGonZor grants you a limited " +
            "non-exclusive license to use this software for any purpose that does " +
            "not violate any laws that apply to your person in your current jurisdiction, " +
            "subject to the following restrictions: \n\n1. The origin of this software " +
            "must not be misrepresented; you must not claim that you wrote the " +
            "original software.\n2. You must not alter the software, user license " +
            "or installer in any way unless given permission to do so.\n3. This " +
            "notice may not be removed or altered from any distribution.\n4. You " +
            "may not resell or charge for the software.\n5. You may not reverse " +
            "engineer, decompile, disassemble, derive the source code of or modify " +
            "[or create derivative work from] the program without the express " +
            "permission of GonZor.\n6. You must not use this software to engage " +
            "in or allow others to engage in any illegal activity.\n7. You may " +
            "not claim any sponsorship by, endorsement by, or affiliation with " +
            "GonZor228.com\n8. You acknowledge that GonZor owns the copyright and " +
            "all associated intellectual property rights relating to the software.\n\n" +
            " This software license is governed by and construed in accordance " +
            "with the laws of Australia and you agree to submit to the exclusive " +
            "jurisdiction of the Australian courts.\n\nBy clicking the \"I agree\" " +
            "button below, you agree to these software license terms. If you disagree " +
            "with any of the terms below, GonZor does not grant you a license " +
            "to use the software ? exit the window.\n\nYou agree that by your installation " +
            "of the GonZor?s software, you acknowledge that you are at least 18 " +
            "years old, have read this software license, understand it, and agree " +
            "to be bound by its terms.\n\nGonZor reserves the right to update and " +
            "change, from time to time, this software license and all documents " +
            "incorporated by reference. You can always find the most recent version " +
            "of this software license at GonZor228.com.  GonZor may change this " +
            "software license by posting a new version without notice to you. " +
            "Use of the GonZor?s software after such change constitutes acceptance " +
            "of such changes.\n\n1.\tOwnership and Relationship of Parties.\n\nThe " +
            "software is protected by copyrights, trademarks, service marks, international " +
            "treaties, and/or other proprietary rights and laws of the U.S. and " +
            "other countries. You agree to abide by all applicable proprietary " +
            "rights laws and other laws, as well as any additional copyright notices " +
            "or restrictions contained in this software license. GonZor owns all " +
            "rights, titles, and interests in and to the applicable contributions " +
            "to the software. This software license grants you no right, title, " +
            "or interest in any intellectual property owned or licensed by GonZor, " +
            "including (but not limited to) the software, and creates no relationship " +
            "between yourself and GonZor other than that of GonZor to licensee.\n\n" +
            "The software and its components contain software licensed from " +
            "GonZor. The licensor software enables the software to perform certain " +
            "functions including, without limitation, access proprietary data " +
            "on third-party data servers as well as GonZor?s own server. You agree " +
            "that you will use the software, and any data accessed through the " +
            "software, for your own personal non-commercial use only. You agree " +
            "not to assign, copy, transfer, or transmit the software, or any data " +
            "obtained through the software, to any third party. Your license to " +
            "use the software, its components, and any third-party data, will " +
            "terminate if you violate these restrictions. If your license terminates, " +
            "you agree to cease any and all use of the software, its components, " +
            "and any third-party data. All rights in any third-party data, any " +
            "third-party software, and any third-party data servers, including " +
            "all ownership rights are reserved and remain with the respective " +
            "third parties. You agree that these third parties may enforce their " +
            "rights under this Agreement against you directly in their own name.\n\n" +
            "2.\tSupport and Software Updates.\n\nGonZor may elect to provide " +
            "you with customer support and/or software upgrades, enhancements, " +
            "or modifications for the software (collectively, \"Support\"), in its " +
            "sole discretion, and may terminate such Support at any time without " +
            "notice to you. GonZor may change, suspend, or discontinue any aspect " +
            "of the software at any time, including the availability of any software " +
            "feature, database, or content. GonZor may also impose limits on certain " +
            "features and services or restrict your access to parts or all of " +
            "the software or the GonZor228.com web site without notice or liability.\n\n" +
            "3.  \tFees and Payments.\n\nGonZor reserves the right to charge fees " +
            "for future use of or access to the software in GonZor?s sole discretion. " +
            "If GonZor decides to charge for the software, such charges will be " +
            "disclosed to you 28 days before they are applied if such fees will " +
            "affect your use of the product.\n\n4.\tDisclaimer of Warranties by " +
            "GonZor.\n\nUse of the software and any data accessed through the software " +
            "is at your sole risk. They are provided \"as is.\"  Any material or " +
            "service downloaded or otherwise obtained through the use of the software " +
            "(such as the \"plug-in\" feature) is done at your own discretion and " +
            "risk, and you will be solely responsible for any damage to your computer " +
            "system or loss of data that results from the download and/or use " +
            "of any such material or service.  GonZor, its officers, directors, " +
            "employees, contractors, agents, affiliates, assigns, and GonZor?s " +
            "licensors (collectively ?Associates?) do not represent that the software " +
            "or any data accessed there from is appropriate or available for use " +
            "outside the Australia.\n\nThe Associates expressly disclaim all warranties " +
            "of any kind, whether express or implied, relating to the software " +
            "and any data accessed there from, or the accuracy, timeliness, completeness, " +
            "or adequacy of the software and any data accessed there from, including " +
            "the implied warranties of title, merchantability, satisfactory quality, " +
            "fitness for a particular purpose, and non-infringement.\n\nIf the " +
            "software or any data accessed there from proves defective, you (and " +
            "not the Associates) assume the entire cost of all repairs or injury " +
            "of any kind, even if the Associates have been advised of the possibility " +
            "of such a defect or damages. Some jurisdictions do not allow restrictions " +
            "on implied warranties so some of these limitations may not apply " +
            "to you.\n\n5. \tLimitation of liability.\n\nThe Associates will not " +
            "be liable to you for claims and liabilities of any kind arising out " +
            "of or in any way related to the use of the software by yourself or " +
            "by third parties, to the use or non-use of any brokerage firm or " +
            "dealer, or to the sale or purchase of any security, whether such " +
            "claims and liabilities are based on any legal or equitable theory." +
            "\n\nThe Associates are not liable to you for any and all direct, incidental, " +
            "special, indirect, or consequential damages arising out of or related " +
            "to any third-party software, any data accessed through the software, " +
            "your use or inability to use or access the software, or any data " +
            "provided through the software, whether such damage claims are brought " +
            "under any theory of law or equity. Damages excluded by this clause " +
            "include, without limitation, those for loss of business profits, " +
            "injury to person or property, business interruption, loss of business " +
            "or personal information. Some jurisdictions do not allow limitation " +
            "of incidental or consequential damages so this restriction may not " +
            "apply to you.\n\nInformation provided through the software may be " +
            "delayed, inaccurate, or contain errors or omissions, and the Associates " +
            "will have no liability with respect thereto. GonZor may change or " +
            "discontinue any aspect or feature of the software or the use of all " +
            "or any features or technology in the software at any time without " +
            "prior notice to you, including, but not limited to, content, hours " +
            "of availability.\n\n6.  \tControlling Law.\n\nThis software license " +
            "and the relationship between you and GonZor is governed by the laws " +
            "of Australia without regard to its conflict of law provisions. You " +
            "and GonZor agree to submit to the personal and exclusive jurisdiction " +
            "of the courts located within Australia. The United Nations Convention " +
            "on the International Sale of Goods does not apply to this software " +
            "license.\n\n7.\tPrecedence.\n\nThis software license constitutes the " +
            "entire understanding between the parties respecting use of the software, " +
            "superseding all prior agreements between you and GonZor.\n\n8.\tSurviving " +
            "Provisions.\n\nSections 1, and 3 through 5, will survive any termination " +
            "of this Agreement.\n\n---------------------------------------------------------------------------------" +
            "---\nIf you accept the terms of the agreements, click I Agree to continue. " +
            " You must accept the agreement to download and use the software. ");
        scroll.setBounds(new Rectangle(36, 36, 478, 305));
        this.getContentPane().add(readcheck);
        readcheck.setVisible(false);
       this.getContentPane().add(scroll);
       textscroll = new JScrollPane (scroll, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        textscroll.setBounds(36,36,400,400);
          getContentPane().add( textscroll );
        this.getContentPane().add(background);
      JLabel background = new JLabel();
      JCheckBox readcheck = new JCheckBox();
      JTextArea scroll = new JTextArea();
    }Sorry about all the text for the agreement. I've tried a number of different things I got from searching the forums at different points in the code (setting the number of rows/columns, setting max and min sizes, etc etc) The code above that wraps the text I could have sworn I tried 3 times before it magically worked... I also tried using the awt component for textareas that had the scrollbars built in, but scrapped it after having even more difficulties with that one. I'm trying to get the textbox to only go down about 300 px and 300 px to the right. Using the graphical editor to change it produces a null pointer error at compile time(?!?). Can anyone help me to get the textbox to render as I want it to?
    Edited by: rpk5000 on Jan 27, 2008 9:43 AM

    for instance, boxlayout would work nicely with the installer frame (or dialog)
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    public class InstalleFrame
        public InstalleFrame()
            try
                jbInit();
            catch (Exception ex)
                ex.printStackTrace();
        private JScrollPane textscroll;
        private JPanel contentPane = new JPanel();
        private JLabel background = new JLabel();
        private JCheckBox readcheck = new JCheckBox();
        private JTextArea scroll = new JTextArea();
        private void jbInit() throws Exception
            contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
            contentPane.setBackground(UIManager.getColor("window"));
            contentPane.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            scroll.setWrapStyleWord(true);
            scroll.setLineWrap(true);
            String text = "Copyright ? 2006-2007 GonZor228.com \n\nBy using or distributing this "
                            + "software (or any work based on the software) you shall be deemed "
                            + "to have accepted the terms and conditions set out below.\n\nGonZor228.com "
                            + "(\"GonZor\") is making this software freely available on the basis "
                            + "that it is accepted as found and that the user checks its fitness "
                            + "for purpose prior to use.\n\nThis software is provided \'as-is\', without "
                            + "any express or implied warranties whatsoever. In no event will the "
                            + "authors, partners or contributors be held liable for any damages, "
                            + "claims or other liabilities direct or indirect, arising from the "
                            + "use of this software.\n\nGonZor will from time to time make software "
                            + "updates available.  However, GonZor accepts no obligation to provide "
                            + "any support to free license holders.\n\nGonZor grants you a limited "
                            + "non-exclusive license to use this software for any purpose that does "
                            + "not violate any laws that apply to your person in your current jurisdiction, "
                            + "subject to the following restrictions: \n\n\nblah, blah, blah,..."
                            + "\n\n";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 5; i++)
                sb.append(text);
            scroll.setText(sb.toString());
            contentPane.add(readcheck);
            contentPane.add(scroll);
            textscroll = new JScrollPane(scroll,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            textscroll.setPreferredSize(new Dimension(400, 400));
            contentPane.add(textscroll);
            JPanel bottomPane = new JPanel();
            bottomPane.setOpaque(false);
            final JButton okButton = new JButton("OK");
            final JButton cancelButton = new JButton("Cancel");
            okButton.setEnabled(false);
            readcheck.setOpaque(false);
            readcheck.setText("I have read and accept the license agreement");
            readcheck.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JCheckBox radioBtn = (JCheckBox)e.getSource();
                    if (radioBtn.isSelected())
                        okButton.setEnabled(true);                   
                    else
                        okButton.setEnabled(false);
            okButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    // TODO: whatever needs to be done here
            cancelButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    SwingUtilities.getWindowAncestor(contentPane).dispose();
            bottomPane.add(readcheck);
            bottomPane.add(okButton);
            bottomPane.add(cancelButton);
            contentPane.add(bottomPane);
            //readcheck.setVisible(false);
            contentPane.add(background);
        public JPanel getContentPane()
            return contentPane;
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    InstalleFrame install = new InstalleFrame();
                    JFrame frame = new JFrame("Install");
                    frame.getContentPane().add(install.getContentPane());
                    frame.setDefaultCloseOperation(3);
                    frame.setSize(550, 400);
                    frame.setUndecorated(false);  //**
                    frame.pack();  //**
                    frame.setLocationRelativeTo(null); //**
                    frame.setVisible(true);
    }

  • How to create a bordeless and titleless dialog or frame?

    Hi people,
    I am trying to do a simple start up screen for my application. I have done the graphics for the startup screen and save as filename.gif. I am looking for a container or a way to paint my the gif so that it looks like a startup screen. I have considered JFrame but haven't found a way to remove the window's title bar. Should I use JDialog?.. Is there a way for me to remove the top title bar. Also anybody knows how I could set my startup screen to be visible for a set period of time and then later display?
    AG

    If your application is out of swing, you can use JWindow, of your application is out of regular components, use Window. I'm more experiancedin swing and I know there are methods to get the users screen size and then from that info you can center the window on the screen. Just don't forget to terminate the window, otherwise people will get mad with an "unclosable" window (they'd have to CTRL+ALT+Del it to close it).
    I have an example: (for Swing, but I'm sure it'll be useful)
    package com.foley.utility;
    import java.awt.*;
    import java.beans.*;
    import javax.swing.*;
    * A window that contains an image.
    * @author Mike Foley
    public class SplashWindow extends JWindow {
         * The Icon displayed in the window.
        private Icon splashIcon;
         * A label used to display the Icon.
        private JLabel iconLabel;
         * Bound property support and name constants.
        private PropertyChangeSupport changeSupport;
        public static final String SPLASHICON_PROPERTY = "SplashIcon";
         * SplashWindow, null constructor.
        public SplashWindow() {
            this( null );
         * SplashWindow, constructor.
         * @param splashIcon�The Icon to view in the window.
        public SplashWindow( Icon splashIcon ) {
            super();
            iconLabel = new JLabel();
            iconLabel.setBorder( BorderFactory.createRaisedBevelBorder() );
            getContentPane().add( iconLabel, BorderLayout.CENTER );
            setSplashIcon( splashIcon );
         * Set the image displayed in the window.
         * This is a bound property named SPLASHICON_PROPERTY.
         * If this property is changed when the window is
         * visible, the window is NOT re-centered on the screen.
         * @param splashIcon�The icon to draw in the window.
        public void setSplashIcon( Icon splashIcon ) {
            Icon old = this.splashIcon;
            this.splashIcon = splashIcon;
            iconLabel.setIcon( splashIcon );
            pack();
            if( changeSupport != null ) {
                changeSupport.firePropertyChange( SPLASHICON_PROPERTY,
                                                  old, splashIcon );
         * Extend the setVisible method to center this window
         * on the screen before being displayed.
         * @param visible�True if showing the window, false if hiding.
        public void setVisible( boolean visible ) {
            if( visible ) {
                // Display the window in the center of the screen.
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                Dimension size = getSize();
                int x;
                int y;
                x = screenSize.width / 2 - size.width / 2;
                y = screenSize.height / 2 - size.height / 2;
                    setBounds( x, y, size.width, size.height);
            // Let super show or hide the window.
            super.setVisible( visible );
         * Need to handle PropertyChangeListeners here until this
         * type of code is moved from JComponent to Component.
        public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
            if (changeSupport == null) {
                changeSupport = new PropertyChangeSupport(this);
            changeSupport.addPropertyChangeListener(listener);
        public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
            if (changeSupport != null) {
                changeSupport.removePropertyChangeListener(listener);
    } // SplashWindow

Maybe you are looking for

  • Was not copied because it cannot be played on this ipod

    I am getting this message when I try to put songs on my ipod. I have had the ipod for over a year and have never had any problems until now. I bought an album of iTunes Store, burned an audio CD,imported it into iTunes as MP3 and tried to put the mp3

  • Basic transitions need to be rendered

    I just installed the uprage to FCP 6 and the some of the basic transitions need to be rendered before I can view them. I never had this problem before upgrading, so am assuming it is a setting that I am missing. A couple would play (some dissolves, a

  • Equium M70 - No icons or picture on TV display

    I connected an S-Video cable to my TV via my laptop. All i can receive on my TV is the desktop picture, nothing else. What i would like to see is everything i see on my laptop. Icons, files, internet, e-mail ect, ect. Is this possible or do i need to

  • Airplay denon

    My Denon was not able to work anymore with Mavericks. I found this solution, you may try if you have airplay issue If I select my denon in System Preference=>Sound, it plays for one seconds and an error meesage says: this device does not allow sound

  • Appearances and opacity masks

    this is a little something I've been trying to work out. under each fill or stroke in the appearance panel you've got your opacity options that appear to be exactly the same as you'd get for an individual object, like so: this includes being able to