Moving JLabel in a JFrame

Hi .
I want to move a JLabel in a JFrame and i set bounds for JLalbe using while
such as :
JLabel lb=new JLabel("JLABEL");
int x=50,;
int y=0;
int w=60;
int h=40;
lb.setBounds(x,y,w,h) ;
while(y<100)
lb.setBounds(x,y,z,t);
y+=1;
But when lb moves in JFrame , it has vertical line its color is Color of lb ?
what should i do to solve this problem ?

Do you have an override of your paintComponent and do you call super.paintComponent from it?
It probably has to do with the fact that you are trying to pig all the CPU cycles and not allowing other processing in your thread, try this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class Junk extends JFrame implements ActionListener{
  private int dX = 1;
  private int dY = 1;
  public int x = 1;
  public int y = 1;
  public JLabel l = null;
  public Timer t = null;
  Junk(){
    t = new Timer(10, this);
  public static void main(String[] args){
    Junk f = new Junk();
    f.setTitle("Junk X.x");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLayout(null);
    f.setSize(600, 600);
    f.l = new JLabel("This is a JLabel");
    f.l.setSize(100, 30);
    f.add(f.l);
//    f.pack();
    f.setVisible(true);
    f.t.start();
  public void actionPerformed(ActionEvent e){
    if((x+l.getWidth()) >= this.getWidth() || x == 0) dX *= (-1);
    if((y+l.getHeight()) >= this.getHeight() || y == 0) dY *= (-1);
     x += dX;
     y += dY;
     l.setLocation(x, y);
}The timer gives the GUI time to update.
BTW: yes, I know I should have used a JPanel. Mmmm... brain dead late night coding....

Similar Messages

  • JLabel in a JFrame delayed Rendering. How do i render first then continue?

    i have a snippent of code:
    JDialog msg_window;
         public void create_window(JPanel contentPane, JLabel jLabel1) {
              msg_window= new JDialog();
              contentPane=(JPanel)msg_window.getContentPane();
              contentPane.setLayout(null);
              jLabel1.setBounds(48,16,133,18);
              contentPane.add(jLabel1);
              msg_window.setContentPane(contentPane);
              msg_window.setSize(222,85);
              msg_window.setLocation(300,252);
              msg_window.setTitle(jLabel1.getText());
              msg_window.setVisible(true);
    that creates a JDialog box. My intentions are to display this dialog box while another part of the program is attempting to load the JTDS database driver. The driver loading seems to temporarily distract the VM. What happens is the box will render, but the JLabel will not until the driver is loaded ( at which point the box disapears).
    How can i make sure the JDialog and all it's components fully rendered before proceding with then next step in the program?

    This example just uses the extra thread to burn cpu cycles and updat a JLabel on the dialog, but shows interaction between modal dialog and an external thread.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class LoadDialog extends JDialog
        JLabel statusLbl;
        public LoadDialog(JFrame parent )
            super( parent );
            setTitle("Loadinig ");
            JPanel cp = new JPanel();
            cp.setLayout( new BorderLayout());
            cp.add( new JLabel("Please Wait") , BorderLayout.NORTH );
            statusLbl = new JLabel("Counter =     ");
            cp.add( statusLbl, BorderLayout.SOUTH );
            setContentPane( cp );
            pack();
            Runnable runner = new Runnable()
                public void run()
                    for( int i = 0; i < 1000000; i++ )
                        for( int j = 1; j < 1000; j++ )
                            int x = 200 * i / j;
                        final int count = i;
                        try
                            SwingUtilities.invokeAndWait( new Runnable()
                                                              public void run()
                                                                  statusLbl.setText( "Counter = "+count );
                        catch( Exception exc )
                            exc.printStackTrace();
            setModal( true );
            Thread t = new Thread( runner );
            t.start();
            setLocationRelativeTo( parent );
            setVisible( true );
        public static void main(String[] args) throws Exception
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch( Exception e )
            final JFrame f = new JFrame("Threaded Dialog");
            JPanel cp = new JPanel();
            JButton button = new JButton( "Load");
            cp.add( button );
            button.addActionListener( new ActionListener()
                                          public void actionPerformed( ActionEvent e )
                                              new LoadDialog( f );
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(cp);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }For your problem, you I would recommend you thread off the file load and use invokeLater or invokeAndWait to dismis the dialog and pass the loaded file back to the main app.
    Hope this helps,
    Todd

  • Inserting image in a jframe

    is it possible to insert an image into a jframe?
    as far as i noe, i can insert a jlabel, and etc. but how about an image?
    if it is possible, can someone please teach me how to do it and post me the codes.
    Thank you.

    You could use g.drawImage, but the simplest solution would be to add the image to a JLabel and add the JLabel to the JFrame.
    JLabel myLabel = new JLabel(new ImageIcon("yourimage.gif"));
    getContentPane().add(myLabel);

  • JLabel spacing

    I have a component with a JLabel above it. Both of these components are centered relative to the component that is next to it. However, it is not coming out quite right. It appears that the JLabel has 4 pixels of extra space above it. This spacing I believe is due to the font and not from the insets of the GridBagLayout. If I double the size of the JLabel's font, the spacing increases to 8 pixels. I also tested this with a small program that adds a single JLabel to a JFrame:
    public class MainClass {
      public static void main(String[] args) {
        javax.swing.JFrame frame = new javax.swing.JFrame();
        javax.swing.JLabel label = new javax.swing.JLabel("Environment-gy");
        label.setBackground(java.awt.Color.RED);
        frame.getContentPane().add(label);
        frame.getContentPane().setBackground(java.awt.Color.RED);
        frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }If you run this, you will notis that the "gy" in the label has only a single pixel of spacing below, but there are 4 pixels of spacing above the text. Is there any way to remove these 4 pixels? The components do not center correctly with them in there. Even in the test program, the label does not appear to be centered exactly. It appears to be too far down from the top, albeit subtely.
    I cannot just kludge this, however, because this application will be run on a number of different environments and there is no way to know what exact font and font size will be used.

    In the future Swing related questions should be posted in the Swing forum.
    If the past you have been given a link to the Swing tutorial, specifically you have been given the link on "How to Use Layout Managers". So read the tutorial, choose the appropriate layout manager and use the appropriate methods to control the spacing.

  • Positioning JLabels

    Hey,
    I'm trying to learn Swing applications and I've run into a bit of trouble positioning my "Hello World" label on the screen. I've created a JFrame that is 640x480 in size and I want to move my label to a specific x,y within the frame. I've tried using setLocation and setBounds with no luck. The label stays stuck vertically centered on the left side of the screen. How do I move this label around?
    Mike

    You need to read on the layout managers. For instance JFrame contentPanes use the BorderLayout as the default layout manager while JPanels use FlowLayout as the default managers. There are two ways to work here: 1) work with the the appropriate layout manager to place your JLabel in a position that will remain correct even if the JFrame is resized, or 2) set the contentPane's layout to null and place your JLabel by absolute positioning (i.e., setBounds or something similar). If you do the latter, you will have to set the size of the jlabel too (setBounds does this). I recommend the former technique over the latter.
    For instance this adds a JLabel to a JFrame (via a JPanel) by the first method: the null layout with absolute positioning and sizing of the JLabel by calling its setBounds method:
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    class HelloWorldFrame
        // the JPanel that will hold our JLabel
        private JPanel mainPanel = new JPanel();
        public HelloWorldFrame()
            mainPanel.setPreferredSize(new Dimension(640, 480));
            mainPanel.setLayout(null); // use no layout manager
            JLabel helloWorldLabel = new JLabel("Hello World");
            // set the bounds: both the location x, y, and the size width, height
            helloWorldLabel.setBounds(20, 400, 100, 24);
            // so we can see the exact size of the JLabel
            helloWorldLabel.setBorder(BorderFactory.createLineBorder(Color.blue, 4));
            mainPanel.add(helloWorldLabel); // add it to the JPanel
        public JPanel getMainPanel()
            return mainPanel;
        private static void createAndShowUI()
            // create a JFrame
            JFrame frame = new JFrame("HelloWorldFrame");
            // add our JPanel to this JFrame
            frame.getContentPane().add(new HelloWorldFrame().getMainPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        // call swing in a thread-safe manner
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }And here I add the JLabel using the second technique: layout managers:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    class HelloWorldFrame2
        // the JPanel that will hold our JLabel
        private JPanel mainPanel = new JPanel();
        public HelloWorldFrame2()
            mainPanel.setPreferredSize(new Dimension(640, 480));
            mainPanel.setLayout(new BorderLayout());
            mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 56, 0));
            JLabel helloWorldLabel = new JLabel("Hello World");
            // so we can see the exact size of the JLabel
            helloWorldLabel.setBorder(BorderFactory.createLineBorder(Color.blue, 4));
            JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            labelPanel.add(helloWorldLabel);
            mainPanel.add(labelPanel, BorderLayout.SOUTH); // add it to the JPanel
        public JPanel getMainPanel()
            return mainPanel;
        private static void createAndShowUI()
            // create a JFrame
            JFrame frame = new JFrame("HelloWorldFrame2");
            // add our JPanel to this JFrame
            frame.getContentPane().add(new HelloWorldFrame2().getMainPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        // call swing in a thread-safe manner
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }Edited by: Encephalopathic on Feb 18, 2008 7:58 PM

  • Positioning a JLable on a JFrame absoloutely

    How can we position a JLabel on a JFrame at a specific position. I tried setLocation(x,y) but that does not seem to work. When i try setLayout(null) the jlabel is not displayed at all. What could be the soloution...

    when you use this
    setLayout(null)
    you need this
    setLocation(x,y)
    and this
    setSize(..,..)
    or setBounds(..,..,..,..);

  • JLabel constructor

    Hello,
    I created two labels called left and right as shown below.
    left = new JLabel ( images[0] );
    right = new JLabel ( images[0]);
    It wont compile complaining, "cannot resolve symbol".
    images is an array created in a separate method within the same code. I thought maybe it wanted me to declare it like this:
    left = new JLabel ( Icon images[0] );
    but that didn't work either. It gives the same error.
    I'd appreciate some help and/or advice on this.
    Daniel

    Here is a sample that works. Use it to see what is missing in your code:
    import javax.swing.*;
    import java.awt.*;
    class TestIcon {
         public static void main (String[] argv) {
              ImageIcon[] imagini = new ImageIcon [2];
              imagini[0] = new ImageIcon ("oops.gif");
              imagini[1] = new ImageIcon ("exclamation.gif");
              JLabel l1 = new JLabel (imagini[0]);
              JLabel l2 = new JLabel (imagini[0]);
              JFrame frame = new JFrame ("testing...");
              frame.getContentPane().setLayout (new FlowLayout());
              frame.getContentPane().add (l1);
              frame.getContentPane().add (l2);
              //frame.setSize (300,200);
              frame.pack();
              frame.show();
              frame.setVisible (true);
    }Good luck,
    Calin

  • Draging a JLabel

    Hi I have a problem while draging a JLabel in a JFrame, could someone help me here's the code. While draging I loose control of the JLabel + the cursor doesn't stay with the JLabel
    2 classes:
    test.java
    MoveLabel.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JLabel;
    class testMove
    public static void main (String[] args)
    final JFrame frame = new JFrame("Prototype");
    final MoveLabel lmv = new MoveLabel();
    frame.getContentPane().add(lmv);
    frame.setSize(500,500);
    frame.setVisible(true);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JLabel;
    class MoveLabel extends JLabel implements MouseListener, MouseMotionListener
    public int x;
    public int y;
    public int mx;
    public int my;
    public int new_mx;
    public int new_my;
    public MoveLabel()
    // super("Print", icon, JLabel.CENTER);
    this.setIcon(new ImageIcon("print.jpg"));
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
    public void mouseClicked(MouseEvent e)
    if (e.getClickCount() == 2)
    System.out.println("You have DoubleClicked ");
    public void mouseDragged(MouseEvent e)
    new_mx = e.getX();
    new_my = e.getY();
    x += new_mx - mx;
    y += new_my - my;
    System.out.println("depl de " + x +" y " + y);
    this.setText("Printing");
    this.setLocation(x,y);
    mx = new_mx;
    my = new_my;
    public void mouseMoved(MouseEvent e)
    public void mousePressed(MouseEvent e)
    mx = e.getX() ;
    my = e.getY() ;
    this.setText("Printing");
    public void mouseReleased(MouseEvent e)
    System.out.println("You have released at " + e.getX()+ " " + e.getY());
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
    }

    I changed some codes in your original program. It works now.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JLabel;
    public class testMove
    public static void main (String[] args)
         JFrame frame = new JFrame("Prototype");
         frame.getContentPane().setLayout(null);
         MoveLabel lmv = new MoveLabel();
         lmv.setBounds(10,10,100,20);
         frame.getContentPane().add(lmv);
         frame.setSize(500,500);
         frame.setVisible(true);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JLabel;
    public class MoveLabel extends JLabel implements MouseListener, MouseMotionListener
    public int x;
    public int y;
    public int mx;
    public int my;
    public int new_mx;
    public int new_my;
    private int compX;
    private int compY;
    public MoveLabel()
    // super("Print", icon, JLabel.CENTER);
    this.setIcon(new ImageIcon("print.jpg"));
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
    public void mouseClicked(MouseEvent e)
    if (e.getClickCount() == 2)
    System.out.println("You have DoubleClicked ");
    public void mouseDragged(MouseEvent e)
         Point p=SwingUtilities.convertPoint(this,e.getPoint(),this.getParent());
         int x1 = p.x;
         int y1 = p.y;
         int diffX=x1-mx;
         int diffY=y1-my;
    /*new_mx = e.getX();
    new_my = e.getY();
    x += new_mx - mx;
    y += new_my - my;*/
    //System.out.println("depl de " + x +" y " + y);
    this.setText("Printing");
    setLocation(compX+diffX,compY+diffY);
    //mx = new_mx;
    //my = new_my;
    public void mouseMoved(MouseEvent e)
    public void mousePressed(MouseEvent e)
    Point p=SwingUtilities.convertPoint(this,e.getPoint(),getParent());
                   mx = p.x;
                   my = p.y;
                   compX=getBounds().x;
                   compY=getBounds().y;
    this.setText("Printing");
    public void mouseReleased(MouseEvent e)
    System.out.println("You have released at " + e.getX()+ " " + e.getY());
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
    }

  • I'm writing a mazerace game...I need help from a Java Pro regarding GUI

    I've tested my code using a textUI, but not successful with GUI.
    Following are the files I have at present but are incomplete...someone please assist me, let me know what I'm missing to run the program successfully in a window.
    All I need to do is to bring the maze (2D array) onto a window, and listen to the keys (A,S,D,W & J,K,L,I) and make the move accordingly (using the move method in the MazeRace Class)
    This is my class - MazeRace
    import javax.swing.*;
    import java.io.*;
    * This class is responsible for:
    * -Initializes instance variables used to store the current state of the game
    * -When a player moves it checks if the move is legal
    * and updates the state of the game if move is allowable and made
    * -Reports information about current state of the game when asked:
    * o whether game has been won
    * o how many moves have been made by a given player
    * o what is the current configuration of the maze, etc.
    public class MazeRace {
    /** The Maze Race layout */
    private static char[][] mazeLayout;
    /** Dimensions of the maze */
    //private static final int rowLength = mazeLayout.length;
    //private static final int columnLength = mazeLayout[0].length;
    /** space in the grid is a wall */
    private static final char wall = 'X';
    /** space in the grid has been used */
    private static final char spaceUsed = '.';
    /** space in the grid is available */
    private static final char spaceAvailable = ' ';
    /** Character for Charles, Ada & Goal*/
    private static final char CHARLES = 'C';
    private static final char ADA = 'A';
    private static final char GOAL = 'G';
    /** Location of Goal in the Maze */
    private static int rowGoal = 0;
    private static int columnGoal = 0;
    /** Location of Ada in the Maze */
    private static int rowAda = 0;
    private static int columnAda = 0;
    /** Location of Charles in the Maze */
    private static int rowCharles = 0;
    private static int columnCharles = 0;
    /** Number of Ada's moves */
    private static int countAdasMoves = 0;
    /** Number of Charles's moves */
    private static int countCharlesMoves = 0;
    * Constructor for MazeRace
    * &param mazeGrid - 2D array of characters
    public MazeRace(char[][] mazeGrid){
    this.mazeLayout = mazeGrid;
    for (int row = 0; row < mazeLayout.length; row++){
    for (int column = 0; column < mazeLayout[0].length; column++){
    if (mazeLayout[row][column] == GOAL){
    this.rowGoal = row;
    this.columnGoal = column;
    if (mazeLayout[row][column] == ADA){
    this.rowAda = row;
    this.columnAda = column;
    if (mazeLayout[row][column] == CHARLES){
    this.rowCharles = row;
    this.columnCharles = column;
    public boolean canMoveLeft(){
    int rowA = this.rowAda;
    int columnA = this.columnAda;
    int rowC = this.rowCharles;
    int columnC = this.rowCharles;
    boolean canMove = false;
    if (mazeLayout[rowA][columnA - 1] == spaceAvailable
    || mazeLayout[rowA][columnA - 1] == GOAL) {
    canMove = true;
    return canMove;
    * This method takes in a single character value that indicates
    * both the player making the move, and which direction the move is in.
    * If move is legal, the player's position will be updated. Move is legal
    * if player can move one space in that direction i.e. the player isn't
    * moving out of the maze, into a wall or a space has already been used.
    * @param moveDirection: indicates the player making the move and direction
    * @return moveMade: boolean value true if move was made, false otherwise
    public boolean move(char move){
    boolean validMove = false;
    /** store Ada's current row location in a temp variable */
    int rowA = this.rowAda;
    /** store Ada's current column location in a temp variable */
    int columnA = this.columnAda;
    /** store Charles current row location in a temp variable */
    int rowC = this.rowCharles;
    /** store Charles current column location in a temp variable */
    int columnC = this.columnCharles;
    /** if Ada is moving left, check if she can make a move */
    if (move == 'A' && (mazeLayout[rowA][columnA - 1] == spaceAvailable
    || mazeLayout[rowA][columnA - 1] == GOAL)) {
    /** if move is legal, then update old space to spaceUsed '.' */
    mazeLayout[rowA][columnA] = spaceUsed;
    /** update Ada's new position */
    mazeLayout[rowA][columnA - 1] = ADA;
    this.rowAda = rowA; //update new row location of Ada
    this.columnAda = columnA - 1; //update new column location of Ada
    validMove = true; //valid move has been made
    countAdasMoves++; //increment Ada's legal move
    /** if Ada is moving down, then check if she can make the move */
    if (move == 'S'&& (mazeLayout[rowA + 1][columnA] == spaceAvailable
    || mazeLayout[rowA + 1][columnA] == GOAL)) {
    mazeLayout[rowA][columnA] = spaceUsed;
    mazeLayout[rowA + 1][columnA] = ADA;
    this.rowAda = rowA + 1;
    this.columnAda = columnA;
    validMove = true;
    countAdasMoves++;
    /** if Ada is moving right, then check if she can make the move */
    if (move == 'D'&& (mazeLayout[rowA][columnA + 1] == spaceAvailable
    || mazeLayout[rowA][columnA + 1] == GOAL)) {
    mazeLayout[rowA][columnA] = spaceUsed;
    mazeLayout[rowA][columnA + 1] = ADA;
    this.rowAda = rowA;
    this.columnAda = columnA + 1;
    validMove = true;
    countAdasMoves++;
    /** if Ada is moving up, then check if she can make the move */
    if (move == 'W'&& (mazeLayout[rowA - 1][columnA] == spaceAvailable
    || mazeLayout[rowA - 1][columnA] == GOAL)) {
    mazeLayout[rowA][columnA] = spaceUsed;
    mazeLayout[rowA - 1][columnA] = ADA;
    this.rowAda = rowA - 1;
    this.columnAda = columnA;
    validMove = true;
    countAdasMoves++;
    /** if Charles is moving left, then check if he can make the move */
    if (move == 'J'&& (mazeLayout[rowC][columnC - 1] == spaceAvailable
    || mazeLayout[rowC][columnC - 1] == GOAL)) {
    mazeLayout[rowC][columnC] = spaceUsed;
    mazeLayout[rowC][columnC -1] = CHARLES;
    this.rowCharles = rowC;
    this.columnCharles = columnC - 1;
    validMove = true;
    countCharlesMoves++;
    /** if Charles is moving down, then check if he can make the move */
    if (move == 'K'&& (mazeLayout[rowC + 1][columnC] == spaceAvailable
    || mazeLayout[rowC + 1][columnC] == GOAL)) {
    mazeLayout[rowC][columnC] = spaceUsed;
    mazeLayout[rowC + 1][columnC] = CHARLES;
    this.rowCharles = rowC + 1;
    this.columnCharles = columnC;
    validMove = true;
    countCharlesMoves++;
    /** if Charles is moving right, then check if he can make the move */
    if (move == 'L'&& (mazeLayout[rowC][columnC + 1] == spaceAvailable
    || mazeLayout[rowC][columnC + 1] == GOAL)) {
    mazeLayout[rowC][columnC] = spaceUsed;
    mazeLayout[rowC][columnC + 1] = CHARLES;
    this.rowCharles = rowC;
    this.columnCharles = columnC + 1;
    validMove = true;
    countCharlesMoves++;
    /** if Charles is moving up, then check if he can make the move */
    if (move == 'I'&& (mazeLayout[rowC - 1][columnC] == spaceAvailable
    || mazeLayout[rowC - 1][columnC] == GOAL)){
    mazeLayout[rowC][columnC] = spaceUsed;
    mazeLayout[rowC - 1][columnC] = CHARLES;
    this.rowCharles = rowC - 1;
    this.columnCharles = columnC;
    validMove = true;
    countCharlesMoves++;
    return validMove;
    * This method indicates whether the current maze configuration is a winning
    * configuration for either player or not.
    * Return 1 if Ada won
    * Return 2 if Charles won
    * Return 0 if neither won
    * @return int won: Indicates who won the game (1 or 2) or no one won the
    * game (0)
    public static int hasWon() {
    int won = 0;
    /** if location of Goal's row and column equals Ada's then she won */
    if (rowGoal == rowAda && columnGoal == columnAda){
    won = 1;
    /** if location of Goal's row and column equals Charles's then he won */
    if (rowGoal == rowCharles && columnGoal == columnCharles){
    won = 2;
    /** if both players are away from the Goal then no one won */
    if ((rowGoal != rowAda && columnGoal != columnAda) &&
    (rowGoal != rowCharles && columnGoal != columnCharles)) {
    won = 0;
    return won;
    * This method indicates whether in the current maze configuration both
    * players are caught in dead ends.
    * @return deadEnd: boolean value true if both players can't make a valid
    * move, false otherwise
    public static boolean isBlocked(){
    boolean deadEnd = false;
    /** Check if Ada & Charles are blocked */
    if (((mazeLayout[rowAda][columnAda - 1] == wall
    || mazeLayout[rowAda][columnAda - 1] == spaceUsed
    || mazeLayout[rowAda][columnAda - 1] == CHARLES)
    && (mazeLayout[rowAda][columnAda + 1] == wall
    || mazeLayout[rowAda][columnAda + 1] == spaceUsed
    || mazeLayout[rowAda][columnAda + 1] == CHARLES)
    && (mazeLayout[rowAda + 1][columnAda] == wall
    || mazeLayout[rowAda + 1][columnAda] == spaceUsed
    || mazeLayout[rowAda + 1][columnAda] == CHARLES)
    && (mazeLayout[rowAda - 1][columnAda] == wall
    || mazeLayout[rowAda - 1][columnAda] == spaceUsed
    || mazeLayout[rowAda - 1][columnAda] == CHARLES))
    && ((mazeLayout[rowCharles][columnCharles - 1] == wall
    || mazeLayout[rowCharles][columnCharles - 1] == spaceUsed
    || mazeLayout[rowCharles][columnCharles - 1] == ADA)
    && (mazeLayout[rowCharles][columnCharles + 1] == wall
    || mazeLayout[rowCharles][columnCharles + 1] == spaceUsed
    || mazeLayout[rowCharles][columnCharles + 1] == ADA)
    && (mazeLayout[rowCharles + 1][columnCharles] == wall
    || mazeLayout[rowCharles + 1][columnCharles] == spaceUsed
    || mazeLayout[rowCharles + 1][columnCharles] == ADA)
    && (mazeLayout[rowCharles - 1][columnCharles] == wall
    || mazeLayout[rowCharles - 1][columnCharles] == spaceUsed
    || mazeLayout[rowCharles - 1][columnCharles] == ADA))) {
    deadEnd = true;
    return deadEnd;
    * This method returns an integer that represents the number of moves Ada
    * has made so far. Only legal moves are counted.
    * @return int numberOfAdasMoves: number of moves Ada has made so far
    public static int numAdaMoves() {
    return countAdasMoves;
    * This method returns an integer that represents the number of moves Charles
    * has made so far. Only legal moves are counted.
    * @return int numberOfCharlesMoves: number of moves Charles has made so far
    public static int numCharlesMoves() {
    return countCharlesMoves;
    * This method returns a 2D array of characters that represents the current
    * configuration of the maze
    * @return mazeLayout: 2D array that represents the current configuration
    * of the maze
    public static char[][] getGrid() {
    return mazeLayout;
    * This method compares contents of this MazeRace object to given MazeRace.
    * The two will not match if:
    * o the two grids have different dimensions
    * o the two grids have the same dimensios but positions of walls, players or
    * goal differs.
    * @param MazeRace: MazeRace object is passed in and compared with the given
    * MazeRace grid
    * @return boolean mazeEqual: true if both grids are same, false otherwise
    public static boolean equals(char[][] mr) {
    boolean mazeEqual = true;
    /** If the length of the arrays differs, then they are not equal */
    if (mr.length != mazeLayout.length || mr[0].length != mazeLayout[0].length){
    mazeEqual = false;
    } else {
    /** If lengths are same, then compare every element of the array to other */
    int count = 0;
    int row = 0;
    int column = 0;
    while( count < mr.length && mazeEqual) {
    if( mr[row][column] != mazeLayout[row][column]) {
    mazeEqual = false;
    count = count + 1;
    row = row + 1;
    column = column + 1;
    return mazeEqual;
    * This method represents the current state of the maze in a string form
    * @return string mazeString: string representation of the maze configuration
    public String toString() {
    String mazeString = "";
    for (int row = 0; row < mazeLayout.length; row++){
    for (int column = 0; column < mazeLayout[0].length; column++){
    mazeString = mazeString + mazeLayout[row][column];
    mazeString = mazeString + "\n";
    return mazeString.trim();
    The following is the Driver class: MazeRaceDriver
    import javax.swing.*;
    import java.io.*;
    * This class is the starting point for the maze race game. It is invoked
    * from the command line, along with the location of the layout file and
    * the desired interface type. Its main purpose is to initialize the
    * components needed for the game and the specified interface.
    public class MazeRaceDriver {
    * A method that takes a text file representation of the maze and
    * produces a 2D array of characters to represent the same maze.
    * @param layoutFileName location of the file with the maze layout
    * @return The maze layout.
    public static char[][] getLayoutFromFile( String layoutFileName )
    throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(layoutFileName));
    String s = br.readLine();
    int r = 0; // start at row 1
    int c = s.length(); // initialize column to the length of the string
    while(s != null){
    r++;
    s = br.readLine();
    char[][]grid = new char[r][c];
    // this part, gets the text file into a char array
    BufferedReader brr = new BufferedReader(new FileReader(layoutFileName));
    String ss = brr.readLine();
    int row = 0;
    while(ss != null){
    for(int col = 0; col < c; col++){
    grid[row][col] = ss.charAt(col);
    row++;
    ss = brr.readLine();
    return grid;
    * The main method of your program.
    * @param args command-line arguments provided by the user
    public static void main( String[] args ) throws IOException {
    // check for too few or too many command line arguments
    if ( args.length != 2 ) {
    System.out.println( "Usage: " +
    "java MazeRaceDriver <location> <interface type>" );
    return;
    if ( args[1].toLowerCase().equals( "text" ) ) {
    char[][] layout = getLayoutFromFile( args[0] );
    MazeRace maze = new MazeRace( layout );
    MazeRaceTextUI game = new MazeRaceTextUI( maze );
    game.startGame();
    else if ( args[1].toLowerCase().equals( "gui" ) ) {
    // Get the filename using a JFileChooser
    // read the layout from the file
    // starting the window-based maze game
    JFileChooser chooser = new JFileChooser("");
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    BufferedReader br =
    new BufferedReader(new FileReader(chooser.getSelectedFile()));
    String inputLine = br.readLine();
    while (inputLine != null) {
    System.out.println(inputLine);
    inputLine = br.readLine();
    char[][] layout = getLayoutFromFile( args[0] );
    MazeRace maze = new MazeRace( layout );
    MazeRaceWindow game = new MazeRaceWindow( maze );
    game.startGame();
    } else {
    System.out.println("Cancel was selected");
    } else {
    System.out.println( "Invalid interface for game." +
    " Please use either TEXT or GUI." );
    return;
    The following is the MazeRaceWindow class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    * This class is responsible for displaying the maze race game. It should
    * set up the maze window when the game is started and update the display
    * with each move.
    public class MazeRaceWindow extends JFrame {
    private JLabel[][] mazeLabel;
    private JFrame mazeFrame;
    * Reference to the underlying MazeRace object which needs to be
    * updated when either player moves
    private MazeRace maze;
    * Class constructor for the GUI object
    * @param maze the underlying MazeRace object
    public MazeRaceWindow( MazeRace maze ) {
    this.maze = maze;
    System.out.println(maze);
    mazeFrame = new JFrame();
    mazeFrame.setSize(200,200);
    Container content = mazeFrame.getContentPane();
    System.out.println(content);
    content.setLayout(new GridLayout(.length, mazeLayout[0].Length));
    for (int i = 0; i < MazeRace.length; i++ ) {
    for (int j = 0; j < MazeRace[0].length; j++ ) {
    mazeLabel = new JLabel[MazeRace.rowLength][MazeRace.columnLength];
    content.add(mazeLabel[i][j]);
    System.out.println(mazeLabel[i][j]);
    mazeFrame.pack();
    mazeFrame.setVisible(true);
    //content.add(mazeLabel);
    //mazeFrame.addKeyListener(this);
    * A method to be called to get the game running.
    public void startGame() throws IOException {
    System.out.println();
    /* loop to continue to accept moves as long as there is at least one
    * player able to move and no one has won yet
    while ( !maze.isBlocked() && maze.hasWon() == 0 ) {
    // prints out current state of maze
    System.out.println( maze.toString() );
    System.out.println();
    // gets next move from players
    System.out.println("Next move?");
    System.out.print("> ");
    BufferedReader buffer =
    new BufferedReader( new InputStreamReader( System.in ) );
    String moveText = "";
    moveText = buffer.readLine();
    System.out.println();
    // note that even if a string of more than one character is entered,
    // only the first character is used
    if ( moveText.length() >= 1 ) {
    char move = moveText.charAt( 0 );
    boolean validMove = maze.move( move );
    // The game has finished, so we output the final state of the maze, and
    // a message describing the outcome.
    System.out.println( maze );
    int status = maze.hasWon();
    if ( status == 1 ) {
    System.out.println( "Congratulations Ada! You won the maze in "
    + maze.numAdaMoves() + " moves!" );
    } else if ( status == 2 ) {
    System.out.println( "Congratulations Charles! You won the maze in "
    + maze.numCharlesMoves() + " moves!" );
    } else {
    System.out.println( "Stalemate! Both players are stuck. "
    + "Better luck next time." );
    The following is the Listener class: MazeRaceListener
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    /** Listens for keystrokes from the GUI interface to the MazeRace game. */
    public class MazeRaceListener extends KeyAdapter {
    * Reference to the underlying MazeRace object which needs to be updated
    * when either player moves
    private MazeRace maze;
    * Reference to the MazeRaceWindow object that displays the state of
    * the game
    private MazeRaceWindow mazeWindow;
    * Class constructor for the key listener object
    * @param maze the underlying MazeRace object
    public MazeRaceListener( MazeRace maze ) {
    this.maze = maze;
    * A method that sets which JFrame will display the game and need to be
    * updated with each move.
    * @param window the JFrame object that displays the state of the game
    public void setMazeRaceWindow( MazeRaceWindow window ) {
    mazeWindow = window;
    * A method that will be called each time a key is pressed on the active
    * game display JFrame.
    * @param event contains the pertinent information about the keyboard
    * event
    public void keyTyped( KeyEvent event ) {
    char move = event.getKeyChar();
    // TODO: complete method so that the appropriate action is taken
    // in the game
    //mazeLabel.setText(String.valueOf(move).toUpperCase());
    }

    and listen to the keys (A,S,D,W & J,K,L,I) and make the move accordingly [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings

  • Need advice on what component(s) to use

    I'm trying to put together a UI that displays a background image and displays on top of that image several jpanels, jlabels, and icon type images . I'd like the user to be able to drag the panels etc. to a desired location.
    I'll then need to grab the coordinates and store them to a file, so that I can rebuild the UI with the components in the same place that they were placed when restarting the application
    Wow that was hard to put into words.
    The idea is the image will be a layout and the panels will be the physical position of a data source. A bit like in home automation programs that shows a layout of the house with the locations of cameras and switches etc.
    So I'm thinking JInternalFrames may work but I need something that is transparent.
    Any advice or a push in the right direction before I dive in will be greatly appreciated.
    Edited by: xavier33 on Feb 22, 2008 4:08 PM

    panels would work equally as well, but you're still going to have the same problem (from your first post)
    "I'm trying to put together a UI that displays a background image and displays on top of that image several jpanels, jlabels, and icon type images ."
    if any of the add-ons has a listener, you'll have to pass on the event to the panel.
    this might be close enough - a small area at the top, when the cursor changes you can drag the panel around
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      int xPos, yPos;
      Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
      Cursor moveCursor = new Cursor(Cursor.MOVE_CURSOR);
      public void buildGUI()
        ImageBackgroundPanel backgroundImage = new ImageBackgroundPanel("test.gif");
        backgroundImage.setLayout(null);
        final JPanel viewPanel = new JPanel(new BorderLayout());
        viewPanel.setOpaque(false);
        viewPanel.setBounds(0,0,100,100);
        final JPanel p = new JPanel();
        p.setOpaque(false);
        p.setPreferredSize(new Dimension(viewPanel.getWidth(),10));
        viewPanel.add(p,BorderLayout.NORTH);
        viewPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));//<---just so you can see it moving
        backgroundImage.add(viewPanel);
        JFrame f = new JFrame();
        f.getContentPane().add(backgroundImage);
        f.setSize(600,400);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        p.addMouseListener(new MouseAdapter(){
          public void mousePressed(MouseEvent me){
            xPos = me.getX();
            yPos = me.getY();
          public void mouseEntered(MouseEvent me){
            p.setCursor(moveCursor);
          public void mouseExited(MouseEvent me){
            p.setCursor(normalCursor);
        p.addMouseMotionListener(new MouseMotionAdapter(){
          public void mouseDragged(MouseEvent me){
            Point vp_p = viewPanel.getLocation();
            Point me_p = me.getPoint();
            viewPanel.setLocation(vp_p.x + me_p.x - xPos,vp_p.y + me_p.y - yPos);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    class ImageBackgroundPanel extends JPanel
      Image img;
      public ImageBackgroundPanel(String file)
        try
          img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource(file), file));
        catch(Exception e){}//handled in paintComponent
      public void paintComponent(Graphics g)
        super.paintComponent(g);
        if(img != null) g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
    }

  • How to close JWindow and keep it front

    my main opens a fullscreen jframe and then a smaller Jwindow.
    i called toFront but the Jwindow is always hidden behind
    the jframe. how do i keep jwindow in front ALWAYS.
    also, i have a mouselistener in the jwindow (that works fine)
    and im calling
    window.setVisible(false);
    window.dispose();
    but the jwindow is never disappearing.
    anybody have any suggestions? thanks!

    I can't reproduce your problems. Here's my code.import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test3 extends JFrame implements ActionListener {
      JWindow jw = new JWindow(this);
      JButton jb = new JButton("Show");
      public Test3() {
        jw.setBounds(100,100,100,100);
        jw.getContentPane().add(new JLabel("I am Window!", JLabel.CENTER));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.add(jb, BorderLayout.SOUTH);
        content.setBackground(Color.pink);
        jb.addActionListener(this);
        setSize(300,300);
        setVisible(true);
      public void actionPerformed(ActionEvent ae) {
        if (jb.getText().equals("Show")) {
          jw.setVisible(true);
          jb.setText("Hide");
        } else {
          jw.setVisible(false);
          jb.setText("Show");
      public static void main(String[] args) { new Test3(); }
    }

  • BufferedImage causing OutOfMemoryError not getting GC'd

    I'm writing a photo library application just for practice. I'm trying to display all the jpegs in an album by displaying thumbnails of them as ImageIcons in JLabels on a JFrame.
    To get the images I use ImageIO.read(File) into a BufferedImage. Then using Image.getScaledInstance I pass the resized image to a new ImageIcon which is added to the JLabel. This all happens in a final class ThumbDisplay, method showPic which returns the JLabel.
    I call ThumbDisplay.showPic(File) in a loop, and it can read about 5 files before throwing an OutOfMemoryError. I have been able to successfully display no more than 4 images. Most of my images were taken on my digital camera and are around 2560X1920.
    I read a bit about the java heap space and I understand how 5 BufferedImages of that size open at once can easily eat up memory. But the code looks to me that any instantiated BufferedImages would be GC'd as soon as the showPic method returned the JLabel. JHAT proved otherwise and there were still 5 instances of BufferedImage when I got the OutOfMemoryError.
    So, the following is my example code block and the StackTrace. No extra stuff required. Just throw about 10 extra large jpegs in whatever path you choose to put in 'File directory' on line 9, compile and run. I'd really appreciate some help on this. I've searched countless message boards for that error and found many similar topics but ZERO answers. Can someone tell me why these aren't getting GC'd?
    code:
    1. import javax.swing.*; 
       2. import java.awt.image.*; 
       3. import javax.imageio.*; 
       4. import java.awt.*; 
       5. import java.io.*; 
       6.  
       7. public class ThumbTest{ 
       8.     public static void main(String args[]){ 
       9.         File directory = new File("c:\\pictemp\\"); 
      10.         File[] files = directory.listFiles(); 
      11.         JFrame jf = new JFrame(); 
      12.         jf.setSize(1000,1000); 
      13.         jf.setLayout(new GridLayout(10,10,15,15)); 
      14.         for(File file : files) 
      15.             jf.add(ThumbDisplay.showPic(file)); 
      16.          
      17.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      18.         jf.setVisible(true); 
      19.  
      20.  
      21.     } 
      22. } 
      23.  
      24. final class ThumbDisplay{ 
      25.      
      26.     public static JLabel showPic(File f){ 
      27.         BufferedImage img = null; 
      28.         try{ 
      29.             img = ImageIO.read(f); 
      30.         }catch (IOException e){ 
      31.             e.printStackTrace(); 
      32.         } 
      33.         if(img != null){ 
      34.             float ratio = 100 / (float) img.getHeight(); 
      35.             int w = Math.round((float)img.getWidth() * ratio); 
      36.             int h = Math.round((float)img.getHeight() * ratio); 
      37.             return new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT))); 
      38.         } else 
      39.             return new JLabel("no image"); 
      40.     } 
      41. }exception:
       1. D:\java\Projects\PhotoLibrary>java ThumbTest 
       2. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space 
       3.         at java.awt.image.DataBufferByte.<init>(Unknown Source) 
       4.         at java.awt.image.ComponentSampleModel.createDataBuffer(Unknown Source) 
       5.         at java.awt.image.Raster.createWritableRaster(Unknown Source) 
       6.         at javax.imageio.ImageTypeSpecifier.createBufferedImage(Unknown Source) 
       7.         at javax.imageio.ImageReader.getDestination(Unknown Source) 
       8.         at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(Unknown Sou 
       9. rce) 
      10.         at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(Unknown Source) 
      11.         at javax.imageio.ImageIO.read(Unknown Source) 
      12.         at javax.imageio.ImageIO.read(Unknown Source) 
      13.         at ThumbDisplay.showPic(ThumbTest.java:29) 
      14.         at ThumbTest.main(ThumbTest.java:15) 

    sjasja wrote:
    ImageIO.read() does not cache images. Run ImageIO.read() in a loop for a large image. No OOME.
    Run the OP's original program under hprof. See in hprof's output how the original image data are retained. Gives an OOME, and hprof's output shows where the memory goes.
    After creating a resized image with Image.getScaledInstance(), make a copy of the resized image and discard the first resized image. (Create a BufferedImage, get a Graphics2D, and blit with g.drawImage()). Discarding the resized image will also make the pointer to the original large image go away, allowing GC. No OOME.
    In the OP's program, edit like so:
    // return new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT))); 
    new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT)));
    return new JLabel("yes image");You are now doing all the image loading and resizing the original program does. But because the JLabel is discarded, the pointer to the resized image is discarded, thus the pointer to the original image is discarded, and everything can be GCd. No OOME.
    If you want to see how the scaled image retains a pointer to the original image, see the interaction of Image.getScaledImage(), BufferedImage.getSource(), java.awt.image.FilteredImageSource, sun.awt.image.OffScreenImageSource, and sun.awt.image.ToolkitImage.
    By these experiments, in a reply above, I guesstimated: "As far as I can figure out, Image.getScaledInstance() keeps a pointer to the original image."
    Yes, getScaledInstance() is somewhat slow. Here is the FAQ entry for a better way to resize an image: http://java.sun.com/products/java-media/2D/reference/faqs/index.html#Q_How_do_I_create_a_resized_copy
    I have a problem with this because it should mean that the code fragment I posted in reply #5 should make no difference but I can load over a thousand images using it whereas the original code allowed me to load only 30 or so.
    I can see how creating a buffered image from the scaled image might help since discarding the scaled image will discard any reference to the original image stored in the scaled image.

  • Question about adding multiple components....

    .....HI, i really hope someone can help out......
    When I try to add mutilple components to the panel, it won't show the components that I have added before again.....
    For example, I have a Icon Label and I want it to show two of the same Label again in the panel.... but it won't... it will just show one of them....
    for example:
    Label[] dice = new Label[6]
    Icon bug[] = new Icon[6];
    String dicePics[] = {"1.jpg", "2.jpg","3.jpg",
    "4.jpg","5.jpg","6.jpg",};
    for(int i=0; i<6; i++){
    bug[i] = new ImageIcon(dicePics);
    dice[i] = new JLabel();
    dice[i].setIcon( bug[i] );
    userPanel.add(dice[0]);
    userPanel.add(dice[0]);
    This will only show dice[0] once in panel........ how can I show the same things over again in a panel more then once.........?? I also try it on other things... when adding a component with same name, it will just show one of them.......... wondering if someone can help me out.......

    .....HI, i really hope someone can help out......
    When I try to add mutilple components to the panel,
    it won't show the components that I have added before
    again.....
    For example, I have a Icon Label and I want it to
    show two of the same Label again in the panel.... but
    it won't... it will just show one of them....
    for example:
    Label[] dice = new Label[6]
    Icon bug[] = new Icon[6];
    String dicePics[] = {"1.jpg", "2.jpg","3.jpg",
    "4.jpg","5.jpg","6.jpg",};
    for(int i=0; i<6; i++){
    bug[i] = new ImageIcon(dicePics);
    dice[i] = new JLabel();
    dice[i].setIcon( bug[i] );
    l.add(dice[0]);
    userPanel.add(dice[0]);
    This will only show dice[0] once in panel........ how
    can I show the same things over again in a panel more
    then once.........?? I also try it on other
    things... when adding a component with same name, it
    will just show one of them.......... wondering if
    someone can help me out.......
    You can't add the same GUI object to a Container multiple times. The problem is with your design. Consider something like this:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class DieLabelTest {
        private Random rand = new Random();
        private final JLabel[] dies = new JLabel[6];
        DieLabelTest() {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel diePanel = new JPanel(new GridLayout(3,0,5,5));
            for (int i = 0; i < 6; i++) {
                dies[i] = new JLabel();
                dies.setIcon(DieIconProvider.getIcon(rand.nextInt(6) + 1));
    diePanel.add(dies[i]);
    f.add(diePanel, BorderLayout.CENTER);
    JButton rollButton = new JButton("Roll");
    rollButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    for (int i = 0; i < 6; i++) {
    dies[i].setIcon(DieIconProvider.getIcon(rand.nextInt(6) + 1));
    f.add(rollButton, BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
    public static void main(String[] args) {
    new DieLabelTest();
    class DieIconProvider {
    private static Icon[] icons = new Icon[6];
    public static synchronized Icon getIcon(int num) {
    if (icons[num - 1] == null) {
    icons[num - 1] = new ImageIcon(num + ".jpg");
    return icons[num -1];

  • Possible to update gui with new thread AND halt program execution?

    Hello, my problem is the following:
    I have a JButton that performs a sql query and retrieves information from a database, while this is done I would like to update a JLabel with information that the query is in progress. I have got this working but the problem is that I would like the main thread to wait until the search thread has finished execution, of course this inflictes with the gui update... look below for code:
    //class that synchronizes the threads when retrieving data
    public class SynkroniseradVektorKlass
       private Vector verde = new Vector();
       private boolean inteFerdig=true;
       public SynkroniseradVektorKlass(boolean inteFerdig)
          this.inteFerdig=inteFerdig;
       //sets the value of the vector
       public synchronized void settVerde(Vector verde)
           this.verde=verde;
           //set the boolean to false so the wait() can be avoided
           inteFerdig=false;
           //notify all threads that we have retrieved a value
           notifyAll();
        public synchronized Vector returneraVerde()
            //if no value has been retrieved, wait
            if(inteFerdig)
               try
                    wait();
               catch(InterruptedException ie){}
        //when waiting is done, return value
        return verde;
    //class that retrieves data and prints it
    //not really necessary here but useful to check that the SynkronisedVektorKlass
    // works
    public class TradHarDataKommit extends Thread
       private SynkroniseradVektorKlass hemtaData;
       public TradHarDataKommit(SynkroniseradVektorKlass hemtaData)
          this.hemtaData=hemtaData;
       public void run()
           System.out.println("Thread two begins");
           System.out.println("data == "+hemtaData.returneraVerde());
           System.out.println("Thread two done");
    //class that communicates with the database and retrieves the data
    public class NyTradKorSQLSats extends Thread
       private String sqlSats;
       private java.util.Timer timer;
       private JLabel label;
       private JFrame ram;
       private SynkroniseradVektorKlass tilldelaData;
       public NyTradKorSQLSats(String sqlSats,java.util.Timer timer,JLabel ,SynkroniseradVektorKlass tilldelaData,JFrame ram)
          this.sqlSats=sqlSats;
          this.timer=timer;
          this.label=label;
          this.tilldelaData=tilldelaData;
          this.ram=ram;
       public void run()
           System.out.println("Thread one begins...");
           //executes the sql query and retrieve data
           tilldelaData.settVerde(klient.korKlient(sqlSats));
           //end the timer that updates the JLabel
           timer.cancel();
           label.setText("");
           ram.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
           System.out.println("Thread one done...");
    //in actionPerformed
    java.util.Timer timer = new java.util.Timer();
    //boolean used to show when execution is done          
    boolean sokningInteFerdig=true;
    //class that holds a value retrieved from database and make sure that
    //everything is synchronized
    SynkroniseradVektorKlass dataFranSokning = new SynkroniseradVektorKlass(sokningInteFerdig);
    //class that retrieves information from dataFranSokning     
    TradHarDataKommit skrivUtData = new TradHarDataKommit(dataFranSokning);
    //class that executes sql query, with arguments sql, a timer that updates
    //the JLabel,the JLabel,the dataholding class, and a JFrame     
    NyTradKorSQLSats korTrad = new NyTradKorSQLSats("1Select namn from kundregister where kundnr=1",timer,statusRad,dataFranSokning,this);
    //a TimerTask class that updates the JLabel               
    TimerStatusRad task1 = new TimerStatusRad(statusRad,"Searching...",this);
    TimerStatusRad task2 = new TimerStatusRad(statusRad," ",this);
    //starts timer task1 directly and restarts every second
    timer.schedule(task1,0,1000);
    //starts timer task 2 after a second and restarts every second after     
    timer.schedule(task2,1000,1000);
    //set the sqlthread to daemon
    korTrad.setDaemon(true);
    //starts the thread                         
    korTrad.start();
    //I would like that the program halts here until korTrad is done
    //because the data retrieved are to be used further in the program
    //There is no point in using join(); because this would halt the update of the guiif anyone got any ideas how to solve this please help me
    ps. sorry about my english, its not my native language

    Was not able to review all of your code. But take a look at wait() and update() methods - they should solve what you need.
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • Draw a line using mouse

    Hello there:
    I'm trying to draw a line using mouse pointer: My code is:
    public class DrawLine extends JFrame implements MouseListener, MouseMotionListener
        int x0, y0, x1, y1;  
        public DrawLine()
             addMouseListener(this);
             addMouseMotionListener(this);
        public void mouseDragged(MouseEvent e)
             x1 = e.getX();
             y1 = e.getY();
             repaint();
        public void mouseMoved(MouseEvent e) { }
        public void mouseClicked(MouseEvent e){ }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited (MouseEvent e) { }
        public void mousePressed(MouseEvent e)
              x0 = e.getX();
              y0 = e.getY();           
        public void mouseReleased(MouseEvent e)
              x1 = e.getX();
              y1 = e.getY();
       public void paint(Graphics g)
                 g.setColor(Color.BLACK);
              g.drawLine(x0, y0, x1, y1);
        public static void main(String[] argv)
             DrawLine dr=new DrawLine("Test");
             dr.setVisible(true);
             dr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }when mouse is dragged, multiple lines are being drawn....
    could you else please tell me what should I've to do???
    thanks n regards...
    Dev

    You can implement the listeners on any class, even one that (implicitly) extends Object. What matters is that the listener is added to the component that needs to use it.
    That said, why do you want to extend JFrame? Are you adding functionality to the JFrame to justify extending the JFC class? Note that extending JFrame allows the users of your class to access the functionality of a JFrame, is that really indicated here?
    one class that extends JFrame, and one can draw a line on JLabel, embedded within JFrame!So you still have to override paintComponent of the JLabel, which implies using an anonymous inner class.
    Starting with the example already posted, that would be:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    public class DrawLineTest
        implements MouseListener, MouseMotionListener {
      JLabel label;
      int x0, y0, x1, y1;
      private void makeUI() {
        JFrame frame = new JFrame("DrawLineTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label = new JLabel("FFFF") {
          public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.BLACK);
            g.drawLine(x0, y0, x1, y1);
        label.setPreferredSize(new Dimension(500, 500));
        label.addMouseListener(this);
        label.addMouseMotionListener(this);
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            new DrawLineTest().makeUI();
      public void mousePressed(MouseEvent e) {
        x0 = e.getX();
        y0 = e.getY();      
      public void mouseReleased(MouseEvent e) {
        x1 = e.getX();
        y1 = e.getY();
      public void mouseDragged(MouseEvent e) {
        x1 = e.getX();
        y1 = e.getY();
        label.repaint();
      public void mouseMoved(MouseEvent e) { }
      public void mouseClicked(MouseEvent e){ }
      public void mouseEntered(MouseEvent e) { }
      public void mouseExited (MouseEvent e) { }
    }Better spend more time with the tutorials, there's a separate section on writing event listeners.
    db

Maybe you are looking for

  • Mod_wl_22.so with Apache 2.4

    Hello I have just upgraded Apache http server from 2.22 to 2.4. It configured ok ("It works"). It is used to forward calls to our OBIEE installation and for this we use a module plugin, the mod_wl_22.so It doesn't work. Starting Apache presents the f

  • Cannot open a document in adobe reader x

    I cannot open a document(.pdf)  under recent documents as i get an error message that the file cannot be found? Why?  I did open both of them the other day. Under recent files both of these documents are listed in duplicate. Thanks for your help.

  • How to write XSJS Select Query with input parameters

    Hello Experts, I am creating a xsjs file and in that file I am trying to write a Select Query based on a Calculation View I have tried it the following way: var query = 'SELECT TOP 100 \"Name\", \"Address\", \"City\", \"Country\" FROM \"_SYS_BIC\".\"

  • Multiple users responsible selection in QM01 to send the email

    Hi, In QM01 we use to create the notification as per the notification type. We are using Noti. Type Q6 (Finance Notification). In the Partner field we used to put number  of person responsible and then we used to click on the SEND EMAIL , a screen po

  • I paid for basic program to convert PDF to Word or Excel - how to operate??

    I paid for the basic program to convert PDF's to Word or Excel Documents.  When I pull up the PDF I want to export and click on export icon in the tool bar it takes me back to sign up for the service which I have already paid for and received email c