Draw a rectangle in Jpanel

I am trying to use GUI programming in java and wanted to draw a rectangle in Jpanel. The code does not give any errors, but I can not get the rectangle in the GUI. Can someone please tell me what I am missing in the following code. I am sure this is quite simple, so please be careful.

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloWorldGUI2 { private static class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class RectDraw extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawRect(230,80,10,10); g.setColor(Color.RED); g.fillRect(230,80,10,10); } } public static void main(String[] args) { JPanel content = new JPanel(); RectDraw newrect= new RectDraw(); JButton okButton= new JButton("OK"); JButton clearButton= new JButton("Clear"); ButtonHandler listener= new ButtonHandler(); okButton.addActionListener(listener); clearButton.addActionListener(listener); content.add(okButton); content.add(clearButton); content.add(newrect); JFrame window = new JFrame("GUI Test"); window.setContentPane(content); window.setSize(250,100); window.setLocation(100,100); window.setVisible(true); } } 
+4
source share
2 answers

Your new RectDraw size is likely to be quite small, possibly [0, 0], as it was added to FlowLayout using JPanel and does not have a preferred size set. Consider overriding your getPreferredSize() method and returning a suitable size so that you can see it.

 private static class RectDraw extends JPanel { protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawRect(230,80,10,10); g.setColor(Color.RED); g.fillRect(230,80,10,10); } public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); // appropriate constants } } 

Besides,

  • The paintComponent method must be protected, not public
  • Remember to use @Override before your method overrides.
  • The goal is much less code in the main method and more code in the "instance" of the world, and not in the static world.
  • Be careful with code formatting. Poor code formatting, especially misleading indentation, leads to stupid errors.
+8
source

I am trying to use GUI programming in java

Then you should start by reading the Swing tutorial .

For this question, you can start with the Custom Painting section.

Not only does the tutorial show you a working example, but also shows how to properly create a frame by executing EDT code. Read more in the Concurrency section.

+5
source

Source: https://habr.com/ru/post/1502866/


All Articles