import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.font.*; /** * This application demonstrates how XOR and Paint mode work in Java. * The application draws a black and a yellow rectangle side-by-side. * Next it sets the XOR mode to the background color and draws 2 red * rectangles, one inside the black and yellow rectangles and one outside * the two rectangles. Finally it resets the mode to Paint mode and draws * another red rectangle within the black and yellow rectangles. * * USER INTERACTION * * If you repeatedly click on the window you can observe how the XOR mode * toggles the first two red rectangles but not the third. You can also see how * the XOR mode correctly draws the red rectangle on the background but produces * weird colors on the black and yellow rectangles. **/ public class xor extends JFrame { boolean first = true; public xor() { getContentPane().add(new myPanel()); } static void createGUI() { xor xorObject = new xor(); xorObject.pack(); xorObject.setVisible(true); } static public void main(String args[]) { //Execute a job on the event-dispatching thread: //creating this applet's GUI. try { javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { createGUI(); } }); } catch (Exception e) { System.err.println("createGUI didn't successfully complete"); } } class myPanel extends JPanel { public myPanel() { addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { repaint(); } }); } public Dimension getPreferredSize() { return new Dimension(200,200); } public void paintComponent(Graphics gr) { Graphics g = gr.create(); // only draw the background graphics the first time paintComponent // is called. If we always redraw the background graphics then // xor will have no effect. The point with XOR is that the // background graphics do not have to be redrawn. if (first) { g.setColor(Color.black); g.fillRect(0,0,100,100); g.setColor(Color.yellow); g.fillRect(100,0,100,100); first = false; } // draw the two red xor rectangles. One will be drawn over the // black and yellow rectangles and the other will be drawn over // a clear area of the panel g.setColor(getBackground()); g.setXORMode(Color.red); g.drawRect(50,20,100,60); g.drawRect(50,120,100,60); // revert to paint mode in order to draw the last red rectangle. // This rectangle appears over the black and yellow rectangles. g.setPaintMode(); g.setColor(Color.red); g.drawRect(70, 40, 60, 20); } } }