Results 1 to 3 of 3
Thread: Print JLabel with a button ?
- 05-28-2012, 04:11 AM #1
Member
- Join Date
- May 2012
- Posts
- 15
- Rep Power
- 0
Print JLabel with a button ?
Hi all
.gif)
I need a little help here, so, I have this:
As you can see, I only need to print the string "Hello" when I press the button.Java Code:import javax.swing.*; import java.awt.event.*; public class ejemplo extends JFrame implements ActionListener{ JLabel myVar; JButton boton1; public ejemplo(){ setLayout(null); myVar = new JLabel("Hello"); myVar.setBounds(150, 100, 100, 30); // I'm not adding this here. boton1=new JButton("Print"); boton1.setBounds(150, 150, 100, 30); add(boton1); boton1.addActionListener(this); } public void actionPerformed(ActionEvent e){ if (e.getSource ()==boton1){ add(myVar); } } public static void main (String[] args){ ejemplo ventana=new ejemplo(); ventana.setBounds(0,0,400,300); ventana.setVisible(true); ventana.setResizable(true); } }
But the string doesn't shows until I resize a little the frame, how can I make the string appear by just pressing the button ???
Thanks a lot !!!
- 05-28-2012, 04:38 AM #2
Member
- Join Date
- May 2012
- Posts
- 15
- Rep Power
- 0
Re: Print JLabel with a button ?
Nevermind!
I just figured out how to do it... I just added this.
Thanks anyway :)Java Code:if (e.getSource ()==boton1){ add(myVar); myVar.repaint(); // I just added this line and that's it. }
- 05-28-2012, 04:41 AM #3
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,606
- Rep Power
- 5
Re: Print JLabel with a button ?
Adding components after a JFrame has been set to visible is more complex than that - adding them to a visible component requires you to validate/paint. There are many solutions: a) add the JLabel before setting the JFrame to visible with its text to an empty string, then call set text in the actionPerformed b) call validate on the JFrame after adding the component c) set the visibility of the component to false d) many more....
Edit: seems you found a solution, which falls into category d)
Similar Threads
-
Javax Print Attribute for Selection Print Range
By rsawatzky in forum AWT / SwingReplies: 0Last Post: 04-26-2012, 12:14 AM -
How to Change a JLabel in a Frame when a Button is clicked?
By fatabass in forum AWT / SwingReplies: 1Last Post: 02-11-2012, 03:07 AM -
Adding a sqrt button and percentage button to a calculator
By Josie_Taylor in forum New To JavaReplies: 4Last Post: 03-14-2011, 01:16 AM -
Adding a JLabel to a JPanel - jlabel not showing
By Bongeh in forum New To JavaReplies: 17Last Post: 04-06-2010, 11:02 PM -
Print the text file and print preview them
By Java Tip in forum java.awtReplies: 0Last Post: 06-22-2008, 11:04 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks