Results 1 to 3 of 3
- 11-11-2011, 02:22 PM #1
Member
- Join Date
- Nov 2011
- Posts
- 2
- Rep Power
- 0
How to move JLabel around on a panel
Hello,
I have some problem with my code. I have not managed to move a JLabel around on my JPanel. I have tried some different approaches in the code, they are in there and it compiles fine but will not move the JLabel. Anyone out there that could tell me what I am missing?
Java Code:package chapter3; import java.awt.Color; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class Panel { public static void main(String[] args) { Color myColor = new Color(255, 0, 120); //Subpanel JPanel subpanel = new JPanel(); subpanel.setPreferredSize(new Dimension(150, 150)); subpanel.setBackground(myColor); JLabel label = new JLabel("Some text"); label.setAlignmentX(SwingConstants.LEFT); //not working label.setAlignmentX(0); //not working label.setHorizontalAlignment(SwingConstants.LEFT); //not working label.setHorizontalAlignment(0); //not working subpanel.add(label); //Main panel JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(200, 200)); panel.setBackground(Color.yellow); panel.add(subpanel); //Frame JFrame frame = new JFrame("The Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(200, 200); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } }
- 11-11-2011, 05:05 PM #2
Senior Member
- Join Date
- Jul 2009
- Posts
- 1,158
- Rep Power
- 5
Re: How to move JLabel around on a panel
The alignment property is only used by some layout manager to control the position within the panel. You add your label to a JPanel which uses a FlowLayout that centers components by default. So the FlowLayout ignores the alignment property.
1) Add the label directly to the JFrame, which uses a BorderLayout. Then the width of the label will be the width of the frame.
2) You only need to use the following property to align the text within its own bounds:
Java Code:label.setHorizontalAlignment(JLabel.LEFT);
Last edited by camickr; 11-11-2011 at 05:12 PM.
- 11-11-2011, 06:25 PM #3
Member
- Join Date
- Nov 2011
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
How to move a JLabel?
By Zambash in forum AWT / SwingReplies: 2Last Post: 08-24-2011, 07:47 PM -
panel on a panel not visible
By warchieflll in forum Advanced JavaReplies: 2Last Post: 01-29-2011, 08:29 PM -
Add panel to parent panel
By LovJava in forum AWT / SwingReplies: 10Last Post: 09-02-2010, 08:43 PM -
Adding a JLabel to a JPanel - jlabel not showing
By Bongeh in forum New To JavaReplies: 17Last Post: 04-06-2010, 11:02 PM -
Adding a panel to a panel
By rclausing in forum New To JavaReplies: 7Last Post: 02-02-2010, 05:56 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks