MouseListener in Java 3D

I am having problems getting a mouse click registered in a Java 3D environment. Basically I have a canvas3D object, onto which I have created a 3D graph and have populated it with points (plotted in 3D space). I really need to be able to click on these points and bring up some information on them. I have included what I hope is the relative parts of code... Any help would be greatly appreciated.
1st bit of code is from the applet class, Grid3D.
2nd bit is the first part of the Protein.java class. The MouseListener part of Protein.java has been implemented just to print to the cmd line "Clicked". However, it doesn't work.
          System.out.println("Displaying Points...");
          ProteinList theList = new ProteinList(459);
          theList.readProteins();
          Transform3D translate = new Transform3D();
          for (int i = 0;i<459;i++){
               Protein theProt = theList.getProteinByNum(i);
               //c.addMouseListener(theProt);     
               translate.setTranslation(new Vector3f
                    ((((theProt.getTheX()-0.5f)*2.0f)),
                    (((theProt.getTheY())-0.5f)*2.0f),
                    (((theProt.getTheZ())-0.5f)*2.0f)));
               theProt.setTransform(translate);
                                                                                theGroup.addChild(theProt);
               u.addBranchGraph(theGroup);
public class Protein extends TransformGroup implements MouseListener, Serializable
     private float x;
     private float y;
     private float z;
     private int clicked = 0;
     private Sphere thePoint;
     /** Creates a new instance of Protein
     * Super refers to TransformGroup
     * Creates Sphere with radius and appearance */
     public Protein() {
          super();
          Appearance app = new Appearance();
          Material mat =new Material();
          mat.setDiffuseColor(1.0f,0.0f,0.0f);
          app.setMaterial(mat);          
          thePoint = new Sphere(0.007f,app);
          this.addChild(thePoint);
------------------------------------------------------------------------------------------------------------------

Look into behavior packages
com.sun.j3d.utils.behaviors.mouse
com.sun.j3d.utils.behaviors.picking
Also some of the pick examples in the Java3D Example Programs show how to apply these.

Similar Messages

  • Slow mouseDragged callbacks in java 1.6.0_10, works fast in prior releases?

    I have this program that draws a selection rectangle by xor-ing a rectangle on the screen following the mouse cursor when clicked. In jre's before 1.6.0_10, this runs fast, but in 1.6.0_10 it runs like dog. I've used this code with JRE's from 1.5 to 1.6.0_07 and it was just fine. And if I switch back in eclipse, it is fast again. Here is a striped down version of the code that illustrates the problem. Any ideas, or is this just a performance issue with 1.6.0_10?
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    // This class is used to track the mouse and to
    // draw a rectangle that follows the pointer.
    // In Java 1.6.0_07 (and before) this is very fast, but in 1.6.0_10
    // this is very slow.....
    public class TestMotion implements MouseMotionListener, MouseListener, KeyListener {
         protected Component parent;
         protected Rectangle startRect;
         protected Point     startMovePt = null;
         protected Point     previousPt = null;
         protected int       width;
         protected int       height;
         protected int       minWidth = 0;
         protected int       minHeight = 0;
         protected boolean   paintedFlg = false;
         public static void main(String [] args) {
              JFrame frame = new JFrame("Test Window");
              JPanel panel = new JPanel();
              panel.setLayout(null);
              new ClickWatcher(panel);
              frame.setContentPane(panel);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(new Dimension(800,600));
              frame.setVisible(true);
         private static class ClickWatcher implements MouseListener {
              private JPanel ourPanel;
              private ClickWatcher(JPanel panel) {
                   ourPanel = panel;
                   panel.addMouseListener(this);
              public void mouseClicked(MouseEvent e) {
              public void mouseEntered(MouseEvent e) {
              public void mouseExited(MouseEvent e) {
              public void mousePressed(MouseEvent e) {
                   new TestMotion(ourPanel,e.getX(),e.getY());
              public void mouseReleased(MouseEvent e) {
         public TestMotion(Component control,
                             int x, int y) {
              this.parent = control;
              startRect = new Rectangle(x,y,0,0);
              this.minWidth = 0;
              this.minHeight = 0;
              parent.addMouseListener(this);
              parent.addMouseMotionListener(this);
              parent.addKeyListener(this);
              parent.requestFocus();
         protected void draw(Graphics g,int x,int y,int cx, int cy) {
              g.drawRect(x,y,cx,cy);
         public void mouseDragged(MouseEvent e) {
              int x = e.getX();
              int y = e.getY();
              System.out.println("Mouse Dragged to ("+x+","+y+")");
              Graphics g = parent.getGraphics();
              g.setColor(Color.black);
             g.setXORMode(Color.white);
             if (previousPt != null) {
                  if (paintedFlg == false)
                       draw(g,previousPt.x,previousPt.y,width,height);
                  paintedFlg = false;
             } else {
                  previousPt = startRect.getLocation();
             int newX = previousPt.x;
             int newY = previousPt.y;
             int newHeight = height;
             int newWidth = width;
              if (x < startRect.x) {
                   newX = x;
                   newWidth = startRect.x - x;
              } else {
                   newX = startRect.x;
                   newWidth = x - startRect.x;
              if (y < startRect.y) {
                   newY = y;
                   newHeight = startRect.y - y;
              } else {
                   newY = startRect.y;
                   newHeight = y - startRect.y;
              if (newWidth < minWidth) {
                  newWidth = minWidth;
             if (newHeight < minHeight) {
                  newHeight = minHeight;
             Dimension maxSize = parent.getSize();
             if ((newX+newWidth) >= maxSize.width) {
                  newWidth = maxSize.width - newX - 1;
             if ((newY+newHeight) >= maxSize.height) {
                  newHeight = maxSize.height - newY - 1;
             if (newX < 0) {
                  newWidth += newX;
                  newX = 0;
             if (newY < 0) {
                  newHeight += newY;
                  newY = 0;
             previousPt = new Point(newX,newY);
             width = newWidth;
             height = newHeight;
             draw(g,previousPt.x,previousPt.y,
                    width,height);
             g.dispose();
         public void mouseMoved(MouseEvent e) {
         public void mouseClicked(MouseEvent e) {
         public void mouseEntered(MouseEvent e) {
         public void mouseExited(MouseEvent e) {
         public void mousePressed(MouseEvent e) {
         public void mouseReleased(MouseEvent e) {
              cleanup1();
             cleanup2();
              e.consume();
         public void keyPressed(KeyEvent e) {
         public void keyReleased(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
              if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
                   cancel();
         private void cleanup1() {
              Graphics g = parent.getGraphics();
              g.setColor(Color.black);
             g.setXORMode(Color.white);
             if (previousPt != null) {
                  draw(g,previousPt.x,previousPt.y,width,height);
             g.dispose();
         private void cleanup2() {
             previousPt = null;
              parent.removeMouseListener(this);
              parent.removeMouseMotionListener(this);
              parent.removeKeyListener(this);
         public void cancel() {
             cleanup1();
             cleanup2();
         // We need to know when paint is called so we don't
         // try and clear our old xor rectangle.
         public void paint() {
              paintedFlg = true;
    }

    Thank you! That solved the problem.No it doesn't, because to make your application work properly on all computers D3D would have to be disabled whenever your application is used. I would look for a way to do what you want without using XOR mode.

  • Java Calendar Help Needed :)

    Hi,
    I am trying to develop a Java Event Calendar which is able to display the calendar weekly. So the JPanel will be setup with 7 JLists for the days of the week. Buttons will allow switching of the days of the week, months and year.
    Each JList corresponding to the day of the week will have its data obtained from the database using JDBC and loaded upon 're-drawing' of the lists.
    However i am having trouble with the GUI side in understanding how to implement this, i am confident with the JList and database side of things, i have just used a similar example using the Calendar API for monthly displays, however i am unsure how to convert this to a weekly calendar.
    Ideally 7 JLists will always be available in the panel in order M,T,W,T,F,S,S but some will be set to inactive (for example in the first and last weeks of the month).
    If anyone has any suggestions please could you help me out :)
    Sorry if what im trying to do is a bit confusing.
    I've included the code i've been using for the monthly calendar
    THANKS!!
    public class CalendarPanel extends JPanel implements ActionListener {
      private Calendar panelDate;
      private Label monthLabel;
      private Label yearLabel;
      private Panel daysPanel;
      private Vector calendarListeners;
      private static final String days[] = {"S","M","T","W","T","F","S"};
      public CalendarPanel(){
        super(new BorderLayout());
        panelDate = Calendar.getInstance();
        buildUI();
      public CalendarPanel(Calendar date){
        super(new BorderLayout());
        panelDate = (date != null) ? (Calendar)date.clone() : Calendar.getInstance();
        buildUI();
      public CalendarPanel(Date date){
        super(new BorderLayout());
        panelDate = Calendar.getInstance();
        if(date != null) panelDate.setTime(date);
        buildUI();
      public Calendar getCalendar(){ return panelDate;}
      public void setCalendar(Calendar date){
        if(date != null){
          panelDate = (Calendar)date.clone();
          redrawPanel();
      public void setCalendar(Date date){
        if(date != null){
          panelDate.setTime(date);
          redrawPanel();
      public int getYear(){ return panelDate.get(Calendar.YEAR);}
      public String getMonthName(){
        switch(panelDate.get(Calendar.MONTH)){
        case Calendar.JANUARY: return "January";
        case Calendar.FEBRUARY: return "February";
        case Calendar.MARCH: return "March";
        case Calendar.APRIL: return "April";
        case Calendar.MAY: return "May";
        case Calendar.JUNE: return "June";
        case Calendar.JULY: return "July";
        case Calendar.AUGUST: return "August";
        case Calendar.SEPTEMBER: return "September";
        case Calendar.OCTOBER: return "October";
        case Calendar.NOVEMBER: return "November";
        case Calendar.DECEMBER: return "December";
        case Calendar.UNDECIMBER: return "Undecimber";
        default: return "Unknown";
      private void buildUI(){
        this.add(buildHeaderPanel(), BorderLayout.NORTH);
        daysPanel = new Panel(new GridBagLayout());
        redrawPanel();
        this.add(daysPanel, BorderLayout.CENTER);
      // build the part of the gui that contains the month and year
      // labels with their incrementors / decrementors
      private Panel buildHeaderPanel(){
        monthLabel = new Label(getMonthName(), Label.CENTER);
        yearLabel = new Label(Integer.toString(panelDate.get(Calendar.YEAR)),
                     Label.CENTER);
        GridBagConstraints gbc = new GridBagConstraints();
        Panel headerPanel = new Panel(new GridBagLayout());
        // month label and buttons
        Panel panel = new Panel(new GridBagLayout());
        Button button = new Button("-");
        button.setActionCommand("decrease month");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(monthLabel, gbc);
        button = new Button("+");
        button.setActionCommand("increase month");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.weightx = 1;
        headerPanel.add(panel, gbc);
        // year label and buttons
        panel = new Panel(new GridBagLayout());
        button = new Button("-");
        button.setActionCommand("decrease year");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.EAST;
        gbc.weightx = 0;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(yearLabel, gbc);
        button = new Button("+");
        button.setActionCommand("increase year");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.weightx = 1;
        headerPanel.add(panel, gbc);
        return headerPanel;
      // redraws the entire panel, including relaying out of
      // the days buttons
      private void redrawPanel(){
        monthLabel.setText(getMonthName());
        yearLabel.setText(Integer.toString(getYear()));
        // redraw days panel
        GridBagConstraints gbc = new GridBagConstraints();
        // clear current days panel
        daysPanel.removeAll();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        // add days of week
        for(int i = 0; i < days.length; i++, gbc.gridx++)
          daysPanel.add(new Label(days, Label.CENTER), gbc);
    gbc.gridx = 0;
    gbc.gridy++;
    // days of month
    Button button; // day buttons
    JTable day = new JTable();
    Calendar today = Calendar.getInstance();
    Calendar cellDay = (Calendar)today.clone();
    int month = panelDate.get(Calendar.MONTH);
    int year = panelDate.get(Calendar.YEAR);
    // start with first of panels month
    cellDay.set(year, month, 1);
    gbc.gridx = cellDay.get(Calendar.DAY_OF_WEEK) - 1;
    while( cellDay.get(Calendar.MONTH) == month ){
    if(gbc.gridx > 6){
         gbc.gridy++;
         gbc.gridx = 0;
    button = new Button(Integer.toString(cellDay.get(Calendar.DATE)));
    button.addActionListener(this);
    if( cellDay.equals(today)){
         button.setForeground(Color.red);
    daysPanel.add(button, gbc);
    gbc.gridx++;
    cellDay.add(Calendar.DAY_OF_MONTH, 1);
    // re validate entire panel
    validate();
    // implementation of ActionListener interface
    // currently no real need to create subclassed action
    // events for calendar. All actions generated by this
    // are action events (generated from the buttons).
    // the action command will be one of the four below
    // or a number (the label of the day button!).
    public void actionPerformed(ActionEvent ae){
    String command = ae.getActionCommand();
    if(command.equals("increase month")){
    panelDate.add(Calendar.MONTH, 1);
    redrawPanel();
    } else if(command.equals("decrease month")){
    panelDate.add(Calendar.MONTH, -1);
    redrawPanel();
    } else if(command.equals("increase year")){
    panelDate.add(Calendar.YEAR, 1);
    redrawPanel();
    } else if(command.equals("decrease year")){
    panelDate.add(Calendar.YEAR, -1);
    redrawPanel();
    notifyCalendarListeners(ae);
    // methods for keeping track of interested listeners
    public void addCalendarActionListener(ActionListener al){
    if(al != null){
    if(calendarListeners == null) calendarListeners = new Vector();
    calendarListeners.addElement(al);
    public void removeCalendarActionListener(ActionListener al){
    if((calendarListeners != null) && (al != null)){
    calendarListeners.removeElement(al);
    private void notifyCalendarListeners(ActionEvent ae){
    if((calendarListeners != null) && (!calendarListeners.isEmpty())){
    java.util.Enumeration e = calendarListeners.elements();
    while(e.hasMoreElements())
         ((ActionListener)e.nextElement()).actionPerformed(ae);

    Hi,
    Sorry for the change of screen name, i'm having trouble with my old account.
    I have now got most of the system working. However I am having trouble working out how to stop the last days of the previous month appearing in the first week of the next month. For example on 'July 2008' , days 29 and 30 of June are present in the first week of July. How can i get rid of this? And also for the last week of the month, how to get rid of the first days of the next month?
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Vector;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.EtchedBorder;
    * @category CalendarSystem
    * @author Daniel Barrett
    public class CalendarSystem extends JPanel implements ActionListener, MouseListener, KeyListener   {
         JPanel events = new JPanel();
         JPanel action = new JPanel();
              //Events Panel
         DateComboBox eventDateChooser = new DateComboBox();
         JTextField ref = new JTextField(10);
         JTextArea eventDetails = new JTextArea();
         JScrollPane scrollingArea = new JScrollPane(eventDetails);
         JTextField dateF = new JTextField(15);
         JTextField timeF = new JTextField(15);
         String[] minutes = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
         String[] hours = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
         JComboBox minsComb = new JComboBox(minutes);
         JComboBox hourComb = new JComboBox(hours);
              //Actions Panel
         JButton delete = new JButton("Delete");
         JButton purge = new JButton("Purge");
         JButton add = new JButton("Add");
         JButton edit = new JButton("Edit");
         JButton mview = new JButton("Month View");
         protected JLabel monthLabel;
         protected JLabel weekLabel;
         protected JLabel lmonday = new JLabel("");
         protected JLabel ltuesday = new JLabel("");
         protected JLabel lwednesday = new JLabel("");
         protected JLabel lthursday = new JLabel("");
         protected JLabel lfriday = new JLabel("");
         protected JLabel lsaturday = new JLabel("");
         protected JLabel lsunday = new JLabel("");
         protected Calendar calendar;
         protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
         protected SimpleDateFormat dayFormat = new SimpleDateFormat("MMM");
         JPanel monthCont = new JPanel();
         JPanel weekCont = new JPanel();
         JPanel yearCont = new JPanel();
         JPanel daysOfWeek = new JPanel();
         JPanel monday = new JPanel();
         JPanel tuesday = new JPanel();
         JPanel wednesday = new JPanel();
         JPanel thursday = new JPanel();
         JPanel friday = new JPanel();
         JPanel saturday = new JPanel();
         JPanel sunday = new JPanel();
         JList mondayEvents = new JList();
         JScrollPane mondayEventsScroll = new JScrollPane(mondayEvents);
         JList tuesdayEvents = new JList();
         JScrollPane tuesdayEventsScroll = new JScrollPane(tuesdayEvents);
         JList wednesdayEvents = new JList();
         JScrollPane wednesdayEventsScroll = new JScrollPane(wednesdayEvents);
         JList thursdayEvents = new JList();
         JScrollPane thursdayEventsScroll = new JScrollPane(thursdayEvents);
         JList fridayEvents = new JList();
         JScrollPane fridayEventsScroll = new JScrollPane(fridayEvents);
         JList saturdayEvents = new JList();
         JScrollPane saturdayEventsScroll = new JScrollPane(saturdayEvents);
         JList sundayEvents = new JList();
         JScrollPane sundayEventsScroll = new JScrollPane(sundayEvents);
         protected Color selectedBackground;
         protected Color selectedForeground;
         protected Color background;
         protected Color foreground;
         public CalendarSystem(){
              setupDays();
              setupHeaders();
              setupEvents();
              setupActions();
              this.calendar = Calendar.getInstance();
              this.calendar.setFirstDayOfWeek(Calendar.SUNDAY);
              this.add(this.monthCont);
              this.add(this.daysOfWeek);
              this.add(this.weekCont);
              this.add(this.events);
              this.add(this.action);
              this.setLayout(new BoxLayout(this,1));
              this.setMaximumSize(new Dimension(400,30));
              this.updateCalendar();
         private void setupActions() {
              this.action.setBorder(BorderFactory.createTitledBorder("Actions"));
              this.action.add(this.add);
              this.action.add(this.edit);
              this.action.add(this.delete);
              this.action.add(this.purge);
              this.action.add(this.mview);
         private void setupEvents() {
              this.events.setBorder(BorderFactory.createTitledBorder("Event Details"));
              this.events.setLayout(new BoxLayout(this.events,1));
              JPanel row1 = new JPanel();
              JPanel row2 = new JPanel();
              JPanel row3 = new JPanel();
              JLabel la = new JLabel("Reference");
              JLabel da = new JLabel("Date");
              JLabel time = new JLabel("Time");
              JLabel det = new JLabel("Details");
              this.ref.setEditable(false);
              this.dateF.setEditable(false);
              this.timeF.setEditable(false);
              this.eventDetails.setEditable(false);
              row1.add(la);
              row1.add(this.ref);
              row1.add(da);
              row1.add(this.dateF);
              row1.add(time);
              row1.add(this.timeF);
              row2.add(det);
              scrollingArea.setPreferredSize(new Dimension(600,50));
              row3.add(this.scrollingArea);
              this.events.add(row1);
              this.events.add(row2);
              this.events.add(row3);
         protected JLabel createUpdateButton(final int field, final int amount, final boolean month) {
             final JLabel label = new JLabel();
             final Border selectedBorder = new EtchedBorder();
             final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
             label.setBorder(unselectedBorder);
             label.setForeground(foreground);
             label.addMouseListener(new MouseAdapter() {
                  public void mouseReleased(MouseEvent e) {
                   calendar.add(field, amount);
                   if(month){
                   updateMCalendar();}
                   else{
                        updateCalendar();
                   public void mouseEntered(MouseEvent e) {
                   label.setBorder(selectedBorder);
                  public void mouseExited(MouseEvent e) {
                   label.setBorder(unselectedBorder);
             return label;
         private void updateMCalendar() {
              this.calendar.set(Calendar.DAY_OF_MONTH, 1);
              updateCalendar();     
         private void setupHeaders() {
              //MONTH CONTROLS
             monthCont.setLayout(new BoxLayout(monthCont, BoxLayout.X_AXIS));
             monthCont.setBackground(background);
             monthCont.setOpaque(true);
             JLabel label;
             label = createUpdateButton(Calendar.YEAR, -1,false);
             label.setText("<<");
             label.setToolTipText("Previous Year");
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(label);
             monthCont.add(Box.createHorizontalStrut(12));
             label = createUpdateButton(Calendar.MONTH, -1,true);
             label.setText("< ");
             label.setToolTipText("Previous Month");
             monthCont.add(label);
             monthLabel =new JLabel("", JLabel.CENTER);
             monthLabel.setForeground(foreground);
             //monthCont.add(Box.createHorizontalGlue());
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(monthLabel);
             monthCont.add(Box.createHorizontalStrut(12));
             //monthCont.add(Box.createHorizontalGlue());
             label =createUpdateButton(Calendar.MONTH, 1,true);
             label.setText(" >");
             label.setToolTipText("Next Month");
             monthCont.add(label);
             label = createUpdateButton(Calendar.YEAR, 1,false);
             label.setText(">>");
             label.setToolTipText("Next Year");
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(label);
             monthCont.add(Box.createHorizontalStrut(12));
             //WEEK CONTROLS
             weekCont.setLayout(new BoxLayout(weekCont, BoxLayout.X_AXIS));
             weekCont.setBackground(background);
             weekCont.setOpaque(true);
             JLabel label1;
             label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, -1,false);
             label1.setText("<<");
             label1.setToolTipText("Previous Week");
             weekCont.add(label1);
             weekLabel =new JLabel("", JLabel.CENTER);
             weekLabel.setForeground(foreground);
             JLabel lweek =new JLabel("Week:  ", JLabel.CENTER);
             lweek.setForeground(foreground);
             //monthCont.add(Box.createHorizontalGlue());
             weekCont.add(Box.createHorizontalStrut(12));
             weekCont.add(lweek);
             weekCont.add(weekLabel);
             weekCont.add(Box.createHorizontalStrut(12));
             //monthCont.add(Box.createHorizontalGlue());
             label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, 1,false);
             label1.setText(">>");
             label1.setToolTipText("Next Week");
             weekCont.add(label1);
         public void setupDays(){
              monday.setLayout(new BoxLayout(monday,1));
              tuesday.setLayout(new BoxLayout(tuesday,1));
              wednesday.setLayout(new BoxLayout(wednesday,1));
              thursday.setLayout(new BoxLayout(thursday,1));
              friday.setLayout(new BoxLayout(friday,1));
              saturday.setLayout(new BoxLayout(saturday,1));
              sunday.setLayout(new BoxLayout(sunday,1));
              monday.add(this.lmonday);
              monday.add(this.mondayEventsScroll);
              monday.setBorder(BorderFactory.createTitledBorder("Monday"));
              tuesday.add(this.ltuesday);
              tuesday.add(this.tuesdayEventsScroll);
              tuesday.setBorder(BorderFactory.createTitledBorder("Tuesday"));
              wednesday.add(this.lwednesday);
              wednesday.add(this.wednesdayEventsScroll);
              wednesday.setBorder(BorderFactory.createTitledBorder("Wednesday"));
              thursday.add(this.lthursday);
              thursday.add(this.thursdayEventsScroll);
              thursday.setBorder(BorderFactory.createTitledBorder("Thursday"));
              friday.add(this.lfriday);
              friday.add(this.fridayEventsScroll);
              friday.setBorder(BorderFactory.createTitledBorder("Friday"));
              saturday.add(this.lsaturday);
              saturday.add(this.saturdayEventsScroll);
              saturday.setBorder(BorderFactory.createTitledBorder("Saturday"));
              sunday.add(this.lsunday);
              sunday.add(this.sundayEventsScroll);
              sunday.setBorder(BorderFactory.createTitledBorder("Sunday"));
              this.mondayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.monday.setPreferredSize(new Dimension(145,300));
              this.tuesdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.tuesday.setPreferredSize(new Dimension(145,300));
              this.wednesdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.wednesday.setPreferredSize(new Dimension(145,300));
              this.thursdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.thursday.setPreferredSize(new Dimension(145,300));
              this.fridayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.friday.setPreferredSize(new Dimension(145,300));
              this.saturdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.saturday.setPreferredSize(new Dimension(145,300));
              this.sundayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.sunday.setPreferredSize(new Dimension(145,300));
              daysOfWeek.add(this.sunday);
              daysOfWeek.add(this.monday);
              daysOfWeek.add(this.tuesday);
              daysOfWeek.add(this.wednesday);
              daysOfWeek.add(this.thursday);
              daysOfWeek.add(this.friday);
              daysOfWeek.add(this.saturday);
        private void updateCalendar() {
             monthLabel.setText(monthFormat.format(calendar.getTime()) );
             weekLabel.setText(String.valueOf(this.calendar.get(calendar.WEEK_OF_MONTH)));
             //Blank out / empty strings for first elements that do not start on sunday
             Calendar setupCalendar = (Calendar) calendar.clone();
             setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
           // while(setupCalendar.get(Calendar.DAY_OF_WEEK) < calendar.getActualMaximum(Calendar.DAY_OF_WEEK)) {
                //System.out.println("day of month: " + setupCalendar.get(Calendar.DAY_OF_MONTH));
                //System.out.println("day of week: " + (setupCalendar.get(Calendar.DAY_OF_WEEK)));
                //System.out.println("week of month: " + calendar.get(Calendar.WEEK_OF_MONTH) + "\n");
                  setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
        public void setDayLabels(int day, int dayOfWeek){
             if(dayOfWeek == 1){
                  this.lsunday.setText(String.valueOf(day));
             if(dayOfWeek == 2){
                  this.lmonday.setText(String.valueOf(day));
             if(dayOfWeek == 3){
                  this.ltuesday.setText(String.valueOf(day));
             if(dayOfWeek == 4){
                  this.lwednesday.setText(String.valueOf(day));
             if(dayOfWeek == 5){
                  this.lthursday.setText(String.valueOf(day));
             if(dayOfWeek == 6){
                  this.lfriday.setText(String.valueOf(day));
             if(dayOfWeek == 7){
                  this.lsaturday.setText(String.valueOf(day));
         @Override
         public void actionPerformed(ActionEvent arg0) {
         @Override
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyPressed(KeyEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyReleased(KeyEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyTyped(KeyEvent arg0) {
              // TODO Auto-generated method stub
         public static void main(String args[]){
              JFrame frame = new JFrame();
              frame.setSize(1100, 670);
              frame.add(new CalendarSystem());
              frame.setVisible(true);
    }Thanks
    Dan

  • MouseListener in JScrollPane doesn't react when scroll arrows focused

    If I press/release/enter a ScrollBar in any area except of the arrows, the listener reacts OK(the testing text is printed). Why does it happen? Aren't the arrows part of The JScrollBar component? What is the solution?
    import javax.swing.JScrollBar;
    import java.awt.event.MouseListener;
    import java.awt.event.AdjustmentEvent;
    import java.awt.event.MouseEvent;
    public class TheScrollBar extends JScrollBar
    public TheScrollBar()
    addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseEntered(MouseEvent e)
    System.out.println("Entered");               
    public void mousePressed(MouseEvent e)
         System.out.println("Pressed");
    public void mouseReleased(MouseEvent e)
         System.out.println("Released");
    }

    Hi
    A quick piece of test code shows that the buttons are separate components.
    import java.awt.*;
    import javax.swing.*;
    public class ScrollBarTest
        private static int total = 0;
        public static void main(String[] args) {
            explore(new JScrollBar());
            System.exit(0);
        public static void explore(Component c) {
            System.out.println("Component [" + total++ +"] is of type: " + c.getClass());
            // recurse
            if (c instanceof Container) {
                Container cont = (Container)c;
                int count = cont.getComponentCount();
                for (int i = 0; i < count; i++) {
                    explore (cont.getComponent(i));
    }Generates output like this:
    Component [0] is of type: class javax.swing.JScrollBar
    Component [1] is of type: class javax.swing.plaf.metal.MetalScrollButton
    Component [2] is of type: class javax.swing.plaf.metal.MetalScrollButton
    So, yes, they are separate components.
    -- Patrick

  • Why isn't Java letting me change the background color of the current panel?

    Basically, I am just trying to learn all there is about interactive mouse gestures and am attempting to build some sort of frankenstein-ish paint program.
    Here is the code:
    import java.awt.Color;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    public class MyPaint extends JPanel
        JButton button;
        JFrame frame;
        int currentX;
        int currentY;
        int counter = 1;
        public MyPaint()
            createComponents();
            addComponentsToPanels();
            setFrameProperties();
            activateListeners();
        public void addComponentsToPanels()
            this.add(button);
        public void createComponents()
            button = new JButton("Button");
            button.setToolTipText("This is the first button");
        public void setFrameProperties()
            frame = new JFrame();
            frame.setSize(400,400);
            frame.setResizable(false);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(this);
        public void activateListeners()
            MyMouseListener listener = new MyMouseListener();
            button.addMouseListener(listener);
            button.addMouseMotionListener(listener);
        private class MyMouseListener implements MouseListener, MouseMotionListener
            MyPaint myPaint = new MyPaint();
            public void mouseClicked(MouseEvent e) throws UnsupportedOperationException
                JOptionPane.showMessageDialog(null,"The mouse was clicked!");
            public void mousePressed(MouseEvent e) throws UnsupportedOperationException
                JOptionPane.showMessageDialog(null,"The mouse was pressed!");
            public void mouseReleased(MouseEvent e) throws UnsupportedOperationException
                JOptionPane.showMessageDialog(null,"The mouse was released!");
            public void mouseEntered(MouseEvent e) throws UnsupportedOperationException
                myPaint.setBackground(Color.RED); // why isn't this working? - I want the original panel to be red (not the newly created windows on top)
            public void mouseExited(MouseEvent e) throws UnsupportedOperationException
                myPaint.setBackground(Color.BLUE); // why isn't this working? - I want the original panel to be blue (not the newly created windows on top)
            public void mouseDragged(MouseEvent e) throws UnsupportedOperationException
                currentX = e.getX();
                currentY = e.getY();
                repaint();
            public void mouseMoved(MouseEvent e) throws UnsupportedOperationException // why is this only being called once?
                System.out.println("mouseMoved: " + counter);
                counter++;
        public static void main(String[] args)
            new MyPaint();
    }I would just like to know how to make the inner class set the background of the panel of the outer class of the same window instead of doing what I want but in a newly opened window.
    Any help in fixing this would be greatly appreciated!
    Thanks in advance!

    Thanks! I just wanted to add:
    In addition to commenting out MyPaint myPaint = new MyPaint() and removing the this keyword when dereferencing setBackground() in MyMouseListener , I also changed
    button.addMouseListener(listener);
    button.addMouseMotionListener(listener);
    into
    this.addMouseListener(listener);
    this.addMouseMotionListener(listener);
    so that the colour changes when you hover the cursor in or out of the panel instead of the button.

  • Calculating and displaying the Length of the side of a triangle

    Hi everyone. I am currently working on Dragging and Stretching a triangle on screen. Ive got it working to a certain extent but the only problem is that whenever I go to the point from which i have to drag my triangle i.e. the Left hand Corner of the BAse at exactly 300,300 it redraws a new triangle below the existing one and then when i stretch it from the top and the right it leaves a trail of triangles everytime. But when i resize my window it clears the trail only to start agian when I drag or stretch it...
    All my code for wahtever I have done is displayed below. I would appreciate all the help that any one can offer.
    Secondly , as I stretch my triangle I would like to calculate My Length of the hypotenuse and the other 2 sides as they change and display it in System.out.println for now...
    PLEASE HELP
    the code is
    This is my Main Form --- Interactive Geometry.java
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    * InteractiveGeometry.java
    * Created on 30 November 2004, 20:29
    * @author  Kripa Bhojwani
    public class InteractiveGeometry extends javax.swing.JFrame {
        public EastPanel eastpanel;
        public Container container;
        public GeomPanel gp;
        public boolean pressed = false;
        public boolean pressT = false;
        public boolean pressR = false;
        /** Creates new form InteractiveGeometry */
        public InteractiveGeometry() {
            initComponents();
            eastpanel = new EastPanel();
            container = new Container();
            Model model = new Model(300,150,450,300,300,300);
            gp = new GeomPanel(model);
            container = getContentPane();
            container.add(eastpanel,BorderLayout.EAST);
            container.add(gp,BorderLayout.CENTER);
            setSize(1400,9950);
            gp.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseDragged(MouseEvent me) {
                    setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
                public void mouseMoved(MouseEvent me) {
                    setTitle("Moving: x=" + me.getX() + "; y=" + me.getY());
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            jMenuBar2 = new javax.swing.JMenuBar();
            jMenu2 = new javax.swing.JMenu();
            jMenuItem1 = new javax.swing.JMenuItem();
            jMenu1 = new javax.swing.JMenu();
            jMenuItem2 = new javax.swing.JMenuItem();
            addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    formMouseDragged(evt);
                public void mouseMoved(java.awt.event.MouseEvent evt) {
                    formMouseMoved(evt);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jMenuBar2.setBackground(new java.awt.Color(0, 102, 204));
            jMenu2.setBackground(new java.awt.Color(222, 222, 238));
            jMenu2.setText("File");
            jMenu2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenu2ActionPerformed(evt);
            jMenuItem1.setBackground(new java.awt.Color(204, 255, 255));
            jMenuItem1.setText("Exit");
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem1ActionPerformed(evt);
            jMenu2.add(jMenuItem1);
            jMenuBar2.add(jMenu2);
            jMenu1.setBackground(new java.awt.Color(199, 215, 255));
            jMenu1.setText("Theorem ");
            jMenuItem2.setText("Pythagoras Theorem");
            jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem2ActionPerformed(evt);
            jMenu1.add(jMenuItem2);
            jMenuBar2.add(jMenu1);
            setJMenuBar(jMenuBar2);
            pack();
        private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        private void formMouseDragged(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        private void formMouseMoved(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        public void mouseDragged(MouseEvent me) {
            setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
        private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            InteractiveGeometry ig = new InteractiveGeometry();
            ig.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ig.show();
            // new InteractiveGeometry().show();
        // Variables declaration - do not modify
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar2;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JMenuItem jMenuItem2;
        // End of variables declaration
    This is my Panel -- GeomPanel.java which draws everything -- /*
    * GeomPanel.java
    * Created on 30 November 2004, 20:29
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.Graphics.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    import java.awt.event.*;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import javax.swing.event.TableModelListener;
    import javax.swing.JScrollPane;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.Container.*;
    * @author Kripa Bhojwani
    public class GeomPanel extends javax.swing.JPanel implements Observer, MouseMotionListener, MouseListener {
    private Model model;
    private boolean pressed = false;
    private boolean pressT = false;
    private boolean pressR = false;
    /** Creates new form GeomPanel */
    public GeomPanel(Model model) {
    this.model = model;
    model.addObserver(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    initComponents();
    setBackground(Color.getHSBColor(6,600,660));
    public void paintComponent(Graphics gfx) {
    Graphics2D g = (Graphics2D) gfx;
    Point tc = model.getTop();
    Point lc = model.getLeft();
    Point rc = model.getRight();
    Point2D.Double p1 = new Point2D.Double(tc.getX(),tc.getY());
    Point2D.Double p2 = new Point2D.Double(lc.getX(),lc.getY());
    Point2D.Double p3 = new Point2D.Double(rc.getX(),rc.getY());
    Line2D.Double line = new Line2D.Double(p1, p2);
    Line2D.Double line1 = new Line2D.Double(p2, p3);
    Line2D.Double line2 = new Line2D.Double(p1, p3);
    g.setColor(Color.BLACK);
    g.draw(line);
    g.draw(line2);
    g.draw(line1);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    setLayout(new java.awt.BorderLayout());
    addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
    public void mouseDragged(java.awt.event.MouseEvent evt) {
    formMouseDragged(evt);
    private void formMouseDragged(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    public void mouseClicked(MouseEvent e) {
    public void mouseDragged(MouseEvent e) {
    System.out.println("Dragged at "+ e.getX()+ "," + e.getY());
    if(pressed == true){
    model.setLeft(e.getX() , e.getY());
    else if(pressT == true){
    model.setTop(e.getX() , e.getY());
    else if (pressR == true){
    model.setRight(e.getX(), e.getY());
    else{
    pressed = false;
    pressT= false;
    pressR=false;
    repaint();
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mouseMoved(MouseEvent e) {
    System.out.println("Mouse at " + e.getX() +"," + e.getY());
    public void mousePressed(MouseEvent e) {
    if (model.getLeft().getX()== e.getX() && model.getLeft().getY()== e.getY()){
    pressed = true;
    else if (model.getTop().getX()==e.getX() && model.getTop().getY()==e.getY()){
    pressT = true;
    else if(model.getRight().getX() == e.getX() && model.getRight().getY()==e.getY()){
    pressR = true;
    // else if(model.getCircle().getX() == e.getX() && model.getCircle().getY() == e.getY()){
    // inoval = true;
    else {
    pressed =false;
    pressT = false;
    pressR = false;
    } repaint();
    public void mouseReleased(MouseEvent e) {
    if(pressed == true){
    model.setLeft(e.getX(),e.getY());
    else if (pressT ==true ){
    model.setTop(e.getX(), e.getY());
    else if(pressR ==true){
    model.setRight(e.getX(),e.getY());
    else {
    pressed = false;
    pressT = false;
    pressR = false;
    repaint();
    public void update(Observable o, Object arg) {
    repaint();
    // Variables declaration - do not modify
    // End of variables declaration
    This is my Model class called Model.java which Holds all teh data for my triangle
    import java.awt.Point;
    import java.util.Observable;
    * Model.java
    * Created on 05 December 2004, 14:11
    * @author  Kripa Bhojwani
    public class Model extends Observable{
        private int  x1,x2,x3, y1,y2,y3;
        private int _transx;
        private int _transy;
        private int _c;
        private int _d;
        /** Creates a new instance of Model */
        public Model(int x1, int y1, int x2, int y2, int x3, int y3) {
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
            this.x3 = x3;
            this.y3 = y3;
            setChanged();
            notifyObservers();
        public void setTop(int x1, int y1){
            //this.x1 =x1;
            this.y1= y1;
            setChanged();
            notifyObservers();
        public void setRight(int x2, int y2){
            this.x2 = x2;
            // this.y2 =y2;
            setChanged();
            notifyObservers();
        public void setLeft(int x3, int y3){
            _transx = x3 - this.x3;
            _transy = y3 - this.y3;
            this.x3 += _transx;
            this.y3 += _transy;
            this.y2 += _transy;
            this.x2 += _transx;
            this.x1 += _transx;
            this.y1 += _transy;
            setChanged();
            notifyObservers();
        public Point getTop(){
            Point p = new Point(x1,y1);
            return p;
        public Point getRight(){
            Point p1 = new Point(x2,y2);
            return p1;
        public Point getLeft(){
            Point p3 = new Point(x3,y3);
            return p3;
        public void update() {
            setChanged();
            notifyObservers();
    This is my TableModel which is the JTable to display all the Cordinates and Lengths and other Measurements like angles etc./*
    * TableModel.java
    * Created on 03 December 2004, 15:08
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Observer;
    import javax.swing.event.TableModelEvent;
    import javax.swing.table.AbstractTableModel;
    * @author Kripa Bhojwani
    public class TableModel extends AbstractTableModel implements Observer{
    private String[] columnNames = {"Point", "X Coordinate", "Y Coordinate"};
    private Object[][] data = {};
    private int rowCount;
    private int columnCount;
    /** Creates a new instance of TableModel */
    public TableModel() {
    rowCount = 0;
    columnCount = 3;
    public int getColumnCount() {
    return columnCount;
    public int getRowCount() {
    return rowCount;
    public String getColumnName(int col) {
    return columnNames[col];
    public void setColumnName (String[] name){
    columnNames = name;
    public void setValueAt(Object obj, int row, int col) {
    data[row][col] = obj;
    fireTableCellUpdated(row, col);
    TableModelEvent tme = new TableModelEvent(this);
    fireTableChanged(tme);
    public Object getValueAt(int row, int col) {
    return data[row][col];
    public void update(java.util.Observable o, Object arg) {
    This is the Panel on the east side of My Main application form which will display all the measurements and Cordinates ---EastPanel.java
    import java.awt.BorderLayout;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.TableModelListener;
    import java.awt.Dimension;
    * EastPanel.java
    * Created on 04 December 2004, 23:07
    * @author  Kripa Bhojwani
    public class EastPanel extends javax.swing.JPanel implements TableModelListener{
        private TableModel tm;
        /** Creates new form EastPanel */
        public EastPanel() {   
          initComponents();
            tm = new TableModel();
            JTable table1 = new JTable(tm);
            table1.setPreferredScrollableViewportSize(new Dimension(250,264));
            table1.getModel().addTableModelListener(this);
            JScrollPane sp = new JScrollPane(table1);
            add(sp,BorderLayout.EAST);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            setLayout(new java.awt.BorderLayout());
        public void tableChanged(javax.swing.event.TableModelEvent e) {
        // Variables declaration - do not modify
        // End of variables declaration
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    public class G
    public G()
    TriangleModel tri = new
    ri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(view.getUIPanel(),
    Panel(), "North");
    f.getContentPane().add(view);
    f.getContentPane().add(view.getTablePanel(),
    Panel(), "South");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    public static void main(String[] args)
    new G();
    class TriangleModel // (x1,
    y1)
    {                                         //      |\
    static final int SIDES = 3; // | \
    private int cx, cy; // |
    | \
    Polygon triangle; // |_
    |_ _\ (x3, y3)
    int selectedIndex; // (x2,
    (x2, y2)
    NumberFormat nf;
    Line2D[] medians;
    Point2D centroid;
    public TriangleModel(int x1, int y1, int x2, int
    int y2, int x3, int y3)
    int[] x = new int[] { x1, x2, x3 };
    int[] y = new int[] { y1, y2, y3 };
    triangle = new Polygon(x, y, SIDES);
    nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(1);
    public boolean contains(Point p)
    // Polygon.contains doesn't work well enough
    return (new Area(triangle)).contains(p);
    public boolean isLineSelected(Rectangle r)
    Line2D line = new Line2D.Double();
    for(int j = 0; j < SIDES; j++)
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    int x1 = x[j];
    int y1 = y[j];
    int x2 = x[(j + 1) % SIDES];
    int y2 = y[(j + 1) % SIDES];
    line.setLine(x1, y1, x2, y2);
    if(line.intersects(r))
    selectedIndex = j;
    return true;
    selectedIndex = -1;
    return false;
    * Only works for right triangle with right angle
    angle at (x2, y2)
    public void moveSide(int dx, int dy, Point p)
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    switch(selectedIndex)
    case 0:
    x[0] += dx;
    x[1] += dx;
    break;
    case 1:
    y[1] += dy;
    y[2] += dy;
    break;
    case 2:
    double rise = y[2] - y[0];
    double run = x[2] - x[0];
    double slope = rise/run;
    // rise / run == (y[2] - p.y) / (x[2]
    ] - p.y) / (x[2] - p.x)
    x[2] = p.x + (int)((y[2] - p.y) /
    )((y[2] - p.y) / slope);
    // rise / run == (p.y - y[0]) / (p.x
    y - y[0]) / (p.x - x[0])
    y[0] = p.y - (int)((p.x - x[0]) *
    )((p.x - x[0]) * slope);
    public void translate(int dx, int dy)
    triangle.translate(dx, dy);
    public Polygon getTriangle()
    return triangle;
    public String findCentroid()
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    // construct the medians defined as the line
    the line from
    // any vertex to the midpoint of the opposite
    opposite line
    medians = new Line2D[x.length];
    for(int j = 0; j < x.length; j++)
    int next = (j + 1) % x.length;
    int last = (j + 2) % x.length;
    Point2D vertex = new Point2D.Double(x[j],
    Double(x[j], y[j]);
    // get midpoint of line opposite vertex
    double dx = ((double)x[last] -
    le)x[last] - x[next])/2;
    double dy = ((double)y[last] -
    le)y[last] - y[next])/2;
    Point2D oppLineCenter = new
    Center = new Point2D.Double(x[next] + dx,
    y[next]
    y[next] + dy);
    medians[j] = new Line2D.Double(vertex,
    uble(vertex, oppLineCenter);
    // centroid is located on any median 2/3 the
    2/3 the way from the
    // vertex (P1) to the midpoint (P2) on the
    ) on the opposite side
    double[] lengths = getSideLengths();
    double dx = (medians[0].getX2() -
    etX2() - medians[0].getX1())*2/3;
    double dy = (medians[0].getY2() -
    etY2() - medians[0].getY1())*2/3;
    double px = medians[0].getX1() + dx;
    double py = medians[0].getY1() + dy;
    //System.out.println("px = " + nf.format(px)
    rmat(px) +
    // "\tpy = " +
    py = " + nf.format(py));
    centroid = new Point2D.Double(px, py);
    return "(" + nf.format(px) + ", " +
    ", " + nf.format(py) + ")";
    public String[] getAngles()
    double[] lengths = getSideLengths();
    String[] vertices = new
    es = new String[lengths.length];
    for(int j = 0; j < lengths.length; j++)
    int opp = (j + 1) % lengths.length;
    int last = (j + 2) % lengths.length;
    double top = lengths[j] * lengths[j] +
    lengths[last] *
    lengths[last] * lengths[last] -
    lengths[opp] *
    lengths[opp] * lengths[opp];
    double divisor = 2 * lengths[j] *
    lengths[j] * lengths[last];
    double vertex = Math.acos(top /
    h.acos(top / divisor);
    vertices[j] =
    ertices[j] = nf.format(Math.toDegrees(vertex));
    return vertices;
    public String[] getLengths()
    double[] lengths = getSideLengths();
    String[] lengthStrs = new
    rs = new String[lengths.length];
    for(int j = 0; j < lengthStrs.length; j++)
    lengthStrs[j] = nf.format(lengths[j]);
    return lengthStrs;
    public String[] getSquares()
    double[] lengths = getSideLengths();
    String[] squareStrs = new
    rs = new String[lengths.length];
    for(int j = 0; j < squareStrs.length; j++)
    squareStrs[j] = nf.format(lengths[j] *
    lengths[j] * lengths[j]);
    return squareStrs;
    private double[] getSideLengths()
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    double[] lengths = new double[SIDES];
    for(int j = 0; j < SIDES; j++)
    int next = (j + 1) % SIDES;
    lengths[j] = Point.distance(x[j], y[j],
    (x[j], y[j], x[next], y[next]);
    return lengths;
    class TriangleView extends JPanel
    private TriangleModel model;
    private Polygon triangle;
    private JTable table;
    private JLabel centroidLabel;
    private boolean showConstruction;
    TriangleControl control;
    public TriangleView(TriangleModel model)
    this.model = model;
    triangle = model.getTriangle();
    showConstruction = false;
    control = new TriangleControl(this);
    addMouseListener(control);
    addMouseMotionListener(control);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.draw(triangle);
    if(model.medians == null)
    centroidLabel.setText("centroid location:
    id location: " + model.findCentroid());
    // draw medians and centroid point
    if(showConstruction && !control.dragging)
    g2.setPaint(Color.red);
    for(int j = 0; j < 3; j++)
    g2.draw(model.medians[j]);
    g2.setPaint(Color.blue);
    g2.fill(new
    g2.fill(new Ellipse2D.Double(model.centroid.getX() -
    2,
    model.centroid.getY()
    model.centroid.getY() - 2, 4, 4));
    public TriangleModel getModel()
    return model;
    public JTable getTable()
    return table;
    public JLabel getCentroidLabel()
    return centroidLabel;
    public JPanel getUIPanel()
    JCheckBox showCon = new JCheckBox("show
    ox("show construction");
    showCon.addActionListener(new
    ener(new ActionListener()
    public void actionPerformed(ActionEvent
    (ActionEvent e)
    boolean state =
    boolean state =
    ((JCheckBox)e.getSource()).isSelected();
    showConstruction = state;
    repaint();
    JPanel panel = new JPanel();
    panel.add(showCon);
    return panel;
    public JPanel getTablePanel()
    String[] headers = new String[] { "", "", "",
    // row and column data labels
    String[] rowHeaders = {
    "sides", "lengths", "squares", "angles",
    ", "angles", "degrees"
    String[] sidesRow = { "vertical",
    rtical", "horizontal", "hypotenuse" };
    String[] anglesRow = { "hyp to ver", "ver to
    "ver to hor", "hor to hyp" };
    // collect data from model
    String[] angles = model.getAngles();
    String[] lengths = model.getLengths();
    String[] squares = model.getSquares();
    String[][] allData = { sidesRow, lengths,
    lengths, squares, anglesRow, angles };
    int rows = 5;
    int cols = 4;
    Object[][] data = new Object[rows][cols];
    for(int row = 0; row < rows; row++)
    data[row][0] = rowHeaders[row];
    for(int col = 1; col < cols; col++)
    data[row][col] = allData[row][col -
    lData[row][col - 1];
    table = new JTable(data, headers)
    public boolean isCellEditable(int row,
    ble(int row, int col)
    return false;
    DefaultTableCellRenderer renderer =
    (DefaultTableCellRenderer)table.getDefaultRenderer(St
    ring.class);
    renderer.setHorizontalAlignment(JLabel.CENTER);
    centroidLabel = new JLabel("centroid
    centroid location: ", JLabel.CENTER);
    Dimension d =
    sion d = centroidLabel.getPreferredSize();
    d.height = table.getRowHeight();
    centroidLabel.setPreferredSize(d);
    JPanel panel = new JPanel(new
    anel(new BorderLayout());
    panel.setBorder(BorderFactory.createTitledBorder("tri
    angle data"));
    panel.add(table);
    panel.add(centroidLabel, "South");
    return panel;
    class TriangleControl extends MouseInputAdapter
    TriangleView view;
    TriangleModel model;
    Point start;
    boolean dragging, altering;
    Rectangle lineLens; // used for line
    line selection
    public TriangleControl(TriangleView tv)
    view = tv;
    model = view.getModel();
    dragging = altering = false;
    lineLens = new Rectangle(0, 0, 6, 6);
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    lineLens.setLocation(p.x - 3, p.y - 3);
    // are we over a line
    if(model.isLineSelected(lineLens))
    start = p;
    altering = true;
    // or are we within the triangle
    else if(model.contains(p))
    start = p;
    dragging = true;
    public void mouseReleased(MouseEvent e)
    altering = false;
    dragging = false;
    view.getCentroidLabel().setText("centroid
    centroid location: " +
    model.findCentroid());
    view.repaint(); // for the construction
    truction lines
    public void mouseDragged(MouseEvent e)
    Point p = e.getPoint();
    if(altering)
    int x = p.x - start.x;
    int y = p.y - start.y;
    model.moveSide(x, y, p);
    updateTable();
    view.repaint();
    start = p;
    else if(dragging)
    int x = p.x - start.x;
    int y = p.y - start.y;
    model.translate(x, y);
    view.repaint();
    start = p;
    private void updateTable()
    String[] lengths = model.getLengths();
    String[] squares = model.getSquares();
    String[] angles = model.getAngles();
    JTable table = view.getTable();
    for(int j = 0; j < angles.length; j++)
    table.setValueAt(lengths[j], 1, j + 1);
    table.setValueAt(squares[j], 2, j + 1);
    table.setValueAt(angles[j], 4, j + 1);
    view.getCentroidLabel().setText("centroid
    centroid location: " +
    model.findCentroid());
    Hey sorry mate.. ive got a nother problem.
    I need to add loads of theorems to this tool. so i need a JMenu Bar called File with all the normal things. then another Menu called Theorems where i can have a list of JMenuItems with the theorem names --- Like when they click on Pythagoras Theorem it opens up all the triangle and the traingle data that u helped me with.
    The thing is im using netbeans and in netbeans i can do it coz its there and all you got to do is put the components together.
    Please Help
    Thanks...
    Sharan

  • GridBagLayout and Panel Border problem

    I have 3 panels like
    A
    B
    C
    and the C panel has a Mouse Listener that on a mouseEntered creates a border around the same panel and on a mouseExited clears that border.
    When this border is created the A and B panels go up a little bit .. they move alone when the border is created.
    Is there any way to fix this problem? Is there any way to get the panels static?
    the code is close to the following:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    import java.awt.event.*;
    import java.text.NumberFormat;
    public class Game extends JFrame implements MouseListener
    JPanel game, options, top, down, middle;
    NumberFormat nf;
    public Game() {
    super("Game");
    nf = NumberFormat.getPercentInstance();
    nf.setMaximumFractionDigits(1);
    JPanel center = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = gbc.BOTH;
    gbc.weighty = 1.0;
    gbc.weightx = 0.8;
    center.add(getGamePanel(), gbc);
    gbc.weightx = 0.104;
    center.add(getOptionsPanel(), gbc);
    Container cp = getContentPane();
    // use the JFrame default BorderLayout
    cp.add(center); // default center section
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setSize(700,600);
    // this.setResizable(false);
    setLocationRelativeTo(null);
    setVisible(true);
    addComponentListener(new ComponentAdapter()
    public void componentResized(ComponentEvent e)
    showSizeInfo();
    showSizeInfo();
    private void showSizeInfo()
    Dimension d = getContentPane().getSize();
    double totalWidth = game.getWidth() + options.getWidth();
    double gamePercent = game.getWidth() / totalWidth;
    double optionsPercent = options.getWidth() / totalWidth;
    double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
    double topPercent = top.getHeight() / totalHeight;
    double middlePercent = middle.getHeight() / totalHeight;
    double downPercent = down.getHeight() / totalHeight;
    System.out.println("content size = " + d.width + ", " + d.height + "\n" +
    "game width = " + nf.format(gamePercent) + "\n" +
    "options width = " + nf.format(optionsPercent) + "\n" +
    "top height = " + nf.format(topPercent) + "\n" +
    "middle height = " + nf.format(middlePercent) + "\n" +
    "down height = " + nf.format(downPercent) + "\n");
    private JPanel getGamePanel()
    // init components
    top = new JPanel(new BorderLayout());
    top.setBackground(Color.red);
    top.add(new JLabel("top panel", JLabel.CENTER));
    middle = new JPanel(new BorderLayout());
    middle.setBackground(Color.green.darker());
    middle.add(new JLabel("middle panel", JLabel.CENTER));
    down = new JPanel(new BorderLayout());
    down.setBackground(Color.blue);
    down.add(new JLabel("down panel", JLabel.CENTER));
    // layout game panel
    game = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.fill = gbc.BOTH;
    gbc.gridwidth = gbc.REMAINDER;
    gbc.weighty = 0.2;
    game.add(top, gbc);
    gbc.weighty = 0.425;
    game.add(middle, gbc);
    gbc.weighty = 0.2;
    game.add(down, gbc);
    down.addMouseListener(this);
    return game;
    private JPanel getOptionsPanel()
    options = new JPanel(new BorderLayout());
    options.setBackground(Color.pink);
    options.add(new JLabel("options panel", JLabel.CENTER));
    return options;
    // mouse listener events
         public void mouseClicked( MouseEvent e ) {
    System.out.println("pressed");
         public void mousePressed( MouseEvent e ) {
         public void mouseReleased( MouseEvent e ) {
         public void mouseEntered( MouseEvent e ) {
    Border redline = BorderFactory.createLineBorder(Color.red);
    JPanel x = (JPanel) e.getSource();
    x.setBorder(redline);
         public void mouseExited( MouseEvent e ){
    JPanel x = (JPanel) e.getSource();
    x.setBorder(null);
    public static void main(String[] args ) {
    Game exe = new Game();
    exe.show();
    }

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    public class Game extends JFrame implements MouseListener{
      JPanel game, options, top, down, middle;
      NumberFormat nf;
      public Game() {
        super("Game");
        nf = NumberFormat.getPercentInstance();
        nf.setMaximumFractionDigits(1);
        JPanel center = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = gbc.BOTH;
        gbc.weighty = 1.0;
        gbc.weightx = 0.8;
        center.add(getGamePanel(), gbc);
        gbc.weightx = 0.104;
        center.add(getOptionsPanel(), gbc);
        Container cp = getContentPane();
        // use the JFrame default BorderLayout
        cp.add(center); // default center section
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(700,600);
        // this.setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
        addComponentListener(new ComponentAdapter(){
            public void componentResized(ComponentEvent e){
            showSizeInfo();
        showSizeInfo();
      private void showSizeInfo(){
        Dimension d = getContentPane().getSize();
        double totalWidth = game.getWidth() + options.getWidth();
        double gamePercent = game.getWidth() / totalWidth;
        double optionsPercent = options.getWidth() / totalWidth;
        double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
        double topPercent = top.getHeight() / totalHeight;
        double middlePercent = middle.getHeight() / totalHeight;
        double downPercent = down.getHeight() / totalHeight;
        System.out.println("content size = " + d.width + ", " + d.height + "\n" +
            "game width = " + nf.format(gamePercent) + "\n" +
            "options width = " + nf.format(optionsPercent) + "\n" +
            "top height = " + nf.format(topPercent) + "\n" +
            "middle height = " + nf.format(middlePercent) + "\n" +
            "down height = " + nf.format(downPercent) + "\n");
      private JPanel getGamePanel(){
        // init components
        top = new JPanel(new BorderLayout());
        top.setBackground(Color.red);
        top.add(new JLabel("top panel", JLabel.CENTER));
        middle = new JPanel(new BorderLayout());
        middle.setBackground(Color.green.darker());
        middle.add(new JLabel("middle panel", JLabel.CENTER));
        down = new JPanel(new BorderLayout());
        down.setBackground(Color.blue);
        down.add(new JLabel("down panel", JLabel.CENTER));
        // layout game panel
        game = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.fill = gbc.BOTH;
        gbc.gridwidth = gbc.REMAINDER;
        gbc.weighty = 0.2;
        game.add(top, gbc);
        gbc.weighty = 0.425;
        game.add(middle, gbc);
        gbc.weighty = 0.2;
        game.add(down, gbc);
        down.addMouseListener(this);
        return game;
      private JPanel getOptionsPanel(){
        options = new JPanel(new BorderLayout());
        options.setBackground(Color.pink);
        options.add(new JLabel("options panel", JLabel.CENTER));
        return options;
      public void mouseClicked( MouseEvent e ) {
        System.out.println("pressed");
      public void mousePressed( MouseEvent e ) {
      public void mouseReleased( MouseEvent e ) {
      public void mouseEntered( MouseEvent e ) {
        Border redline = new CalmLineBorder(Color.red);
        JPanel x = (JPanel) e.getSource();
        x.setBorder(redline);
      public void mouseExited( MouseEvent e ){
        JPanel x = (JPanel) e.getSource();
        x.setBorder(null);
      public static void main(String[] args ) {
        Game exe = new Game();
        exe.setVisible(true);
    class CalmLineBorder extends LineBorder{
      public CalmLineBorder(Color c){
        super(c);
      public CalmLineBorder(Color c, int thick){
        super(c, thick);
      public CalmLineBorder(Color c, int thick, boolean round){
        super(c, thick, round);
      public Insets getBorderInsets(Component comp){
        return new Insets(0, 0, 0, 0);
    }

  • Need help to drag a rectangle to define a zoom level

    Can some help me figure this out. I am trying to draw some graphics on a JPanel, then drag a rectangle to define a new zoom extent. I am having problems understanding how to do this with the AffineTransform. If you run the following code, you will see what I am trying to do....
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    public class TestCase extends JPanel implements MouseListener, MouseMotionListener {
      private Integer _startX = 0; // start x for dragging of rectangle
      private Integer _startY = 0; // start y for dragging of rectangle
      private Integer _lastX = 0; // end x for dragging of rectangle
      private Integer _lastY = 0; // end y for dragging of rectangle
      private boolean _isDragging = false;
      private Rectangle _rect = new Rectangle();
      private Rectangle[] _rects = null;
      private Color[] _colors = null;
      protected BufferedImage _imageBuffer = null;
      protected AffineTransform _xform = null;
      public TestCase() {
        _xform = new AffineTransform();
        _rects = new Rectangle[6];
        _rects[0] = new Rectangle(0, 0, 100, 100);
        _rects[1] = new Rectangle(100, 100, 100, 100);
        _rects[2] = new Rectangle(200, 200, 100, 100);
        _rects[3] = new Rectangle(300, 300, 100, 100);
        _rects[4] = new Rectangle(200, 0, 50, 50);
        _rects[5] = new Rectangle(250, 50, 50, 50);
        _colors = new Color[6];
        _colors[0] = Color.RED;
        _colors[1] = Color.WHITE;
        _colors[2] = Color.BLUE;
        _colors[3] = Color.GREEN;
        _colors[4] = Color.YELLOW;
        _colors[5] = Color.CYAN;
        setBackground(Color.LIGHT_GRAY);
        addMouseListener(this);
        addMouseMotionListener(this);
      // The next three methods enable user to drag a retangle
      // First, set the start points of the rectangle
      public void mousePressed(MouseEvent e) {
        _startX = new Integer(e.getX());
        _startY = new Integer(e.getY());
        _lastX = new Integer(e.getX());
        _lastY = new Integer(e.getY());
        _isDragging = true;
      // Second, drag the rectangle
      public void mouseDragged(MouseEvent e) {
        _lastX = new Integer(e.getX());
        _lastY = new Integer(e.getY());
        repaint();
      // Third, complete the rectangle, then zoom
      public void mouseReleased(MouseEvent event) {
        _lastX = new Integer(event.getX());
        _lastY = new Integer(event.getY());
        _lastX = new Integer(event.getX());
        _lastY = new Integer(event.getY());
        Rectangle rect = new Rectangle(_startX, _startY, _lastX - _startX, _lastY - _startY);
        Double widPanel = new Integer(this.getWidth()).doubleValue() / _xform.getScaleX();
        Double hgtPanel = new Integer(getHeight()).doubleValue() / _xform.getScaleY();
        Double widRect = rect.getWidth();
        Double hgtRect = rect.getHeight();
        Double scalex = widPanel.doubleValue() / widRect;
        Double scaley = hgtPanel.doubleValue() / hgtRect;
        Double translatex = _startX.doubleValue() * scalex;
        Double translatey = _startY.doubleValue() * scaley;
        _xform.setToScale(scalex, scaley);
        _xform.setToTranslation(translatex, translatey);
        _isDragging = false;
        repaint();
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        if(_isDragging){
          g2.drawImage(_imageBuffer, 0, 0, this);
          g2.setPaint(Color.RED);
          g2.drawRect(_startX, _startY, _lastX - _startX, _lastY - _startY);
        else{
          paintPanel(g2);
      protected void paintPanel(Graphics2D g) {
        Double width = this.getSize().getWidth();
        Double height = this.getSize().getHeight();
        Dimension size = this.getSize();
        _imageBuffer = new BufferedImage(Math.round(width.floatValue()), Math.round(height.floatValue()), BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = (Graphics2D) _imageBuffer.getGraphics();
        graphics.setColor(Color.LIGHT_GRAY);
        graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
        for(int i = 0; i <= _rects.length - 1; i++){
          Rectangle rect = _rects;
    Shape shape = _xform.createTransformedShape(rect);
    graphics.setColor(_colors[i]);
    graphics.fill(shape);
    g.drawImage(_imageBuffer, 0, 0, this);
    protected void zoomToExtent() {
    _xform.setToIdentity();
    repaint();
    public void mouseClicked(MouseEvent event) {
    public void mouseEntered(MouseEvent event) {
    public void mouseExited(MouseEvent event) {
    public void mouseMoved(MouseEvent event) {
    public static void main(String[] args) {
    final TestCase test = new TestCase();
    JButton btnFullExtent = new JButton("Reset");
    btnFullExtent.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    test.zoomToExtent();
    JToolBar toolBar = new JToolBar();
    toolBar.add(btnFullExtent);
    final JFrame f = new JFrame();
    f.getContentPane().setLayout(new BorderLayout());
    f.getContentPane().add(toolBar, BorderLayout.NORTH);
    f.getContentPane().add(new TestCase(), BorderLayout.CENTER);
    f.setSize(600, 400);
    f.setVisible(true);

    I modified you code a little bit, just so I could improve my understanding. I tried to swap out the class level scale and translate variables, with an AffineTransform object, but wasn't able to get it working? Do you know why this won't work?
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Rectangle2D;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    public class TestCase extends JPanel implements MouseListener, MouseMotionListener {
      private Point start;
      private Point end;
      private boolean dragging = false;
      private double zoom_x = 1.0;
      private double zoom_y = 1.0;
      private double translateX;
      private double translateY;
      private Rectangle[] _rects = null;
      private Color[] _colors = null;
      public TestCase() {
        setBackground(Color.LIGHT_GRAY);
        _rects = new Rectangle[6];
        _rects[0] = new Rectangle(0, 0, 100, 100);
        _rects[1] = new Rectangle(100, 100, 100, 100);
        _rects[2] = new Rectangle(200, 200, 100, 100);
        _rects[3] = new Rectangle(300, 300, 100, 100);
        _rects[4] = new Rectangle(200, 0, 50, 50);
        _rects[5] = new Rectangle(250, 50, 50, 50);
        _colors = new Color[6];
        _colors[0] = Color.RED;
        _colors[1] = Color.WHITE;
        _colors[2] = Color.BLUE;
        _colors[3] = Color.GREEN;
        _colors[4] = Color.YELLOW;
        _colors[5] = Color.CYAN;
        addMouseListener(this);
        addMouseMotionListener(this);
      public void mousePressed(MouseEvent e) {
        start = e.getPoint();
        dragging = true;
      public void mouseDragged(MouseEvent e) {
        end = e.getPoint();
        repaint();
      public void mouseReleased(MouseEvent e) {
        end = e.getPoint();
        double visibleWidth = getWidth();
        double visibleHeight = getHeight();
        double selectedWidth = Math.abs(end.getX() - start.getX());
        double selectedHeight = Math.abs(end.getY() - start.getY());
        double zoomFactorX = visibleWidth / selectedWidth;
        double zoomFactorY = visibleHeight / selectedHeight;
        translateX -= start.x / zoom_x;
        translateY -= start.y / zoom_y;
        zoom_x *= zoomFactorX;
        zoom_y *= zoomFactorY;
        dragging = false;
        repaint();
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        paintShapes((Graphics2D) g2.create());
        if(dragging){
          g2.setPaint(Color.RED);
          g2.drawRect(start.x, start.y, end.x - start.x, end.y - start.y);
      private void paintShapes(Graphics2D g2) {
        System.out.println("translateX=" + translateX + ", translateY=" + translateY + ", zoom_x=" + zoom_x + ", zoom_y=" + zoom_y);
        g2.scale(zoom_x, zoom_y);
        g2.translate(translateX, translateY);
        for(int i = 0; i <= _rects.length - 1; i++){
          Rectangle rect = _rects;
    g2.setColor(_colors[i]);
    g2.fill(rect);
    public void reset() {
    zoom_x = 1.0;
    zoom_y = 1.0;
    translateX = 0;
    translateY = 0;
    repaint();
    public void mouseClicked(MouseEvent event) {
    public void mouseEntered(MouseEvent event) {
    public void mouseExited(MouseEvent event) {
    public void mouseMoved(MouseEvent event) {
    public static void main(String[] args) {
    final TestCase test = new TestCase();
    JButton btnFullExtent = new JButton("Reset");
    btnFullExtent.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    test.reset();
    JToolBar toolBar = new JToolBar();
    toolBar.add(btnFullExtent);
    final JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new BorderLayout());
    f.getContentPane().add(toolBar, BorderLayout.NORTH);
    f.getContentPane().add(test, BorderLayout.CENTER);
    f.setSize(600, 400);
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • Help with my Bouncing ball?

    Hey guys,
    I really have the basis of my program working and everything however i just had one question. My Animation works by using the Alarm which uses the take notice method. The takeNotice then calls a move method that updates my ball coordinates. I am having trouble slowing down the animation. My question is how could I slow down the animation for the viewer without altering the velocity. My set period is at 25 milliseconds that makes the ball animation very smooth however when I increase the milliseconds the animation becomes sloppy and choppy. Does anyone have any ideas of how I could fix this problem???
    Thanks guys
    The BingBong class which sets up my environment...
         BingBong.java
        This class defines and implements the demo itself.
         It also implements all the methods required to implement a "MouseListener".
    import java.awt.*;                                   
    import java.awt.event.*;               
    import java.awt.geom.*;
    public class BingBong extends Frame
                             implements     MouseListener, AlarmListener
    //     The instance variables
        private Abutton resetButton,        // My  Buttons
                             throwButton,
                             slowButton,
                             fastButton;          
         private WindowClose myWindow =               //     A handle on the window
                                       new WindowClose();
         private int lastX, lastY;          //     To keep the mouse location
         private Alarm alarm;               //     We use an alarm to wake us up
         private Ball ball;                    // Creating my one ball
    //     Constructor
    //     ===========
    //     The constructor defines a new frame to accommodate the drawing window.
    //     It also sets the scene with the visualization of the element
    //     and the buttons to manipulate the value of the element.
         public BingBong()
              setTitle("Bing Bong");     //     We set the characteristics of our
              setLocation(50, 50);          //          drawing window
              setSize(420, 450);
              setBackground(Color.pink);
              setVisible(true);                         
              addWindowListener(myWindow);          //     To check on the window
              addMouseListener(this);                    //          and on the mouse
              int x = 53;      // Setting the start points for the button coordiates
              int y = 25;
              resetButton = new Abutton("Reset", Color.red, x, y);
              x += Abutton.BUTTON_WIDTH + 5;
              throwButton = new Abutton("Throw", Color.gray, x, y);
              x += Abutton.BUTTON_WIDTH + 5;
              slowButton = new Abutton("Slower", Color.yellow, x, y);
              x += Abutton.BUTTON_WIDTH + 5;
              fastButton = new Abutton("Faster", Color.green, x, y);
              alarm = new Alarm("Beep", this);     //     We "create" an alarm
              alarm.start();                              //          and we get it started
              alarm.setPeriod(25);                    // The alarm will go off every 35 milliseconds
         public void action()
              System.out.println("\nClick on one of the buttons!\n");
              repaint();   // When the program is launched we will notify the user to click via the console
    //     The next method checks where the mouse is been clicked.
    //     Each button is associated with its own action.
         private void check()
                   if (resetButton.isInside(lastX, lastY)) {
                        ball = null;  // If the reset button is hit the ball will go away
                   else if (throwButton.isInside(lastX, lastY)) {
                        double randomX = 380*Math.random();    // Creating a random starting spot for the ball
                        double randomY = 420*Math.random();
                        double randomSpeedX = (9*Math.random()) + 1; //Giving the ball a random speed
                        double randomSpeedY = (7*Math.random()) + 1; // By adding at the end I protect          
                                                                               // in case the random creates a zero
                        ball = new Ball(randomX, randomY, -randomSpeedX, -randomSpeedY);
                        // Calling the Ball constuctor to create a new ball
                   else if (slowButton.isInside(lastX, lastY)) {
                        double currentSpeedX = ball.getSpeedX();  // Getting the current ball's speed
                        double currentSpeedY = ball.getSpeedY();
                        double newSpeedX = currentSpeedX - (currentSpeedX/4); // Taking 1/4 of the current speed and
                        double newSpeedY = currentSpeedY - (currentSpeedY/4); // and subtracting it from the current speed
                        ball.setSpeed(newSpeedX, newSpeedY); // Calling the set speed method
                   else if (fastButton.isInside(lastX, lastY)) {
                        double currentSpeedX = ball.getSpeedX(); // Getting the current ball's speed
                        double currentSpeedY = ball.getSpeedY();
                        double newSpeedX = (currentSpeedX/4) + currentSpeedX; // Taking 1/4 of the current speed and
                        double newSpeedY = (currentSpeedY/4) + currentSpeedY; // and adding it to the current speed
                        ball.setSpeed(newSpeedX, newSpeedY); // Calling the set speed method
                   else  {
                        System.out.println("What?"); // I did not understand the action
                   repaint();
    //     In order to use an alarm, we need to provide a takeNotice method.
    //     It will be invoked each time the alarm goes off.
         public void takeNotice()
              if (ball != null){ // If the ball exists everytime the alarm goes off move the ball
                   ball.move();
              repaint();          //     Finally, we force a redrawing
    //     The only "graphical" method of the class is the paint method.
         public void paint(Graphics pane)
              if (throwButton != null)               //     When instantiated,
                   throwButton.paint(pane);          //     we display all the buttons
              if (slowButton != null)                    
                   slowButton.paint(pane);
              if (fastButton != null)
                   fastButton.paint(pane);
              if (resetButton != null)                    
                   resetButton.paint(pane);
              if (ball != null)                         // Drawing the ball
                   ball.paint(pane);
              pane.drawLine(10, 60, 10, 440);     // Using pixel coord. to draw the lines of our "box"
              pane.drawLine(10, 440, 410, 440);
              pane.drawLine(410, 440, 410, 60);
              pane.drawLine(10, 60, 70, 60);
              pane.drawLine(410, 60, 350, 60);
         public void mouseClicked(MouseEvent event)
              check();                                   //     Handle the mouse click
         public void mousePressed(MouseEvent event)
              lastX = event.getX();                    //     Update the mouse location
              lastY = event.getY();
              flipWhenInside();                         //     Flip any button hit by the mouse
         public void mouseReleased(MouseEvent event)
              flipWhenInside();
         public void mouseEntered(MouseEvent event) {}
         public void mouseExited(MouseEvent event) {}
         private void flipWhenInside()
              if (resetButton.isInside(lastX, lastY))  // Flips the buttons to emulate
                   resetButton.flip();                  // a push down effect when clicked.
              else if (throwButton.isInside(lastX, lastY))
                   throwButton.flip();
              else if (slowButton.isInside(lastX, lastY))
                   slowButton.flip();
              else if (fastButton.isInside(lastX, lastY))
                   fastButton.flip();
              repaint();
    }     // end BingBongMy Ball Class holds its own unique characteristics.....
         Ball.java
         Programmer: Jason Martins
         7/2/08
    import java.awt.*;
    import java.awt.event.*;
    public class Ball
         // My private variables:
         private double x = 0;    // The location of the ball.
         private double y = 0;  
         private Color color = Color.BLUE;
         private double speedX, speedY;  // The speed of my ball.
         private double gravity = 0.098; // The gravity effect (9.8 m per s).
         private double bounceFactor  = 0.97; // The bouncy ness of my ball.
         private final
                   double
                        DIAMETER = 21,      // The size of my ball.
                        LEFT_SIDE = 10,
                        RIGHT_SIDE = 410,
                        BOTTOM_BOX = 440;
         // The default constructor for the Ball.
         public Ball(){
         // The Ball constructor will create an
         // ball due its own unique x and y coordinate as well as its speed.
         public Ball(double x, double y, double speedX, double speedY){
              this.x = x;                    // When a new ball is created,
              this.y = y;                    // it will have 4 critical
              this.speedX = speedX;     // doubles. The x and y coordinate and its speed
              this.speedY = speedY;   // horizontally and vertically.
         //     Drawing a ball
         public void paint(Graphics pane)
              pane.fillOval((int) x, (int)y, (int) DIAMETER, (int) DIAMETER);
              // The fillOval method will start from the specfied x and y and draw a oval based on size and height.
         // Will set the color of the given ball, by the specific color passed.
         public void setColor(Color color){
              this.color = color;                    // Sets the color of the ball.
         // Returns the x coordinate the ball is current at.
         public double getX(){
              return x;
         // Returns the y coordinate the ball is current at.
         public double getY(){
              return y;
         // Returns the horizontal velocity of the ball.
         public double getSpeedX(){
              return speedX;
         // Returns the vertical velocity of the ball.
         public double getSpeedY(){
              return speedY;
         // Sets the speed of the ball by the horizontal and vertical velocity passed.
         public void setSpeed(double newSpeedX, double newSpeedY){
              speedX = newSpeedX;
              speedY = newSpeedY;
         // Will move the ball inside the frame depending on numerous factors.
         public void move(){
              x += speedX; // Add horizontal speed to the x location and update the location.
              y += speedY; // Add vertical speed to the y location and update the location.
              speedY += gravity; // Add gravity to the vertical speed and update the vertical speed.
              if(x <= LEFT_SIDE){ // If my x coordinate is equal to the boundry on the left.
                   x = LEFT_SIDE;  // The ball bounces reversing the horizontal velocity.
                   speedX = -speedX; 
              if(x + DIAMETER >= RIGHT_SIDE){ // If my x coordinate is equal to the boundry on the right.
                   x = RIGHT_SIDE - DIAMETER; // The ball bounces reversing the horizontal velocity.
                   speedX = -speedX;
              /*if(y <= 60 && x <= 70){
                   y = 60;
                   x = 70;
                   speedY = -speedY;
              if(y <= 60 && x >= 350){
                   y = 60;
                   x = 350 - DIAMETER;
                   speedY = -speedY;
              if(y + DIAMETER >= BOTTOM_BOX){  // If my y coordinate is equal to the boundry on the bottom.
                   y = BOTTOM_BOX - DIAMETER;   // The ball bounces reversing the vertical velocity times
                   speedY = -speedY *  bounceFactor; // the bouncyness of the ball.
    }My Alarm Class.... given to us by our professor
         Alarm.java
                                                 A l a r m
                                                 =========
         This class defines a basic timer, which "beeps" after a resetable delay.
         On each "beep," the alarm will notify the object registered when the timer
              is instantiated..
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    public class Alarm
                        extends Thread
         private AlarmListener whoWantsToKnow;     //     The object to notify
                                                           //          in case of emergency
         private int delay = 0;                         //     The first beep will occur
                                                           //          without any delay
    //     C o n s t r u c t o r s
         public Alarm()
              super("Alarm");                              //     With the default constructor,
              whoWantsToKnow = null;                    //          nobody will be notified
         public Alarm(AlarmListener someBody)
              super("Alarm");                              //     In general,  we expect to know who
              whoWantsToKnow = someBody;               //          (i.e., which object) to notify
         public Alarm(String name, AlarmListener someBody)
              super(name);                              //     We can also give a name to the alarm
              whoWantsToKnow = someBody;
    //     The setPeriod method will set or reset the period by which beeps will occur.
    //     Note that the new period will be used after reception of the following beep.
         public void setPeriod(int someDelay)
         {                                                  //     Note:  The period should be expressed
              delay = someDelay;                         //                    in milliseconds
    //     The setPeriodicBeep method will keep on notifying the "object in charge"
    //          at set time intervals.
    //     Note that the time interval can be changed at any time through setPeriod.
         private void setPeriodicBeep(int someDelay)
              delay = someDelay;
              try {
                   while (true){                              //     For as long as we have energy,
                        Thread.sleep(delay);               //          first we wait
                        if (whoWantsToKnow != null)          //          then we notify the
                             whoWantsToKnow.takeNotice();//          responsible party
                   }                                             //          (if anybody wants to hear)
              catch(InterruptedException e) {
                   System.err.println("Oh, oh ... " + e.getMessage());
    //     The alarm is a Thread, and the run method gets the thread started, and running.
         public void run()
              System.out.println("The alarm is now running.");
              setPeriodicBeep(delay);
    }     //     end of class AlarmThanks guys again

    One slightly confusing thing is that what you are calling speedX and speedY are not, in fact, the speed of your ball in the X and Y directions. They are the location-change-in-pixels-per-frame values.
    The "best" refresh rate has more to do with
    (1) the responsiveness of your application: how often it can redraw the screen. This sets an upper limit on the refresh rate. If you try a refresh rate that is too high (ie a delay that is too small) your application won't be able to keep up.
    (2) how sensitive the user is to detecting "jerkiness". This sets a lower limit on the refresh rate. If you try a refresh rate that is too low (a delay value that is too big) then the user will at some point complain that the animation is "choppy".
    It's a matter of trial and error, but I would start at 20 frames per decond (delay == 50) and see what happens. (The code I posted did that - I haven't run it.) If it appears choppy you can print the time inside your paint() method. This will let you check that you really are repainting every 50ms. If not, then you have exceeded the limit mentioned in (1). That is, your application can't "keep up" and you will need to improve the effeciency of paint().
    Say my velocity was 5, if i set my period too 1000 * 5 / (my preferred delay say 50) == 100I'm not completely sure I understand this - if your delay is 50, then the refresh rate must be 1000/50=20 frames per second. You can't change that. If you wanted the ball to move at 5 pixels per second (in the X direction) and your delay was 50 (ie 20fps) then you would find the appropriate speedX value by solving the equation:
    5 = 1000 * speedX / 50
    speedX = 0.25(Note: 5 pixels per second is not very fast)

  • Getting the bounds of a drawn image on a panel

    Hello, I have a problem with getting the bounds of a drawn image on a panel...Since it is drawn as graphics, i tried getClipBounds and since my class extends JPanel i tried to get the bounds from the panel but neither of them worked properly. It only gets the bounds of a jframe that contains the panel.Then i tried to put the panel in a layeredpane and then a container; but this time the image disappeared completely. Hope someone can help or tell me what I am doing wrong. Thanks in advance. Here is the code below:
    By the way what I am trying to do in this code is basically zooming the image in and out by dragging or the mouse wheel. But I need to get the bounds so that I can use this.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * @author Admin
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.RenderingHints;
    import java.awt.Toolkit;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseWheelEvent;
    import java.awt.event.MouseWheelListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.NoninvertibleTransformException;
    import java.awt.geom.Point2D;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    public class ZoomDemo extends JPanel {
    AffineTransform tx = new AffineTransform();
    String imagePath = "D:/Documents and Settings/Admin/Belgelerim/tsrm/resim.jpg";
    Image image = Toolkit.getDefaultToolkit().getImage(imagePath);
    int width = image.getWidth(this);
    int height = image.getHeight(this);
    int scrwidth = Toolkit.getDefaultToolkit().getScreenSize().width;
    int scrheight = Toolkit.getDefaultToolkit().getScreenSize().height;
    double zoomfac = 1.0;
    int xAdj;
    int yAdj;
    int prevY;
    double scale = 1.0;
    Point pt;
    public static int x;
    public static int y;
    public static int w;
    public static int h;
    public ZoomDemo() {
    this.addMouseWheelListener(new ZoomHandler());
    this.addMouseListener(new ZoomHandler());
    this.addMouseMotionListener(new ZoomHandler());
      repaint();
    @Override
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.drawImage(image, tx, this);
    // x =    (int) g2.getClipBounds().getX();
    // y=     (int) g2.getClipBounds().getY();
    // w=     (int) g2.getClipBounds().getWidth();
    // h=     (int) g2.getClipBounds().getHeight();
    // System.out.println(x+" "+y+" "+w+" "+h);
    //  public int getRectx(){
    //    return x;
    //public int getRecty(){
    //    return y;
    //public int getRectw(){
    //    return w;
    //public int getRecth(){
    //    return h;
    private class ZoomHandler implements MouseWheelListener,MouseListener, MouseMotionListener {
    public void mousePressed(MouseEvent e){
        System.out.println("Mouse Pressed");
    xAdj = e.getX();
    yAdj = e.getY();
    prevY = getY();
    public void mouseDragged(MouseEvent e){
           System.out.println("Mouse Dragged");
    boolean zoomed = false;
    if(e.getY()<prevY){
         zoomfac = zoomfac + 0.1;
         prevY = e.getY();
         zoomed = true;
    else if(e.getY()>prevY){
         zoomfac = zoomfac - 0.1;
         prevY = e.getY();
         zoomed = true;
       scale = zoomfac;
    Point2D p1 = new Point((int)xAdj-(width/2),(int)yAdj-(height/2));
    Point2D p2 = null;
    try {
    p2 = tx.inverseTransform(p1, null);
    } catch (NoninvertibleTransformException ex) {
    // should not get here
    ex.printStackTrace();
    return;
    tx.setToIdentity();
    tx.translate(p1.getX(), p1.getY());
    tx.scale(scale, scale);
    tx.translate(-p2.getX(), -p2.getY());
    tx.transform(p1, p2);
    ZoomDemo.this.revalidate();
    ZoomDemo.this.repaint();
    public void mouseWheelMoved(MouseWheelEvent e) {
    if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
    Point2D p1 = e.getPoint();
    Point2D p2 = null;
    try {
    p2 = tx.inverseTransform(p1, null);
    } catch (NoninvertibleTransformException ex) {
    // should not get here
    ex.printStackTrace();
    return;
    scale -= (0.1 * e.getWheelRotation());
    scale = Math.max(0.1, scale);
    tx.setToIdentity();
    tx.translate(p1.getX(), p1.getY());
    tx.scale(scale, scale);
    tx.translate(-p2.getX(), -p2.getY());
    ZoomDemo.this.revalidate();
    ZoomDemo.this.repaint();
            public void mouseClicked(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            public void mouseReleased(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            public void mouseEntered(MouseEvent e) {
               // throw new UnsupportedOperationException("Not supported yet.");
            public void mouseExited(MouseEvent e) {
               // throw new UnsupportedOperationException("Not supported yet.");
            public void mouseMoved(MouseEvent e) {
               // throw new UnsupportedOperationException("Not supported yet.");
    public static void main(String[] args) {
    //SwingUtilities.invokeLater(new ZoomDemo());
    int scrwidth = Toolkit.getDefaultToolkit().getScreenSize().width;
    int scrheight = Toolkit.getDefaultToolkit().getScreenSize().height;
    JFrame f = new JFrame("Zoom");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(scrwidth , scrheight);
    //JLayeredPane lp = new JLayeredPane();
    //f.add(lp);
    ZoomDemo zd = new ZoomDemo();
    zd.getBounds();
    f.add(zd);
    //int x = (int) zd.getX();
    //int y = (int) zd.getY();
    //int w = (int) zd.getWidth();
    //int h = (int) zd.getHeight();
    //System.out.println(x+" "+y+" "+w+" "+h);
    //zd.setBounds(x ,y ,w ,h );
    //lp.add(zd, JLayeredPane.DEFAULT_LAYER);
    //f.setLocationRelativeTo(null);
    f.setVisible(true);
    //lp.setVisible(true);
    //zd.setVisible(true);
    }Edited by: .mnemonic. on May 26, 2009 11:07 PM
    Edited by: .mnemonic. on May 27, 2009 11:00 AM

    You'll need a stable point in the component to track and orient to the scaling transform(s).
    From this you can construct whatever you need in the way of image location and size.
    Let's try a center&#8211;of&#8211;image tracking point:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class ZD extends JPanel {
        BufferedImage image;
        Point center;
        AffineTransform at = new AffineTransform();
        Point2D.Double origin = new Point2D.Double(0,0);
        public ZD(BufferedImage image) {
            this.image = image;
            center = new Point(image.getWidth()/2, image.getHeight()/2);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.drawRenderedImage(image, at);
            g2.setPaint(Color.red);
            g2.fill(new Ellipse2D.Double(origin.x-1.5, origin.y-1.5, 4, 4));
            g2.setPaint(Color.blue);
            g2.fill(new Ellipse2D.Double(center.x-1.5, center.y-1.5, 4, 4));
        private void setTransform(double scale) {
            // keep image centered over Point "center"
            double x = center.x - scale*image.getWidth()/2;
            double y = center.y - scale*image.getHeight()/2;
            origin.setLocation(x, y);
            at.setToTranslation(x, y);
            at.scale(scale, scale);
        public static void main(String[] args) throws java.io.IOException {
            java.net.URL url = ZD.class.getResource("images/hawk.jpg");
            BufferedImage image = javax.imageio.ImageIO.read(url);
            ZD test = new ZD(image);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.setSize(500,500);
            f.setLocation(100,100);
            f.setVisible(true);
            test.addMouseListener(test.mia);
            test.addMouseMotionListener(test.mia);
        /** MouseAdapter okay in j2se 1.6+ */
        private MouseInputAdapter mia = new MouseInputAdapter() {
            final double SCALE_INC = 0.05;
            final int SCALE_STEP = 20;
            double scale = 1.0;
            double lastStep;
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                center.setLocation(p);
                //System.out.printf("center = [%3d, %3d]%n", p.x, p.y);
                setTransform(scale);
                repaint();
            public void mouseDragged(MouseEvent e) {
                // scale up/down with relative vertical motion
                int step = (e.getY() - center.y)/SCALE_STEP;
                if(step != lastStep) {
                    scale += SCALE_INC*((step < lastStep) ? -1 : 1);
                    //System.out.printf("step = %3d  scale = %.3f%n", step, scale);
                    setTransform(scale);
                    lastStep = step;
                    repaint();
    }

  • How can I hide a JPanel?

    I have some JPanels and using the mouse motion listeners you can scribble on them. I want to be able to switch between these panels but the problem is the drawings get wiped off when I use repaint() and frame.add(panel).
    Any ideas how else I could try doing this?

    Ok thanks everyone. I've taken the MyPanel class from here http://java.sun.com/docs/books/tutorial/uiswing/painting/step3.html
    class MyPanel extends JPanel {
        private int squareX = 50;
        private int squareY = 50;
        private int squareW = 20;
        private int squareH = 20;
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
            addMouseMotionListener(new MouseAdapter() {
                public void mouseDragged(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
        private void moveSquare(int x, int y) {
            int OFFSET = 1;
            if ((squareX!=x) || (squareY!=y)) {
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
                squareX=x;
                squareY=y;
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
        public Dimension getPreferredSize() {
            return new Dimension(250,200);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);      
            g.drawString("This is my custom Panel!",10,20);
            g.setColor(Color.RED);
            g.fillRect(squareX,squareY,squareW,squareH);
            g.setColor(Color.BLACK);
            g.drawRect(squareX,squareY,squareW,squareH);
    }Now if I use this class to make two panels, how can I hide one and bring the other one up and vice versa, using two buttons? setVisible() still doesn't work properly.
    Here's the whole code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseMotionAdapter;
    public class PanelTest extends JFrame {
        private MyPanel panelOne;
        private MyPanel panelTwo;
        private BorderLayout layoutManager;
        private PanelTest() {
            layoutManager = new BorderLayout();
            this.setLayout(layoutManager);
            panelOne = new MyPanel();
            panelTwo = new MyPanel();
            panelOne.add(new JLabel("This is Panel One"));
            panelTwo.add(new JLabel("This is Panel Two"));
            setCurrentPanel(panelOne);
            JButton switchButton = new JButton("Switch");
            switchButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(getCurrentPanel() == panelOne) {
                        setCurrentPanel(panelTwo);
                    } else {
                        setCurrentPanel(panelOne);
            this.getContentPane().add(switchButton, BorderLayout.SOUTH);
            this.pack();
            this.setVisible(true);
        private void setCurrentPanel(MyPanel panel) {
            this.getContentPane().add(panel, BorderLayout.CENTER);
            panel.revalidate();
            panel.repaint();
        private JPanel getCurrentPanel() {
            return (JPanel)layoutManager.getLayoutComponent(BorderLayout.CENTER);
        public static void main(String[] args) {
            new PanelTest();
    class MyPanel extends JPanel {
        private int squareX = 50;
        private int squareY = 50;
        private int squareW = 20;
        private int squareH = 20;
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
            addMouseMotionListener(new MouseAdapter() {
                public void mouseDragged(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
        private void moveSquare(int x, int y) {
            int OFFSET = 1;
            if ((squareX!=x) || (squareY!=y)) {
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
                squareX=x;
                squareY=y;
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
        public Dimension getPreferredSize() {
            return new Dimension(250,200);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);      
            g.setColor(Color.RED);
            g.fillRect(squareX,squareY,squareW,squareH);
            g.setColor(Color.BLACK);
            g.drawRect(squareX,squareY,squareW,squareH);
    }Edited by: atom.bomb on Mar 30, 2010 11:25 AM

  • How to highlight Icon with mouse click ?

    This program will open up a JFileChooser, Select one or more than one images from your computer. It will display them as Icons.
    I am trying to highlight any icon with mouseclick from the program below but I am not able to do it. Please help. Thanks in advance.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.border.Border;
    public class IconIllustrate extends JFrame implements ActionListener, MouseListener
    JLabel[] lblimage = new JLabel[10];
    JPanel panAttachment = new JPanel();
    JPanel panButton = new JPanel();
    JButton bAdd = new JButton("Add");
    Component comp = null;
    Component c = null;
    boolean bolVal = false;
    public IconIllustrate()
    // TODO Auto-generated constructor stub
    panButton.add(bAdd);
    bAdd.addActionListener(this);
    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(panAttachment, BorderLayout.CENTER);
    this.getContentPane().add(panButton, BorderLayout.SOUTH);
    * @param args
    public static void main(String[] s)
    // TODO Auto-generated method stub
    IconIllustrate ii = new IconIllustrate();
    ii.setLocation(300, 200);
    ii.setTitle("Testing Highlight Icon");
    ii.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ii.setSize(400, 300);
    ii.setVisible(true);
    public void actionPerformed(ActionEvent ae)
    // TODO Auto-generated method stub
    if(ae.getSource().equals(bAdd))
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(true);
    int answer = chooser.showOpenDialog(this);
    File[] file = null;
    String[] fileName = new String[10];
    if(answer == JFileChooser.OPEN_DIALOG)
    file = chooser.getSelectedFiles();
    ImageIcon icon;
    try
    for(int i = 0; i < file.length; i++)
    icon = new ImageIcon(file.toString());
    ImageIcon thumbnailIcon = new ImageIcon(getScaledImage(icon.getImage(), 50, 40));
    lblimage = new JLabel[10];
    lblimage[i] = new JLabel();
    lblimage[i].addMouseListener(this);
    lblimage[i].setName("" + i);
    lblimage[i].setBorder(BorderFactory.createEmptyBorder());
    lblimage[i].setVerticalTextPosition(JLabel.BOTTOM);
    lblimage[i].setHorizontalTextPosition(JLabel.CENTER);
    lblimage[i].setHorizontalAlignment(JLabel.CENTER);
    lblimage[i].setIcon(thumbnailIcon);
    panAttachment.add(lblimage[i]);
    panAttachment.revalidate();
    catch(Exception ex )
    ex.printStackTrace();
    private Image getScaledImage(Image srcImg, int w, int h)
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();
    return resizedImg;
    public void mouseClicked(MouseEvent me)
    // TODO Auto-generated method stub
    int clickCount = me.getClickCount();
    if(clickCount == 1 || clickCount == 2)
    Component comp = me.getComponent();
    Component c = comp.getComponentAt(me.getX(), me.getY());
    // c.setPreferredSize(new Dimension(100, 100));
    c.setBackground(Color.CYAN);
    System.out.println("clickCount");
    repaint();
    this.panAttachment.revalidate();
    public void mouseEntered(MouseEvent arg0)
    // TODO Auto-generated method stub
    public void mouseExited(MouseEvent arg0)
    // TODO Auto-generated method stub
    public void mousePressed(MouseEvent arg0)
    // TODO Auto-generated method stub
    public void mouseReleased(MouseEvent arg0)
    // TODO Auto-generated method stub

    Hi,
    phungho2000 wrote:
    Thank you for the Code. Now I am able to set the label border. I need to figure out how keep track of the last selected component so that I can reset the border.**g**
    No, you have still fundamental misunderstood how listeners are working. You add a listener to a component. From this time on, this listener is watching this component. It listens if something occurs with this component therefor it is competent. If so, then it will pay attention to this. So the listener always knows the components it is in charge of. There is no need for you to "keep track of the last selected component" because the listener is doing this for you already.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.GridLayout;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.*;
    public class FocusTesting extends JFrame implements FocusListener, MouseListener
      // There is no need for JLabel fields here.
      //JLabel labelA = new JLabel("Label A");
      //JLabel labelB = new JLabel("Label B");
      public FocusTesting()
        super("FocusTesting");
        JPanel paneFirst = new JPanel();
        JPanel paneSecond = new JPanel();
        paneSecond.setBackground(Color.gray);
        //use simply FlowLayout for testing this
        //paneFirst.setLayout(new BorderLayout());
        paneFirst.setBorder(BorderFactory.createBevelBorder(2));
        // pane.setBackground(Color.blue);
        JLabel labelA = new JLabel("Label A");
        // give the labelA a name only to show you, that the listener knows about the compontent it ist added to
        labelA.setName(labelA.getText());
        labelA.addMouseListener(this);
        labelA.addFocusListener(this);
        labelA.setFocusable(true);
        JLabel labelB = new JLabel("Label B");
        // give the labelB a name only to show you, that the listener knows about the compontent it ist added to
        labelB.setName(labelB.getText());
        labelB.addMouseListener(this);
        labelB.addFocusListener(this);
        labelB.setFocusable(true);
        paneFirst.add(labelA);
        paneFirst.add(labelB);
        this.getContentPane().setLayout(new GridLayout(2, 1));
        this.getContentPane().add(paneFirst);
        this.getContentPane().add(paneSecond);
      public static void main(String[] s)
        //separate the initial thread form the event dispatch thread
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            FocusTesting ft = new FocusTesting();
            ft.setLocation(300, 200);
            ft.setSize(300, 200);
            ft.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ft.setVisible(true);
      public void focusGained(FocusEvent fe)
        // TODO Auto-generated method stub
        JComponent jcomp = (JComponent)fe.getComponent();
        jcomp.setBorder(BorderFactory.createLineBorder(Color.GREEN, 5));
        System.out.println("focusGained " + jcomp.getName());
      public void focusLost(FocusEvent fe) 
        // TODO Auto-generated method stub
        JComponent jcomp = (JComponent)fe.getComponent();
        jcomp.setBorder(BorderFactory.createEmptyBorder());
        System.out.println("focusLost " + jcomp.getName());
      public void mouseClicked(MouseEvent me)
        Component comp = me.getComponent();
        comp.requestFocusInWindow();
        System.out.println("mouseClicked " + comp.getName());
      public void mouseEntered(MouseEvent arg0)
        // TODO Auto-generated method stub
      public void mouseExited(MouseEvent arg0)
        // TODO Auto-generated method stub
      public void mousePressed(MouseEvent arg0)
        // TODO Auto-generated method stub
      public void mouseReleased(MouseEvent arg0)
        // TODO Auto-generated method stub
    } You also should read again the Java Tutorial about Concurrency in Swing. Especially why and how to separate the initial thread form the event dispatch thread. [http://java.sun.com/docs/books/tutorial/uiswing/concurrency/initial.html]
    Also have a look on [http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html], especially [http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html#focusable] for why use the MouseListener too.
    And if you have understood that all, then you may think about in what way it would be much easier to use JButton's instead of JLabel's for your clickable and focusable thumbnails.
    best regards
    Axel

  • Repaint() in JPanel doesn't align correctly

    Hey all,
    I'm running into this problem with a program I'm writing for work. It's basically a dispatch board which connects to our SQL server via ODBC. When the user presses a "Next" or "Prev" button, the dates will change and show the dispatching for the next or previous week respectively. However, the refreshed components go where they are supposed to, but the old screen is underneath, and shifted slightly so that nothing aligns. In turn, you can make heads or tails as to what's happening. However, if you select File -> Refresh from my menubar (calls repaint() the same way) everything is repainted correctly. Any ideas?
    package dispatchBoard.DispatchBoard;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.sql.*;
    import javax.swing.JPanel;
    import sun.misc.Queue;
    public class DB_MainWindow extends JPanel implements MouseListener{
         private static final long serialVersionUID = 1L;
         private int _xRes, _yRes;
         private int _techs;
         private String _dayOption, _monday, _tuesday, _wednesday, _thursday, _friday, _odbcName, _databaseName, _currYear;
         private String[] _months;
         private Tech _myTechList;
         private Font _defaultFont;
         DB_Frame _mainFrame;
         private Calendar cal = new GregorianCalendar();
         public DB_MainWindow(String _resolution, String optionString, String ofTechs, DB_Frame frame, String _odbc, String _database, String _year)
              _xRes = Integer.valueOf(_resolution.substring(0, findCharPosition(_resolution, 'x'))).intValue() - 5;
              _yRes = Integer.valueOf(_resolution.substring(findCharPosition(_resolution, 'x')+1)).intValue() - 30;
              _techs = Integer.valueOf(ofTechs).intValue();
              _dayOption = optionString;
              _mainFrame = frame;
              _odbcName = _odbc;
              _databaseName = _database;
              _currYear = _year;
              setDaysFiveStraight();
              System.out.println(_xRes + " " + _yRes);
              this.setBackground(Color.GRAY);
              this.setPreferredSize(new Dimension(_xRes,_yRes));
              this.addMouseListener(this);
         public void paint(Graphics g)
              _myTechList = null;
              int _spacing = 0;
              int _spacing2 = 0;
              g.setColor(Color.BLACK);
              g.drawLine(60,0,60,_yRes);
              _defaultFont =g.getFont();
              //draw tech barriers
              for (int i = 1; i < _techs+1; i ++)
                   _spacing = _yRes / (_techs+1);
                   g.drawLine(0, _spacing*i, 1366, _spacing*i);
              //draw day barriers
              for (int j = 1; j < 5; j++)
                   _spacing2 = (_xRes-60) / 5;
                   g.drawLine(_spacing2*j + 60, 0, _spacing2*j + 60, 768);
              int _curPos = 60, _timePos = 0;
              int _time[] = {8,9,10,11,12,1,2,3,4,5};
              for (int k = 0; k < 5; k++)
                   _curPos = 60+(k*_spacing2);
                   for (int l = 0; l < 9; l++)
                        g.drawLine( _curPos + (l*(_spacing2/9)), 0+_spacing, _curPos + (l*(_spacing2/9)), _yRes);
                        String _tempString = ""+_time[_timePos];
                        g.drawString(_tempString, _curPos + (l*(_spacing2/9)), _spacing);
                        _timePos++;
                   _timePos = 0;
              //draw graph labels
              System.out.println(_dayOption);
              g.drawString("TECHS", 10, _spacing);
              g.drawString("Monday "+_monday, 60+(_spacing2/2) - 23, _spacing/2);
              g.drawString("Tuesday "+_tuesday, 60+_spacing2+(_spacing2/2) - 26, _spacing/2);
              g.drawString("Wednesday "+_wednesday, 60+2*_spacing2+(_spacing2/2) - 33, _spacing/2);
              g.drawString("Thursday "+_thursday, 60+3*_spacing2+(_spacing2/2) - 28, _spacing/2);
              g.drawString("Friday "+_friday, 60+4*_spacing2+(_spacing2/2) - 25, _spacing/2);
               * At this point the default grid, including all labels, have been drawn on
               * the dispatch board.  Now, we have to fetch the data from the SQL server,
               * place it into some sort of form (possibly 2d array?!) and then print it out
               * on the board....
               * Here goes!
    //          this.addMouseMotionListener(this);
    //          g.drawRect(_mousePosition.x, _mousePosition.y, 10, 10);
              fillInTimes(g, _spacing, _spacing2);
         public void setDaysFiveStraight()
              if (_dayOption.equals(new String("work_week")))
                   _monday = new String("");
                   _tuesday = new String("");
                   _wednesday = new String("");
                   _thursday = new String("");
                   _friday = new String("");
                   String[] _months2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
                   _months = _months2;
                    * Sunday = 1
                    * Monday = 2
                   System.out.println("DAY OF THE WEEK = "+cal.get(Calendar.DAY_OF_WEEK));
                   if (cal.get(Calendar.DAY_OF_WEEK) == 2)
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 3)
                   {     //tuesday
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        System.out.println("TUESDAY = "+_tuesday);
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 4)
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        //System.out.println("TUESDAY = "+_tuesday);
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 5)
                   {     //thursday
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 6)
                   {     //friday
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
         private void fillInTimes(Graphics g, int _spacing, int _spacing2) {
              // need to get the data first, building pre-defined array for test data...
              //****START REAL DATA LOAD****\\
    //          Calendar cal = new GregorianCalendar();
             try {
                 // Load the JDBC-ODBC bridge
                 Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
                 // specify the ODBC data source's URL
                 String url = "jdbc:odbc:"+_odbcName;
                 // connect
                 Connection con = DriverManager.getConnection(url,"sa",_currYear);
                 // create and execute a SELECT
                 Statement stmt = con.createStatement();
                 Statement stmt2 = con.createStatement();
                 ResultSet techList = stmt2.executeQuery("USE "+_databaseName+" SELECT Distinct(SV00301.Technician) from SV00301 join SV00115 on SV00301.Technician = SV00115.Technician where SV00115.SV_Inactive<>1");
                 // traverse through results
                 Tech temp;
                 int counter = 0;
                 while(techList.next())
                      if (_myTechList == null)
                           _myTechList = new Tech(techList.getString(1).trim());
                           System.out.println(_myTechList.getName());
                           counter++;
                      else if (!_myTechList.hasNext())
                           _myTechList.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(_myTechList.getNext().getName());
                           counter++;
                      else
                           temp = _myTechList.getNext();
                           while(temp.hasNext())
                                temp = temp.getNext();
                           temp.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(temp.getNext().getName());
                           counter++;
    //             printTechList();
                 String nextMonth, prevMonth;
                 if(cal.get(Calendar.MONTH)==11)
                      nextMonth=_months[0];
                 else
                      nextMonth = _months[cal.get(Calendar.MONTH)+1];
                 if(cal.get(Calendar.MONTH) == 0)
                      prevMonth = _months[11];
                 else
                      prevMonth = _months[cal.get(Calendar.MONTH)-1];
                 ResultSet rs = stmt.executeQuery
                 ("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00301.Task_Date)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00301.Task_Date)="+prevMonth+" or Month(SV00301.Task_Date)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                 System.out.println("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00300.Date_of_Service_Call)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00300.Date_of_Service_Call)="+prevMonth+" or Month(SV00300.Date_of_Service_Call)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                  while (rs.next()) {
                      // get current row values
                       String servicecallid = rs.getString(1).trim(),
                               tech = rs.getString(4).trim(),
                               rawDate = rs.getString(6).trim(),
                               startTime = rs.getString(7).trim(),
                               _length = rs.getString(9).trim(),
                               description = rs.getString(33).trim(),
                               customernumber = rs.getString(35).trim(),
                               custname = rs.getString(45).trim(),
                               location = rs.getString(46).trim(),
                               calltype = rs.getString(54).trim(),
                               notes = rs.getString(268).trim();   
    //                  String formattedDate = month+"/"+day+"/"+year;
    //                  System.out.println(formattedDate);
    //                  String tech = rs.getString(142).trim();
    //                  String rawDate = rs.getString(144);
                      System.out.println(rawDate);
                      String day = rawDate.substring(8,10);
                      String month = rawDate.substring(5,7);
                      String year = rawDate.substring(0,4);
                      formatNumber(day);
                      formatNumber(month);
    //                  startTime = rs.getString(145);
    //                  String _length = rs.getString(147);
                      int hour = Integer.valueOf(startTime.substring(11,13)).intValue();
                      String minute = startTime.substring(14,16);
                      int minutes = Integer.valueOf(minute).intValue();
                      minutes = minutes / 60;
                      double length = (Integer.valueOf(_length).intValue())/100;
                      // print values
                      //System.out.println ("Service_Call_ID = " + Surname);
                      if (hour!=0)
                           sortJob(new Job(servicecallid, custname, new MyDate(month,day,year), hour+minutes,length, description, customernumber, location, calltype, notes), _myTechList, tech);
                  // close statement and connection
                  stmt.close();
                  con.close();
                  catch (java.lang.Exception ex) {
                      ex.printStackTrace();
              //draw techs and blocks of jobs!!!!!
              //***TECHS***\\
             Tech _tempTech = new Tech("DOOKIE");
              int multiplier = 2;
              if (_myTechList.hasNext())
                   g.setColor(Color.BLACK);
                   _tempTech = _myTechList.getNext();
                   g.drawString(_myTechList.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_myTechList.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_myTechList,multiplier, _spacing,_spacing2);
                   multiplier++;
              while(_tempTech.hasNext())
                   g.setColor(Color.BLACK);
                   g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
                   multiplier++;
                   _tempTech = _tempTech.getNext();
              g.setColor(Color.BLACK);
              g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
              System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
              printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
              //***TIME BLOCKS***\\\
         private void printTechList() {
              // TODO Auto-generated method stub
              boolean temp = !_myTechList.hasNext();
              Tech tempTech = _myTechList;
              System.out.println("BEGINNING TECH LIST PRINTOUT!!!!");
              while (tempTech.hasNext() || temp)
                   System.out.println(tempTech.getName());
                   if (temp)
                        temp = !temp;
                   else
                        tempTech = tempTech.getNext();
              System.out.println(tempTech.getName());
              System.out.println("END TECH LIST PRINTOUT!!!");
         private void formatNumber(String month) {
              // TODO Auto-generated method stub
              if (month.equals(new String("01")))
                   month = new String("1");
              else if (month.equals(new String("02")))
                   month = new String("2");
              else if (month.equals(new String("03")))
                   month = new String("3");
              else if (month.equals(new String("04")))
                   month = new String("4");
              else if (month.equals(new String("05")))
                   month = new String("5");
              else if (month.equals(new String("06")))
                   month = new String("6");
              else if (month.equals(new String("07")))
                   month = new String("7");
              else if (month.equals(new String("08")))
                   month = new String("8");
              else if (month.equals(new String("09")))
                   month = new String("9");
         private void printJobs(Graphics g, Tech techList, int multiplier, int _spacing, int _spacing2) {
              Job tempJob = techList.getJobs();
              boolean temp = false;
              if (tempJob != null)
              {     temp = !tempJob.hasNext();
              while (tempJob.hasNext() || temp)
                   g.setColor(Color.RED);
                   String _tempDate = new String(tempJob.getDate().toString());
    //               System.out.println("This job has date of: "+_tempDate);
                   int horizontalMultiplier = 0;
                   if (_tempDate.equals(_monday))
                        horizontalMultiplier = 0;
                   else if (_tempDate.equals(_tuesday))
                        horizontalMultiplier = 1;
                   else if (_tempDate.equals(_wednesday))
                        horizontalMultiplier = 2;
                   else if (_tempDate.equals(_thursday))
                        horizontalMultiplier = 3;
                   else if (_tempDate.equals(_friday))
                        horizontalMultiplier = 4;
                   else
                        horizontalMultiplier = 5;
    //               System.out.println("HorizontalMultiplier = "+horizontalMultiplier);
                   if (horizontalMultiplier !=5)
                        if (tempJob.getJobCallType().equals(new String("TM"))) g.setColor(new Color(0,255,0));
                        else if (tempJob.getJobCallType().equals(new String("SU"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("SPD"))) g.setColor(new Color(44,148,67));
                        else if (tempJob.getJobCallType().equals(new String("QUO"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("MCC"))) g.setColor(new Color(255,0,255));
                        else if (tempJob.getJobCallType().equals(new String("MC"))) g.setColor(new Color(128,0,255));
                        else if (tempJob.getJobCallType().equals(new String("CBS"))) g.setColor(new Color(0,0,255));
                        else if (tempJob.getJobCallType().equals(new String("AS"))) g.setColor(new Color(255,255,255));
                        else g.setColor(Color.red);
                        g.fillRect(/*START X*/(int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1),/*START Y*/_spacing*(multiplier-1)+1,/*LENGTH*/(int)(tempJob.getJobLength()*(_spacing2/9)-1),/*WIDTH*/_spacing-1);
                        System.out.println("g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        g.setColor(Color.BLACK);
                        g.setFont(new Font("Monofonto", Font.PLAIN, 22));
                        if ((int)(tempJob.getJobLength()*(_spacing2/9)-1) >0)
                             g.drawString(formatStringLength(tempJob.getJobName().toUpperCase(), tempJob.getJobLength()), (int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1), (_spacing*(multiplier)+1)-_spacing/2+5);
                        g.setFont(_defaultFont);
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
                   else
                        System.out.println("*g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
         //     g.fillRect((int)(60+(tempJob.getStarTime()-8)*(_spacing2/9)+1),_spacing*(multiplier-1)+1,(int)(tempJob.getJobLength()*(_spacing2/9)-1),_spacing-1);
         private String formatStringLength(String string, double jobLength) {
              // TODO Auto-generated method stub
              if (jobLength*3>string.length())
                   return string;
              return string.substring(0, new Double(jobLength*3).intValue());
         private void sortJob(Job job, Tech techList, String techName) {
              Tech _tempTech2;
              if (techName.equals(techList.getName()))
                   techList.insertJob(job);
                   System.out.println("ADDED " + job.getJobName() +" TO " + techName);
              else
                   _tempTech2 = techList.getNext();
                   while (!_tempTech2.getName().equals(techName) && _tempTech2.hasNext())
                        _tempTech2 = _tempTech2.getNext();
    //                    System.out.println(_tempTech2.getName()+" vs. " + techName);
                   if (_tempTech2.getName().equals(techName))
                        _tempTech2.insertJob(job);
                        System.out.println("ADDED " + job.getJobName() +" TO " + techName);
                   else
                        System.out.println("TECH NAME: "+_tempTech2.getName()+" NOT FOUND :: COULD NOT INSERT JOB");
         private int findCharPosition(String _resolution2, char c) {
              // TODO Auto-generated method stub
              for (int i = 0; i < _resolution2.length(); i++)
                   if (_resolution2.charAt(i) == c)
                        return i;
              return 0;
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
              System.out.println("Mouse clicked at coordinates: "+arg0.getX()+", "+arg0.getY()+"\nAttempting to intelligently find the job number");
               * Find the tech
              int techNum = arg0.getY()/(_yRes / (_techs+1));
              String techName= new String("");
              int counter = 0;
              Tech temp = _myTechList;
              boolean found = true;
              while(temp.hasNext() && found)
                   counter++;
                   if (counter == techNum)
                        techName = temp.getName();
                        found = false;
                   else
                        temp = temp.getNext();
              System.out.println("The "+techNum+"th tech was selected... which means you clicked "+techName);
               * Find the day
              int day = (arg0.getX()-60)/(0 + ((_xRes-60)/5));
              String days[] = {_monday, _tuesday, _wednesday, _thursday, _friday};
              System.out.println("The day you chose was "+days[day]);
               * Find the time
              int blocksIn = ((arg0.getX()-60)/(((_xRes-60)/5)/9))%9;
              System.out.println(blocksIn+" blocks inward!!!!");
               * Find the job
               *           - temp is already initialized to the current tech!!
              System.out.println(temp.getName()+" has "+temp.getNumberOfJobs()+" jobs");
              Job current = temp.getJobs();
              Queue jobQueue = new Queue();
              boolean first = true;
              while(current.hasNext() || first)
                   if(current.getDate().toString().equals(days[day]))
                        jobQueue.enqueue(current);
                        System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
                   else
                        System.out.println("Did not queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
              if(current.getDate().toString().equals(days[day]))
                   jobQueue.enqueue(current);
                   System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              else
                   System.out.println("Did not queue the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              blocksIn+=8;
              while(!jobQueue.isEmpty())
                   try {
                         * Get a job off the queue... now check the times
                        Job dqJob = (Job)jobQueue.dequeue();
                        System.out.println(dqJob.getStarTime()+"<="+blocksIn +" && "+(dqJob.getStarTime()+dqJob.getJobLength()-1)+">="+blocksIn+" :: "+dqJob.getJobName());
                        if (dqJob.getStarTime()<=blocksIn && dqJob.getStarTime()+dqJob.getJobLength()-1>=blocksIn)
                             System.out.println("MONEY!!!! Found job: "+dqJob.getJobName());
                             new JobDisplayer(dqJob, _xRes, _yRes);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void nextDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+7);
                   setDaysFiveStraight();
              this.repaint();
         public void prevDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-7);
                   setDaysFiveStraight();
                   this.repaint();
              this.repaint();
    }Sorry for the huge chunk of code.
    Thanks in advance,
    Jeff

    Sorry for the huge chunk of code.
    Mm, yes, I'm far too lazy to read all that.
    But you should be overriding paintComponent(), not paint().
    http://www.google.co.uk/search?hl=en&q=java+swing+painting&btnG=Google+Search&meta=
    I've not bothered to work out from that pile of magic numbers exactly what you're tring to draw but is it not something that JTable would happily do?

  • Need help with  HTML and Swing Components

    Dear All,
    I am using HTML text for Jbutton and Jlabel and MenuItem.
    But when i am trying to disable any of these, its foreground color is not being grayed out.
    For that, I have overrided the setEnable() method as mentioned below:
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.*;
    import javax.swing.plaf.FontUIResource;
    * HtmlLabelEx.java
    public class HtmlLabelEx extends javax.swing.JDialog implements MouseListener{
         * Creates new form HtmlLabelEx
        public HtmlLabelEx(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            initComponents();
            setLayout(null);
            this.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent event)
                    System.exit(0);
            JLabel jLabel1 = new JLabel()
                public void setEnabled(boolean b)
                  super.setEnabled(b);
                  setForeground(b ? (Color) UIManager.get("Label.foreground") : (Color) UIManager.get("Label.disabledForeground"));
            JButton jButton1 = new JButton()
                public void setEnabled(boolean b)
                  super.setEnabled(b);
                  setForeground(b ? (Color) UIManager.get("Label.foreground") : (Color) UIManager.get("Label.disabledForeground"));
            add(jButton1);
            String str = "<html><body><b>Label</b></body></html>";
            System.out.println("str = "+str);
        jLabel1.setText(str);
        add(jLabel1);
        jLabel1.setBounds(10,10,100,20);
        jLabel1.setEnabled(false);
        jButton1.setText("<html><body><b>Button</b></body></html>");
        jButton1.setEnabled(true);
        jButton1.setBounds(10,50,100,20);
        System.out.println("getText = "+jLabel1.getText());
        setSize(400,400);
        addMouseListener(this);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            getContentPane().setLayout(null);
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HtmlLabelEx(new javax.swing.JFrame(), true).setVisible(true);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
        public void mouseClicked(MouseEvent e)
            if(e.getButton() == e.BUTTON3)
                JMenuItem mit = new JMenuItem("<html><body><b>Menu Item</b></body></html>");
                JPopupMenu pop = new JPopupMenu();
                pop.add(mit);
                mit.setEnabled(false);
                pop.show(this,e.getX(),e.getY());
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
    But, I think it is difficult to write like this for each component.
    I am looking for an optimized solution so that the change will be only in one place.
    so that, It wont leads to change so many pages or so many places.
    And i have the following assumptions to do this. please let me know the possibility.
    1.Implementing custom UI class, extending the JButton/JMenuItem (As the BasicButton/MenuItemUI class does not have setEnabled() method to override) and putting this in UIManager.put("ButtonUI/MenuItemUI","CustomClass).
    2.If there is any possibility to achieve this, by just overriting any key in the UIManager
    3.By setting any client property globally.
    My requirement is to do this only at one place for entire the application.So, that we need not change all the buttoins, sya some 30 buttions are there in a dialog, then we need to override each button class.
    Please suggest me the possibilties..
    Thank you

    Hi camickr ,
    I know that to set the font we have to use component.setfont().
    But, as per my requirement,i am not setting any font to any component in my application.
    i am just passing HTML text along with FONT tags to all the components in my Application.SO, in this case we will get bold letters and that problem fixed when we set swing.boldMetal = false in UI Manager.
    But actual problem irrespective of font settings is when ever we use HTML rendered text, when the button or menuitem is disabled,then that one will not be changed to gray color. i.e., it still looks like normal controls, even it is disabled.(It is also reported as bug)
    But, as per my knowledge we can fix by overrding setEnabled or paint() methods for each and every component.
    But, if we do like that, for an application that has 200 buttons or MenuItems, it is difficult to follow that approach.
    So, We should find a way to achieve that only in one place like using UIManager or other one as i mentioned in previous posts if possible.
    I hope you understood what my problem is exactly.
    Thank You
    Edited by: sindhumourya on Mar 4, 2010 7:26 AM

  • How to display a frame at the upper left corner of each screen?

    hi,
    below are 2 ways to display a frame at the upper left corner of each screen (i have 2 monitors).
    both work but the 2nd way is much slower. which, if any, of the 2 approaches is "more" correct?
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.DisplayMode;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.GraphicsConfiguration;
    import java.awt.GraphicsDevice;
    import java.awt.GraphicsEnvironment;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    // the thing that matters in here is setting the frame's location: xCoord
    // is incremented in each iteration by the current screen's width and
    // is used to set the frame's x-coordinate.
    public static void main(String args[])
          GraphicsEnvironment gEnviron = GraphicsEnvironment.getLocalGraphicsEnvironment();
          GraphicsDevice[]    gDevices = gEnviron.getScreenDevices();
          Color colors[] = {Color.blue, Color.red};
          for(int i = 0, xCoord = 0; i < gDevices.length; i++)
             // set panel's size and frame's size to take up the whole screen
             DisplayMode didsplayMode = gDevices.getDisplayMode();
    int screenWidth = didsplayMode.getWidth();
    int screenHeight = didsplayMode.getHeight();
    JPanel panel = new JPanel();
    panel.setBackground(colors[i % colors.length]);
    JFrame frame = new JFrame();
    frame.setSize(new Dimension(screenWidth, screenHeight));
    frame.setContentPane(panel);
    frame.setUndecorated(true);
    // set location of frame.
    frame.setLocation(xCoord, 0);
    xCoord += screenWidth;
    frame.addMouseListener
    new MouseAdapter()
    public void mousePressed(MouseEvent event) {System.exit(1);}
    frame.setVisible(true);
    // this is a lot slower and may not be correct: it sets the frame's location by calling
    // getConfigurations() on each screen device but using only the 1st configuration
    // (it returns 6 on my computer) to get the bounds (for the frame's x-coord).
    // a screen device has 1 or more configuration objects but do all the objects
    // of the device report the same bounds? if the anwser is yes, then the code
    // is correct, but i'm not sure.
    public static void main1(String args[])
    GraphicsEnvironment gEnviron = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gDevices = gEnviron.getScreenDevices();
    Color colors[] = {Color.blue, Color.red};
    for(int i = 0; i < gDevices.length; i++)
    // set panel's size and frame's size to take up the whole screen
    DisplayMode didsplayMode = gDevices[i].getDisplayMode();
    int screenWidth = didsplayMode.getWidth();
    int screenHeight = didsplayMode.getHeight();
    JPanel panel = new JPanel();
    panel.setBackground(colors[i % colors.length]);
    JFrame frame = new JFrame();
    frame.setSize(new Dimension(screenWidth, screenHeight));
    frame.setContentPane(panel);
    frame.setUndecorated(true);
    // set location of frame: getConfigurations() is very time consuming
    GraphicsConfiguration[] gConfig = gDevices[i].getConfigurations();
    // on my computer: gConfig.length == 6. using the 1st from each set of configs
    Rectangle gConfigBounds = gConfig[0].getBounds();
    frame.setLocation(gConfigBounds.x, gConfigBounds.y);
    frame.addMouseListener
    new MouseAdapter()
    public void mousePressed(MouseEvent event) {System.exit(1);}
    frame.setVisible(true);
    thank you.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Darryl.Burke wrote:
    Blocked one abusive post.
    @flounder
    Please watch your language.
    dbDude - I just looked at your profile. WTF are you doing in India??

Maybe you are looking for

  • Trying to understand Transferable

    Hello, I'm trying to write a drag-and-drop file uploading applet and am thus trying to understand the Transferable interface. I found some very clear source but no clear explanation of one point. I'm sure this information is commonly available; I apo

  • Publish more than one operation by WebService

    Hi all Somebody can helpme saying me how to do the following with eGate ( i cant use eInsight ): For now im enabled to publish one operation and one webservice, but mi problem is that i can't publish one WebService with more than one operation and i

  • Foreign language attachment titles messed up

    I often get files with Japanese titles attached to emails. In Mail on both my 4-year-old iMac and 1-year-old MBP, both running 10.8.2, these titles often get all goofy-charactered. Funny thing is, if I go to view my iCloud mail in Safari, the titles

  • EDirectory SSL certificates for Apache2

    Hi, Need some direction. What is the easiest way to use eDirectory Certificates for Apache2 on OES2SP2/SLES10SP3. Currently the default site uses it but I have no idea where the *.conf files are located for the web site https://default-server.com/wel

  • Middleware Replication-ISU Installation Facts into CRM Service Contract

    Hi All, I would like to share an update which I have followed for one of my implementation project. Following document will help you, if you want to replicate some of the data from ISU to CRM Service contract custom fields, which is not the standard