Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: A problem with JLabel!

  1. #1
    Junior Member
    Join Date
    Dec 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default A problem with JLabel!

    Hi!

    I am a beginner and I am learning to program on my spare time. I am working with a website to have a goal with learning Java instead of just making small programs... I have written lots of the code for handling input and publishing stuff on the website. Now I have come to the graphical part and I am stuck...

    My idea is to have an applet with a text area. There is going to be a lot of buttons around the window. And when you push a button text will be published in the text area. My idea is to use JLabel to publish the text because then I can read HTML files and publish the HTML code directly.

    However, I do not understand really how JLabels work. I have tried with "setBounds(0,100,600,800)" in order to change the size and position of the JLabel and in some way that works but not fully. Instead the program will publish the JLabel in the center of the applet. When I click the button more JLabels are published but nothing happens in the text area. Really grateful if someone could help me because I am really stuck and I don't have anyone else to ask for advice...

    You can view the applet [HERE]...

    /Niklas


    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
     
     
    public class Applet4 extends JApplet {
     
    	/**a
    	 * @param args
    	 */
    	public static void main(String[] args) {
     
    		JFrame window = new JFrame("Simple Paint");
    		DrawBackground content = new DrawBackground();
    		window.setContentPane(content);
    	    window.setSize(1000,480);
    	    window.setLocation(0,0);
    	    window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    	    window.setVisible(true);
     
    	}
     
     
    	public void init() {
     
    		setContentPane( new DrawBackground() );
     
     
    	}
     
    	public static class DrawBackground extends JPanel implements MouseListener, MouseMotionListener {
     
    		private JLabel theLabel;
     
    		private Cursor previousCursor;
     
    		DrawBackground () {
    			System.out.println("Constructor");
    	        addMouseListener(this);
    	        addMouseMotionListener(this);
     
     
     
    		}
     
    		public void paintComponent (Graphics g) {
     
    			JLabel aNewLabel;
     
    			setBackground(Color.YELLOW);
    			setOpaque(true);
    			System.out.println("Background");
    			super.paintComponent(g);
     
    			g.setColor(Color.LIGHT_GRAY);
    			g.fillRect(10, 10, 40, 40);
     
    			//Draw the text area
    			theLabel = HtmlDisplay2();
    			theLabel.setBackground(Color.WHITE);
    			theLabel.setOpaque(true);
    			theLabel.setBounds(0,100,600,800);
    	        add(theLabel);
     
     
     
    		}
     
     
    		public void mousePressed(MouseEvent evt) { }
    		public void mouseClicked(MouseEvent evt) { 			
    			int x = evt.getX();   // x-coordinate where the user clicked.
    			int y = evt.getY();   // y-coordinate where the user clicked.
     
    			JLabel aNewLabel;
     
    			if (x >= 10 && x <= 50 && y >= 10 && y <= 50) {
    				Graphics g = getGraphics();
    				g.setColor(Color.BLUE);
    				g.fillRect(10, 10, 40, 40);
     
    				String testar = "<html>Testing 2</html>";
    				aNewLabel = new JLabel(testar);
    				aNewLabel.setBackground(Color.WHITE);
    				aNewLabel.setOpaque(true);
    				aNewLabel.setBounds(0,100,600,800);
    				add(aNewLabel);
    				updateUI();
    			}
    		}
    		public void mouseReleased(MouseEvent evt) { }
    		public void mouseEntered(MouseEvent evt) { }
    		public void mouseExited(MouseEvent evt) { }
    		public void mouseMoved(MouseEvent evt) { 
     
    			Graphics g = getGraphics();
     
    			int x = evt.getX();   // x-coordinate where the user clicked.
             	int y = evt.getY();   // y-coordinate where the user clicked.
     
    //         	System.out.println("(" + x + ", " + y + ")");
             	if (x >= 10 && x <= 50 && y >= 10 && y <= 50) {
        			g.setColor(Color.ORANGE);
        			g.fillRect(10, 10, 40, 40);
             		setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
               	}
             	else {
        			g.setColor(Color.LIGHT_GRAY);
        			g.fillRect(10, 10, 40, 40);
             		setCursor(previousCursor);
             	}
     
    		}
    		public void mouseDragged(MouseEvent evt) { }
     
     
     
    		private JLabel HtmlDisplay2() {
    			JLabel aLabel;
     
     
    				String html_text = "<html>\n" +
    		        "Color and font test:\n" +
    		        "<ul>\n" +
    		        "<li><font color=red>red</font>\n" +
    		        "<li><font color=blue>blue</font>\n" +
    		        "<li><font color=green>green</font>\n" +
    		        "<li><font size=-2>small</font>\n" +
    		        "<li><font size=+2>large</font>\n" +
    		        "<li><i>italic</i>\n" +
    		        "<li><b>bold</b>\n" +
    		        "</ul>\n";
     
    				aLabel = new JLabel(html_text);
     
     
    				return aLabel;
     
     
    		}
     
     
     
    	}
     
    }


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,659
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: A problem with JLabel!

    JLabels really shouldn't be used for anything other than Labeling and little 1-line things. The reason is because JLabel's abilities and interactive capabilities are very primitive compared to other Swing Elements. Your goals can definitely be done with JLabels, but it will be far more difficult and tedious than it needs to be.

    If your concern is reading HTML files, I would suggest having a look into JEditorPane:
    API: JEditorPane (Java Platform SE 6)
    Tutorial: Using Text Components (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)

    JEditorPanes will give you a MUCH larger range of capabilities and functionality than what JLabels will give you. You can think of JEditorPanes as JTextAreas with a larger range of specific functionality. I am no expert by any means on using JEditorPanes, but I know there are some people on this forum that know about them fairly well.
    Last edited by aussiemcgr; December 14th, 2010 at 05:06 PM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Dec 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: A problem with JLabel!

    Thanks for your reply!

    I will look into how to use JEditorPane instead. Unfortuneately, I will not have time until this weekend...

    However, I would appreciate if you or someone else could explain to me why I can't place a JLabel at a specific position. You must be able to place a JLabel wherever you want to even if JLabels are for simpler labeling?
    In my applet it works to place a JLabel for one case. The problem is that it simultaneously put the same JLabel in the centre of the applet.

    The applet is available [HERE].

    Thanks in advance!

    /Niklas

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,297
    Thanks
    180
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: A problem with JLabel!

    Organization, layout, and location of components is based upon layout managers (see Using Layout Managers) which organize the layout based upon many factors (such as window size and resize, etc...). You should select the appropriate manager for your needs.

    Next, the code adds JLabels after the parent component is realized. To dynamically add components to a container, you should call revalidate() and repaint() on said component

  5. #5
    Junior Member
    Join Date
    Dec 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: A problem with JLabel!

    copeg>>I studied the pages you sent me and managed to get the layout problems to work. Thanks you!

    aussiemcgr>>I tried JEditorPane and it worked also. There was only one problem and that was that I could see the HTML code in the applet when I ran i locally on my computer but the HTML page was not read when I uploaded the applet on the server. The HTML page I tried to display was all the time on the same server. I will look into that more later... Thanks for the tip with JEditorPane!

    My applet now works almost as I want it to. The only problem is that the new JPanel which appears after I have clicked the button disappears if I resize the window, scrolls or switch windows. Then "paintComponent" is addressed and I loose the information. I have gone through the API for Containers but I can not find any appropriate method which can repaint the "new" JPanel. Does anyone has a solution for this?

    The applet is available [HERE].

    Thanks in advance!

    The new applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
     
     
    public class Applet4 extends JApplet {
     
     
    	/**a
    	 * @param args
    	 */
    	public static void main(String[] args) {
     
    	}
     
     
    	public void init() {
     
    		this.setContentPane(new DrawBackground());
    		this.setLayout(null);
     
    	}
     
    	public static class DrawBackground extends JPanel implements MouseListener, MouseMotionListener {
     
     
     
    		private Cursor previousCursor;
     
    		DrawBackground () {
    			System.out.println("Constructor");
    	        addMouseListener(this);
    	        addMouseMotionListener(this);
     
    		}
     
     
    		public void paintComponent (Graphics g) {
     
    			setBackground(Color.YELLOW);
    			setOpaque(true);
    			double random = Math.random();
    			System.out.println("Background " + random);
    			super.paintComponent(g);
     
    			g.setColor(Color.LIGHT_GRAY);
    			g.fillRect(10, 10, 40, 40);
     
     
    			JPanel testing_ = new JPanel();
    			testing_.setLayout(null);
    			testing_.setBackground(Color.WHITE);
    			testing_.setBounds(0,100,600,800);
    			add(testing_);
     
    			}
     
     
    		public void mousePressed(MouseEvent evt) { }
    		public void mouseClicked(MouseEvent evt) { 			
    			int x = evt.getX();   // x-coordinate where the user clicked.
    			int y = evt.getY();   // y-coordinate where the user clicked.
     
    			if (x >= 10 && x <= 50 && y >= 10 && y <= 50) {
     
    				Graphics g = getGraphics();
     
    				g.setColor(Color.BLUE);
    				g.fillRect(10, 10, 40, 40);
     
    				String test = "Testing 2";
    				JLabel aLabel = new JLabel(test);
    				JPanel testing_2 = new JPanel();
    				aLabel.setLayout(null);
    				aLabel.setBounds(0,100,600,800);
     
    				testing_2.setLayout(new BorderLayout());
    				testing_2.add(aLabel, BorderLayout.NORTH);
    				testing_2.setBackground(Color.GREEN);
    				testing_2.setLayout(null);
    				testing_2.setBounds(0,100,600,800);
    				testing_2.setVisible(true);
    				add(testing_2);
    				testing_2.repaint();
     
    			}
    		}
    		public void mouseReleased(MouseEvent evt) { }
    		public void mouseEntered(MouseEvent evt) { }
    		public void mouseExited(MouseEvent evt) { }
    		public void mouseMoved(MouseEvent evt) { 
     
    			Graphics g = getGraphics();
     
    			int x = evt.getX();   // x-coordinate where the user clicked.
             	int y = evt.getY();   // y-coordinate where the user clicked.
     
    //         	System.out.println("(" + x + ", " + y + ")");
             	if (x >= 10 && x <= 50 && y >= 10 && y <= 50) {
        			g.setColor(Color.ORANGE);
        			g.fillRect(10, 10, 40, 40);
             		setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
               	}
             	else {
        			g.setColor(Color.LIGHT_GRAY);
        			g.fillRect(10, 10, 40, 40);
             		setCursor(previousCursor);
             	}
     
    		}
    		public void mouseDragged(MouseEvent evt) { }
     
     
    	}
     
    }

  6. #6
    Junior Member
    Join Date
    Dec 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: A problem with JLabel!

    Hi again!

    I re-thinked a little bit and solved the problem with the update of the text area. Now everything works and I a base to continue working on!

    You can see the applet [HERE].

    Thanks for all the help!!!

    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
     
    import javax.swing.*;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkListener;
    import javax.swing.text.Document;
     
     
     
    public class Applet5 extends JApplet {
     
    	public static String urltest = "http://www.vaxjook.se/blueberry/test/legs/etappmall.html";
     
    	/**a
    	 * @param args
    	 */
    	public static void main(String[] args) {
     
    	}
     
     
    	public void init() {
     
    		this.setContentPane(new DrawBackground());
    		this.setLayout(null);
     
    	}
     
    	public static class DrawBackground extends JPanel implements MouseListener, MouseMotionListener {
     
     
    		private Cursor previousCursor;
     
    		DrawBackground () {
    			System.out.println("Constructor");
    	        addMouseListener(this);
    	        addMouseMotionListener(this);
     
    		}
     
     
    		public void paintComponent (Graphics g) {
     
    			System.out.println(urltest);
     
    			setBackground(Color.YELLOW);
    			setOpaque(true);
    			double random = Math.random();
    			System.out.println("Background " + random);
    			super.paintComponent(g);
     
    			g.setColor(Color.LIGHT_GRAY);
    			g.fillRect(10, 10, 40, 40);
     
    			HtmlDisplay testing_4 = new HtmlDisplay();
    			testing_4.setBackground(Color.WHITE);
    			testing_4.setBounds(0,100,600,800);
    			testing_4.setVisible(true);
    			testing_4.setOpaque(true);
    			add(testing_4);
     
    			}
     
     
    		public void mousePressed(MouseEvent evt) { }
    		public void mouseClicked(MouseEvent evt) { 			
    			int x = evt.getX();   // x-coordinate where the user clicked.
    			int y = evt.getY();   // y-coordinate where the user clicked.
     
    			if (x >= 10 && x <= 50 && y >= 10 && y <= 50) {
     
    				Graphics g = getGraphics();
     
    				g.setColor(Color.BLUE);
    				g.fillRect(10, 10, 40, 40);
     
    				urltest = "http://www.vaxjook.se/blueberry/test/legs/etappmall2.html";
    				repaint();
     
     
    			}
    		}
    		public void mouseReleased(MouseEvent evt) { }
    		public void mouseEntered(MouseEvent evt) { }
    		public void mouseExited(MouseEvent evt) { }
    		public void mouseMoved(MouseEvent evt) { 
     
    			Graphics g = getGraphics();
     
    			int x = evt.getX();   // x-coordinate where the user clicked.
             	int y = evt.getY();   // y-coordinate where the user clicked.
     
    //         	System.out.println("(" + x + ", " + y + ")");
             	if (x >= 10 && x <= 50 && y >= 10 && y <= 50) {
        			g.setColor(Color.ORANGE);
        			g.fillRect(10, 10, 40, 40);
             		setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
               	}
             	else {
        			g.setColor(Color.LIGHT_GRAY);
        			g.fillRect(10, 10, 40, 40);
             		setCursor(previousCursor);
             	}
     
    		}
    		public void mouseDragged(MouseEvent evt) { }
     
     
    	}
     
    	public static class HtmlDisplay extends JPanel implements HyperlinkListener {
    	     public static void main(String[] args) {
     
    //	         HtmlDisplay obj=new HtmlDisplay();
    //	         obj.setSize(600,600);
    //	         obj.setVisible(true);
    	     }
     
    	     URL url;
    	     JEditorPane html;
    	     Document doc;
     
    	     public HtmlDisplay() {
     
    	    	 	try {
    	    	 		System.out.println("Detta är urltest:" + urltest);
    	    	 		UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    	    	 		url=new URL(urltest);
    	    	 		html=new JEditorPane();
    	    	 		System.out.println("Editor created");
    	    	 		html.setEditable(false);
    	    	 		html.setPage(url);
    	    	 		html.addHyperlinkListener(this);
    //	             	JScrollPane scroller = new JScrollPane();
    //	             	JViewport vp = scroller.getViewport();
    //	             	vp.add(html);
    //	             	vp.setBackingStoreEnabled(true);
     
    	    	 		System.out.println("html created");
    //	             	getContentPane().add(scroller);
    	    	 		add(html);
    //	             	getContentPane().add(html);
     
    	             }
    	             catch(Exception e) {
    	            	 e.printStackTrace();
    	             }
     
    	     }
    	         public void hyperlinkUpdate(HyperlinkEvent e) {
    	             try {
     
    	            	 if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
     
    	            		 doc = html.getDocument();
    	            		 System.out.println(e.getURL());
    	            		 html.setPage(e.getURL());
    	            		 getToolkit().beep();
    	            		 System.out.println("Listening");
    	            	 }
    	             }
     
    	             catch(Exception ex) {
    	            	 // html.setDocument(doc);
    	            	 ex.printStackTrace();
    	             }
    	         }	
    	  }
     
    }

Similar Threads

  1. drag item or insert item into new Jlabel in JPanel
    By qaromi in forum AWT / Java Swing
    Replies: 5
    Last Post: July 6th, 2010, 07:37 PM
  2. Cannot update Jlabel in JApplet
    By rin in forum Java Applets
    Replies: 2
    Last Post: April 17th, 2010, 08:21 AM
  3. JApplet containing JButton and a JLabel
    By JuneM in forum AWT / Java Swing
    Replies: 3
    Last Post: March 26th, 2010, 08:32 AM
  4. Funny business with JFrame, JPanel and JLabel
    By JeffC in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 21st, 2010, 12:26 PM
  5. how to output using JLabel?
    By qaromi in forum AWT / Java Swing
    Replies: 1
    Last Post: August 30th, 2009, 02:09 PM

Tags for this Thread