0

Alright so I am practicing Java myself and I found this exercise: Draw the word: "HELLO" only using lines and ovals. So I basically drew all the letters and it should work perfectly, but for some reason only the "O" (last letter) shows, and I do not know why. Here's my code:

Main class:

public static void main(String[] args) {

   JFrame frame = new JFrame();
   frame.setSize(1000, 750);
   frame.setTitle("HELLO without using Strings");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setPreferredSize(new Dimension(1000, 1000));
   JComponent componentH = new LetterH();
   JComponent componentE = new LetterE();
   JComponent componentL1 = new LetterL1();
   JComponent componentL2 = new LetterL1();
   JComponent componentO = new LetterO();
   frame.add(componentH);
   frame.add(componentE);
   frame.add(componentL1);
   frame.add(componentL2);
   frame.add(componentO);      
   frame.setVisible(true);
}

One letter (I could post the other letters aswell, but there's no point as the code looks completely the same on every letter, except for: x1, y1, x2, y2:

public class LetterH extends JComponent {

@Override
public void paintComponent(Graphics g) {
    g.setColor(Color.RED);
    g.drawLine(10, 0, 10, 100);
    g.drawLine(60, 0, 60, 100);
    g.drawLine(10, 50, 60, 50);


    g.setColor(Color.BLACK);
    g.drawLine(120, 0, 120, 100);
    g.drawLine(120, 100, 170, 100);

    g.setColor(Color.BLACK);
    g.drawLine(180, 0, 180, 100);
    g.drawLine(180, 100, 230, 100);




}

}

I couldn't find an answer on this problem anywhere, so I thought I'd ask it here. I hope someone can help. Every tip is appreciated! Thanks in advance.

Sincerely, Double.

Wout
  • 77
  • 6
  • 1
    Possible duplicate of [Java Swing components not showing](http://stackoverflow.com/questions/13041915/java-swing-components-not-showing) – Arnaud Mar 15 '17 at 10:45
  • Alternatively, you may want to do something like `frame.setLayout(new GridLayout(1,))` . – Arnaud Mar 15 '17 at 10:53

1 Answers1

0

Frames like other swing stuff should be initialized within the EDT - Thread (java.awt.EventQueue.invokeLater explained). Initialization from a main method should look like this:

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

If all this stuff is done from other threads (main thread), then very strange things are going to happen: not drawn or partial drawn contents, not updating components, ...

Nevertheless there could also be a problem with the sizes of your components. Try to install a LayoutManager within your frame or initialize position and size of your Letter components.

Community
  • 1
  • 1
wumpz
  • 8,257
  • 3
  • 30
  • 25