How to remove and add a content with a single button in JPanel Java Gui?

56 Views Asked by At

I wrote a code that visualise some Cities with random x and y values, if i press on the button RandomB.Firstly I want it to clear the Screen so i used Screen.removeAll(); Screen.revalidate(); Screen.repaint(); for the Job. I then return the function in forLoop to create some cities getSA is the Number of cities.But the problem is after I run the proggramm and press the button i see the cities but they disappear very fast.I sometiemes dont even see them What could be the Problem??

@Override
    public void actionPerformed(ActionEvent e) {
       
        //if (e.getSource() == starButton) {
            
        //}
        
        if (e.getSource() == randomB) {
            Screen.removeAll();
            Screen.revalidate();
            Screen.repaint();
            getSA = StadtAnzahl.getSelectedItem().toString();
            
            for (int i = 0; i < Integer.parseInt(getSA); i++) {
                int x = r.nextInt((int) Math.round(0.77 * screenSize.width)) + 10;
                int y = r.nextInt((int) Math.round(0.82 * screenSize.height)) + 10;
                ZeichneStadt(x, y, Screen.getGraphics());                
            }
        
        }
    }
    public void ZeichneStadt(int x,int y,Graphics g)
    {
       Graphics2D g2=(Graphics2D)g.create();
       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
       g2.setColor(Color.red);
       g2.fillOval(x, y, 10, 10);
       salesman.hinzufügen(x, y);
    }

I tried to replace removeall(),revalidiate() and repaint().

1

There are 1 best solutions below

0
queeg On

First of all create a paintComponent() method which will paint data from a variable onto the screen. Be aware that paintComponent() is not called by you. It is up to Swing to decide when a component needs to be painted.

In your actionPerformed() method prepare the data that shall be painted (=put them into a variable), but then you just call repaint(). This indicates to Swing that the data has changed and the component should be repainted. Swing will check if the component is visible at all, and only then call paintComponent().