Why can’t I access my panel’s getWidth() and getHeight() functions?

Swing components have no width or height until they’ve been rendered. This occurs if you call pack() or setVisible(true) on a root container. Consider placing your x y int initialization code in the componentResized method of a ComponentListener that is added to your JPanel. e.g., import java.awt.event.*; import java.awt.*; import javax.swing.*; public class TestLinePanel { … Read more

add JMenuBar to a JPanel?

You can use a BorderLayout for your JPanel and put the JMenuBar into the NORTH area of the panel with JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(menubar, BorderLayout.NORTH); JMenuBar is a JComponent and can be added to a Container like any other JComponent.

CardLayout showing two panels, flashing

Here’s a problem: final Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { Don’t use a java.util.Timer in a Swing program as you will have threading problems. Instead use a Swing Timer. Also, you’re making Swing calls in background threads and using Graphics object obtained by calling getGraphics() on a component, two no-nos for Swing programs. … Read more