Thursday, September 11, 2008

Changing a Foreground color:

After a little research, I found how to change the foreground color in a JLabel and therefore in the content pane of the kinds of applications we are writing. (Thanks Stephen)

You need to set the Opaqity or opaqueness of the label to change the forground. Note lines 13, 29 and 30 below:



1 // RedText

2 import java.awt.*;

3 import javax.swing.*;

4

5 public class RedText extends JFrame

6 {

7 private JLabel aLabel; // JLabel that displays text

8

9 // no-argument constructor

10 public RedText()

11 {

12 // get content pane and set layout to null

13 Container contentPane = getContentPane();

14 contentPane.setBackground( Color.LIGHT_GRAY );

15 contentPane.setLayout( null );

16

17 // set properties of application's window

18 setTitle( "REDText Demo" ); // set title bar string

19 setSize( 608, 143 ); // set width and height of JFrame

20 setVisible( true ); // display JFrame on screen

21

22 // set up aLabel

23 aLabel = new JLabel();

24 aLabel.setText( "I am red text on light gray!!" );

25 aLabel.setLocation( 30, 0 );

26 aLabel.setSize( 550, 88 );

27 aLabel.setFont( new Font( "Serif", Font.PLAIN, 36 ) );

28 aLabel.setHorizontalAlignment( JLabel.CENTER );

29 aLabel.setOpaque(false);

30 aLabel.setForeground(Color.RED);

31 contentPane.add( aLabel );

32 }

33

34 // main method

35 public static void main( String[] args )

36 {

37 RedText application = new RedText();

38 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

39

40 } // end method main

41

42 } // end class RedText




No comments :

Post a Comment

Note: Only a member of this blog may post a comment.