Drawing with graphics and with widgets in JApplet/

2019-07-22 20:27发布

Basically I have a JApplet that tries to draw with the graphics (ie, g.drawOval(10,10,100,100) and also include JCompotents (ie. JButton). What happens is that the repaint can get really wacky.

Sometimes the graphics will draw over widgets or vis-versa. It's not reliable and leads to unpredictable behavior.

(Button also always be on top of those graphics)

I've played around with it trying to override or manually draw components, changing orders, etc, but think I'm missing something very fundamental here. Anyone have a template or the correct way to use both g.drawXXX and JCompotents?

1条回答
放荡不羁爱自由
2楼-- · 2019-07-22 20:45

Again, just follow what I recommended,

be sure never to draw directly in the JApplet but rather in a JPanel or in its contentPane (which is a JPanel). Make sure to draw in this JPanel's paintComponent(...) method.

and it works:

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;

import javax.swing.*;

public class Test2 extends JApplet {


   public void init() {
      try {
         SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
               Test2BPanel panel = new Test2BPanel();
               setContentPane(panel);
            }
         });
      } catch (InvocationTargetException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

   }


}

class Test2BPanel extends JPanel {
   private String[] backgroundImageFileNames = { "test", "test", "test" };

   private JButton refreshButton;
   private JComboBox backgroundList;

   public Test2BPanel() {

      setBackground(Color.white);

      setLayout(new FlowLayout());

      refreshButton = new JButton("replant new forest");
      refreshButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {

         }

      });
      add(refreshButton);

      backgroundList = new JComboBox(backgroundImageFileNames);
      backgroundList.setSelectedIndex(2);
      add(backgroundList);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      paintIt(g);
   }

   public void paintIt(Graphics g) {
      for (int i = 0; i < 200; i++) {
         for (int j = 0; j < 200; j++) {
            g.setColor(Color.red);
            g.drawOval(10 * i, j, 10, 10);
         }
      }
   }
}

Also, please check the Swing painting tutorials including the Basic Painting Tutorial and the Advanced Painting Tutorial.

For a great book on this and more, please look into buying Filthy Rich Clients by Chet Haase and Romain Guy. You won't regret the purchase! It's one of the best Java books that I own.

查看更多
登录 后发表回答