Adding jlabel to a jframe using components

I have 2 classes,

My main class creates a frame and I want another class to add content to it. A bit of reading arroudn told me I should use components to do this however when I run my code the frame is empty.

 public static void main(String[] args)
 {
    // create frame
    JFrame frame = new JFrame();
    final int FRAME_WIDTH = 800;
    final int FRAME_HEIGHT = 600;
    // set frame attributes
    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setTitle("My Frame");
    frame.setVisible(true);

    Component1 Com = new Component1();
    Component add = frame.add(Com);

}

My Component class creates a JLabel

public class Component1 extends JComponent {

   public void paintComponent()
   {
       JLabel label = new JLabel("<html>Some Text</html>");
   }
}

I don't get any compile errors, however I dont get any text in my JFrame.

Can anyone explain what I'm doing wrong?

Chris

Answers


You need to add the JLabel. Also better to extend JPanel instead of JComponent as it has a default layout manager and will make any added components appear without the need to set component sizes. paintComponent is used for custom painting BTW.

public class Component1 extends JPanel {

   Component1() {
      JLabel label = new JLabel("<html>Some Text</html>");
      add(label);
   }
}

No need to create a new Component. Just call frame.getContentPane().add(label). And initialize your label before this.


Need Your Help

iOS: UICollectionViewCell auto adjust size according to screen size

ios objective-c swift uicollectionview uicollectionviewcell

I am trying to create 10 cells in the collection view(same size as the screen). When I run my app in iphone5s simulator, the view contains exactly 5 cells. But when I switch to iphone6p simulator, ...

How do you use multiple form fields to interact with a single method in rails?

ruby-on-rails

I have a model which has start_at and end_at attributes. In the form for the end-user, I am displaying start_at using the standard datetime_select, but I'd rather not have a second datetime select