1

I want to edit my text alignment to the center. I already know you can do: intro.setHorizontalAlignment(JLabel.CENTER); to make it centered. But I want to do it so that it is like in microsoft word when you do that icon. This is my program so far:

import javax.swing.*;

import javax.swing.JLabel;

public class FrameStuff

{

 public static void main(String[] args)

 {

 // Creating and setting up a regular frame
 JFrame frame = new JFrame();

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 // Setting up frame characteristics
 frame.setSize(800, 600);
 frame.setTitle("FrameStuff");

 // Making it visible

frame.setVisible(true);

 //Making and assigning a new string

String textintro = new String("<html>This is my program <br/>I am having loads of fun <br/>Thanks for helping me!</html>");

// Made a new label (just happened to call it intro

 JLabel intro = new JLabel(textintro );

 // Set some sort of alignment within the frame

 intro.setHorizontalAlignment(JLabel.CENTER);

 //Add the dang label to the frame. 

frame.add(intro); 

}

}

My first time using this and a newbie at programming.

newuser
  • 8,338
  • 2
  • 25
  • 33

2 Answers2

5

Use an AlignmentAction from the StyledEditorKit, for example,

JButton button = new JButton(new
    StyledEditorKit.AlignmentAction("Center", StyleConstants.ALIGN_CENTER));

You can try it out in this related example. See also How to use Action and Text Component Features.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 2
    +1 and see the section from the Swing tutorial on [Text Component Features](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html) for an example of this approach that uses the default Actions fro the editor kit. Not sure why you didn't include a link to the tutorial instead of a custom example. Not only does the tutorial give a good working example but hopefully the OP will bookmark the tutorial for future reference. – camickr Oct 22 '13 at 01:10
2

You could try

String message; 

JLabel label = new JLabel(message, SwingConstants.CENTER);

I haven't used the AlignmentAction that trashgod mentioned, but if you end up having problems with that, this should work just as well.

Vince
  • 14,470
  • 7
  • 39
  • 84
  • +1 related example are examined [here](http://stackoverflow.com/q/19506769/230513) & [*How to Use Labels*](http://docs.oracle.com/javase/tutorial/uiswing/components/label.html). – trashgod Oct 22 '13 at 01:16