How to draw in JPanel? (Swing/graphics Java)

Note the extra comments. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; class JavaPaintUI extends JFrame { private int tool = 1; int currentX, currentY, oldX, oldY; public JavaPaintUI() { initComponents(); } private void initComponents() { // we want a custom Panel2, not a generic JPanel! jPanel2 = new Panel2(); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); … Read more

the images are not loading

I’m sorry to say this, but there are simply so many things wrong with your code… Lets start with: DON’T override any of the paint methods of a top level container. To start with, none of the top level containers are double buffered. Use light weight components instead of heavy weight components (use JFrame instead … Read more

Stretch a JLabel text

In the approach shown below, the desired text is imaged using TextLayout using a suitably large Font size and scaled to fill the component. There’s a related example here. import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JLabel; /** @see … Read more

Drawing Multiple JComponents to a Frame

What you want to do is use a data structure of Car objects and loop through them in the paintComonent method. Something like List<Car> cars = new ArrayList<>(); …. @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (Car car : cars) { car.drawCar(g); } } The drawCar method would come from your Car class public … Read more

How does paintComponent work?

The (very) short answer to your question is that paintComponent is called “when it needs to be.” Sometimes it’s easier to think of the Java Swing GUI system as a “black-box,” where much of the internals are handled without too much visibility. There are a number of factors that determine when a component needs to … Read more

Difference between paint, paintComponent and paintComponents in Swing

AWT, override paint(). Swing top-level container (e.g.s are JFrame, JWindow, JDialog, JApplet ..), override paint(). But there are a number of good reasons not to paint in a TLC. A subject for a separate question, perhaps. The rest of Swing (any component that derives from JComponent), override paintComponent(). Neither override nor explicitly call paintComponents(), leave … Read more