Sunday, October 9, 2011

Solution to problem 3-7

// Solution to Project 3.7
// Displays coordinates of the center point of the panel. Notice that there are two separate classes
// here that can be compiled separately but work together if are in the same folder
// When both classes are compiled - run this one (the first shown)
//since it has  " public static void main(... "
import javax.swing.*;   
import java.awt.*;      
public class GUIWindow{
   public static void main(String[] args){
      JFrame theGUI = new JFrame();
      theGUI.setTitle("GUI Program");
      theGUI.setSize(300, 200);
      theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      ColorPanel panel = new ColorPanel(Color.white);
      Container pane = theGUI.getContentPane();
      pane.add(panel);
      theGUI.setVisible(true);
   }
}

//Example 3.7: used together with the GUIWindow class but compiled
//as a separate class

import javax.swing.*;
import java.awt.*;
public class ColorPanel extends JPanel{
  
   public ColorPanel(Color backColor){
      setBackground(backColor);
   }
   public void paintComponent(Graphics g){
      super.paintComponent(g);
      int x = getWidth() / 2 - 60;
      int y = getHeight() / 2;
      g.setColor(Color.blue);
      g.drawRect(x, y, 120, 20);
      g.setColor(Color.red);
      g.drawString("Hello world!", x + 10, y + 15);
   }
}

No comments:

Post a Comment