Why in Java on the panel the rectangle can not be drawn?

public class FinanceMarketFrame extends JFrame { private JPanel toolPanel; FinanceMarketFrame() { super("ГрафичСскоС ΠΏΡ€ΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅"); this.setBackground(Color.WHITE); setBounds(50,50,1000, 450); toolPanel = new JPanel(); toolPanel.setPreferredSize(new Dimension(70, this.getContentPane().getHeight())); add(toolPanel, BorderLayout.EAST); toolPanel.getGraphics().setColor(Color.black); toolPanel.getGraphics().drawRect(5, 40, 5, 20); toolPanel.setOpaque(false); toolPanel.add(new JButton()); this.setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } 

    1 answer 1

    Maybe. Judging by your code, you have the following (If you first correct the example because NullPointerException will not move on) you draw a rectangle and the panel is redrawn excluding all the changes described earlier. Here is an example of working code:

     public class Test extends JFrame { private JPanel toolPanel; Test() { super("ГрафичСскоС ΠΏΡ€ΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅"); setBounds(50, 50, 1000, 450); setBackground(Color.WHITE); toolPanel = new JPanel(); toolPanel.setPreferredSize(new Dimension(70, 90)); add(toolPanel, BorderLayout.EAST); toolPanel.add(new JButton()); setVisible(true); paint(getGraphics()); setDefaultCloseOperation(EXIT_ON_CLOSE); } @Override public void paint(Graphics g) { g.setColor(Color.BLACK); g.drawRect(50, 50, 300, 300); } public static void main(String[] args) { new Test(); } }