Results 1 to 8 of 8
  1. #1
    ted1a is offline Member
    Join Date
    Jan 2014
    Posts
    4
    Rep Power
    0

    Default New to Java, and really stuck

    I've been working with Java for a couple months now. However, I'm pretty stuck. I was working on adding a selector on the screen. Searching for code, I found something that some created better than I ever could. I'm trying to integrate it into my code.

    I have a program that is pretty MVC.

    I'm in my controller class and I'm calling this code:
    java - Drawing a bounding rectangle to select what area to record - Stack Overflow

    I've changed it to a runnable and called a wait after I called this class, but it still continues on to the next line.

    I'm thinking I'll have to either create a super controller (one that manages two controllers and have a multiple set of views and models) because I'll have multiple views or I'll have to figure out how to wait for it to finish as a thread. As mentioned above, wait() doesn't work.

    This is the code in my controller after I changed it back from a Runnable:
    SelectionRectangle m_rect = new SelectionRectangle();
    //Thread m_thread = new Thread(m_rect);
    //m_thread.start();


    TopLeft = m_rect.getTopLeft();
    BottomRight = m_rect.getBottomRight();
    _view.setText(TopLeft.toString());


    Any suggestions?

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: New to Java, and really stuck

    Any suggestions?
    Post a SSCCE that shows the problem.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    ted1a is offline Member
    Join Date
    Jan 2014
    Posts
    4
    Rep Power
    0

    Default Re: New to Java, and really stuck

    I don't know how else to explain it, so I'm going to post the code I'm using. I hope that helps.

    This is the button click on my controller:
    Java Code:
    	public class CustomCaptureMouseClicks implements ActionListener 
    	{
    
    		MainView _view;
    		
    		CustomCaptureMouseClicks(MainView view)
    		{
    			_view = view;
    			
    		}
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			// TODO Auto-generated method stub
    			if (e.getActionCommand() == null)
    				return;
    			
    
    			
    			SelectionRectangle m_rect = new SelectionRectangle();
    			//Thread m_thread = new Thread(m_rect);
    			//m_thread.start();
    
    
    			TopLeft = m_rect.getTopLeft();
    			BottomRight = m_rect.getBottomRight();
    			_view.setText(TopLeft.toString());
    			
    			
    		}
    		
    	}
    This is the modified SelectionRectangle:
    Java Code:
    package com.main;
    
    import javax.swing.*;
    
    import java.awt.*;
    import java.util.logging.*;
    import java.awt.event.*;
    import java.awt.image.*;
    
    import javax.swing.border.EmptyBorder;
    
    public class SelectionRectangle {
    
    	private BackgroundPane m_bg = new BackgroundPane();
        public SelectionRectangle() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    //m_bg
                    JFrame frame = new JFrame("Test");
                    frame.setUndecorated(true);
                    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(m_bg);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);	
    
                }
    
            });
    
        }
        
        public Boolean getisComplete()
        {
        	return m_bg.getIsComplete();
        }
        
        public Point getTopLeft()
        {
        	return m_bg.getTopLeft();
        }
        
        public Point getBottomRight()
        {
        	return m_bg.getBottomRight();
        }
    
        public class BackgroundPane extends JPanel {
    
            private BufferedImage background;
            private Point mouseAnchor;
            private Point dragPoint;
    
            private SelectionPane selectionPane;
    
            public BackgroundPane() {
                selectionPane = new SelectionPane();
                try {
                    Robot bot = new Robot();
                    background = bot.createScreenCapture(getScreenViewableBounds());
                } catch (AWTException ex) {
                    Logger.getLogger(SelectionRectangle.class.getName()).log(Level.SEVERE, null, ex);
                }
    
                selectionPane = new SelectionPane();
                setLayout(null);
                add(selectionPane);
    
                MouseAdapter adapter = new MouseAdapter() {
                    @Override
                    public void mousePressed(MouseEvent e) {
                        mouseAnchor = e.getPoint();
                        dragPoint = null;
                        selectionPane.setLocation(mouseAnchor);
                        selectionPane.setSize(0, 0);
                    }
    
                    @Override
                    public void mouseDragged(MouseEvent e) {
                        dragPoint = e.getPoint();
                        int width = dragPoint.x - mouseAnchor.x;
                        int height = dragPoint.y - mouseAnchor.y;
    
                        int x = mouseAnchor.x;
                        int y = mouseAnchor.y;
    
                        if (width < 0) {
                            x = dragPoint.x;
                            width *= -1;
                        }
                        if (height < 0) {
                            y = dragPoint.y;
                            height *= -1;
                        }
                        selectionPane.setBounds(x, y, width, height);
                        selectionPane.revalidate();
                        repaint();
                    }
    
                };
                addMouseListener(adapter);
                addMouseMotionListener(adapter);
    
            }
    
            public Point getBottomRight() {
    			// TODO Auto-generated method stub
    			return dragPoint;
    		}
    
    		public Point getTopLeft() {
    			// TODO Auto-generated method stub
    			return mouseAnchor;
    		}
    		
    		
    
    		@Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.drawImage(background, 0, 0, this);
                g2d.dispose();
            }
    
    		public boolean getIsComplete() {
    
    			return selectionPane.getIsComplete();
    		}
    
        }
    
        public class SelectionPane extends JPanel {
    
        	//private Point TopLeft;
        	//private Point BottomRight;
            private JButton button;
            //private JButton reset;
            private JLabel label;
            private Boolean complete;
    
            public SelectionPane() {
                button = new JButton("Close");
                //reset = new JButton("Reset");
                setOpaque(false);
    
                complete = false;
                label = new JLabel("Rectangle");
                label.setOpaque(true);
                label.setBorder(new EmptyBorder(4, 4, 4, 4));
                label.setBackground(Color.GRAY);
                label.setForeground(Color.WHITE);
                setLayout(new GridBagLayout());
    
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                add(label, gbc);
    
                gbc.gridy++;
                add(button, gbc);
                //gbc.gridy++;
                //add(reset, gbc);
    
                button.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        SwingUtilities.getWindowAncestor(SelectionPane.this).dispose();
                        complete = true;
                    }
                });
    
    //            reset.addActionListener(new ActionListener() {
    //                @Override
    //                public void actionPerformed(ActionEvent e) {
    //                    
    //                }
    //            });
    
                addComponentListener(new ComponentAdapter() {
                    @Override
                    public void componentResized(ComponentEvent e) {
                        label.setText("Rectangle " + getX() + "x" + getY() + "x" + getWidth() + "x" + getHeight());
                        //TopLeft = new Point(getX(),getY());
                        //BottomRight = new Point(getWidth(),getHeight());
                    }
                });
    
            }
            
            public Boolean getIsComplete()
            {
            	return complete;
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setColor(new Color(128, 128, 128, 64));
                g2d.fillRect(0, 0, getWidth(), getHeight());
    
                float dash1[] = {10.0f};
                BasicStroke dashed =
                                new BasicStroke(3.0f,
                                BasicStroke.CAP_BUTT,
                                BasicStroke.JOIN_MITER,
                                10.0f, dash1, 0.0f);
                g2d.setColor(Color.BLACK);
                g2d.setStroke(dashed);
                g2d.drawRect(0, 0, getWidth() - 3, getHeight() - 3);
                g2d.dispose();
            }
    
        }
    
        public static Rectangle getScreenViewableBounds() {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
    
            return getScreenViewableBounds(gd);
        }
    
        public static Rectangle getScreenViewableBounds(GraphicsDevice gd) {
            Rectangle bounds = new Rectangle(0, 0, 0, 0);
            if (gd != null) {
                GraphicsConfiguration gc = gd.getDefaultConfiguration();
                bounds = gc.getBounds();
    
                Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
    
                bounds.x += insets.left;
                bounds.y += insets.top;
                bounds.width -= (insets.left + insets.right);
                bounds.height -= (insets.top + insets.bottom);
            }
            return bounds;
        }
    	
    }
    This is the error I'm getting running the code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.main.MainController$CustomCaptureMouseClicks.a ctionPerformed(MainController.java:56)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

    My thought as to why is because the SelectionRectangle class is still running when it hits the next line in the controller class. So, the variables that I'm trying to fill aren't utilized yet. Also, while debugging, I hit the "TopLeft = m_rect.getTopLeft();" line before I actually create the rectangle.


    Let me know if that helps you. I googled SSCCE, but I couldn't think of a short way. :)
    Last edited by ted1a; 01-30-2014 at 07:47 PM.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: New to Java, and really stuck

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.main.MainController$CustomCaptureMouseClicks.a ctionPerformed(MainController.java:56)
    There is a variable with a null value on line 56. Look at line 56 in the your source and see what variable is null. Then backtrack in the code to see why that variable does not have a valid value.
    If you can not tell which variable it is, add a println just before line 56 and print out the values of all the variables on that line.

    I don't see a main() method in the posted code. How would the code be compiled and executed for testing?
    Last edited by Norm; 01-30-2014 at 02:17 PM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    ted1a is offline Member
    Join Date
    Jan 2014
    Posts
    4
    Rep Power
    0

    Default Re: New to Java, and really stuck

    Quote Originally Posted by Norm View Post
    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.


    There is a variable with a null value on line 56. Look at line 56 in the your source and see what variable is null. Then backtrack in the code to see why that variable does not have a valid value.
    If you can not tell which variable it is, add a println just before line 56 and print out the values of all the variables on that line.

    I don't see a main() method in the posted code. How would the code be compiled and executed for testing?
    Very correct on the line 56. I do know that is where I'm getting a problem. However, I want to not have the line above it until it returns. I think it is creating a thread, but when I add a wait at the end of the thread it doesn't stop and wait.

    As per your request, here is my main:
    Java Code:
    package com.main;
    
    public class MainProgram {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		MainModel m_model = new MainModel();
    		MainView m_view = new MainView(m_model);
    		MainController m_controller = new MainController(m_view,m_model);
    		
    		
    		m_view.setVisible(true);
    		
    		//m_rect.
    		
    	}
    	
    	
    
    }
    here is my view
    Java Code:
    package com.main;
    
    import java.awt.FlowLayout;
    import java.awt.TextArea;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class MainView extends JFrame {
    	private MainModel _model;
    	
    	//componenets 
    	private JButton m_getsize = new JButton("Capture Size");
    	private TextArea m_text = new TextArea();
    	
    	
    	public MainView(MainModel model)
    	{
    		_model = model;
    		
    		JPanel _panel = new JPanel(new FlowLayout());
    		_panel.add(m_getsize);
    		_panel.add(m_text);
    		
    		this.setContentPane(_panel);
    		this.pack();
    		
    		this.setTitle("Run Missions");
    		
    	}
    	
    	void AddButtonMouseClickListner(ActionListener _ButtonAction)
    	{
    
    		m_getsize.addActionListener(_ButtonAction);
    
    		
    	}
    	
    	public void setText(String _text)
    	{
    		m_text.setText(_text);
    	}
    	
    
    }
    here is my model (although I'm not really using it yet. I will once I get this figure out)
    Java Code:
    package com.main;
    
    import java.awt.Point;
    
    public class MainModel {
    	Point _topleft;
    	Point _bottomright;
    	
    	public MainModel()
    	{
    		_bottomright = _topleft = new Point(0,0);
    		
    		
    	}
    	
    
    }
    here is my controller
    Java Code:
    package com.main;
    
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    
    import javax.swing.JOptionPane;
    
    public class MainController {
    
    	MainView _view;
    	MainModel _model;
    	private Point TopLeft;
    	private Point BottomRight;
    	
    	
    	
    	public MainController(MainView m_view, MainModel m_model)
    	{
    		_view = m_view;
    		_model = m_model;
    		
    		_view.AddButtonMouseClickListner(new CustomCaptureMouseClicks(_view));
    		
    	}
    	
    	public class CustomCaptureMouseClicks implements ActionListener 
    	{
    
    		private Point TopLeft;
    		private Point BottomRight;
    		MainView _view;
    		
    		CustomCaptureMouseClicks(MainView view)
    		{
    			_view = view;
    			
    		}
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			// TODO Auto-generated method stub
    			if (e.getActionCommand() == null)
    				return;
    			
    
    			
    			SelectionRectangle m_rect = new SelectionRectangle();
    			//Thread m_thread = new Thread(m_rect);
    			//m_thread.start();
    
    
    			TopLeft = m_rect.getTopLeft();
    			BottomRight = m_rect.getBottomRight();
    			_view.setText(TopLeft.toString());
    			
    			
    		}
    		
    	}
    }
    You should have all of my code now. As I was saying, but I wasn't clear, the _view.settext is failing. It is failing because SelectedRectangle goes to the next as if it was a thread. If I convert it to a thread and override run, it still goes to the next line even if I add a wait() statement on the thread.

    Does that help?

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: New to Java, and really stuck

    _view.settext is failing
    Please explain what "is failing" means.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    ted1a is offline Member
    Join Date
    Jan 2014
    Posts
    4
    Rep Power
    0

    Default Re: New to Java, and really stuck

    Failing as in the variable that I'm using to write the text "TopLeft.toString()" is empty. That is the error I have reported. However, I cannot fill that variable until the SelectionRectangle completes._view.SetText is called before the SelectionRectangle completes.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: New to Java, and really stuck

    variable that I'm using to write the text "TopLeft.toString()" is empty
    There are more specific (and correct) ways to say that. Does the variable: TopLeft have a null value?
    When is does the getTopLeft() method have a valid non-null value?

    I don't understand what the code is supposed to do.
    Can you describe the steps the code and the user should do for the code to do what you want?
    After The user presses the Capture Size button then what?


    Question: Do professors teach the use of program comments? They are useful to explain what a program is trying to do.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Stuck with my inheritance java testing :'(
    By Aname in forum New To Java
    Replies: 12
    Last Post: 08-21-2012, 12:49 PM
  2. Really stuck in java
    By evelina1 in forum New To Java
    Replies: 7
    Last Post: 07-12-2011, 11:34 PM
  3. Java Help please xD SO stuck
    By Ethan in forum New To Java
    Replies: 1
    Last Post: 03-19-2011, 12:54 PM
  4. New to java and stuck
    By xpd259 in forum New To Java
    Replies: 2
    Last Post: 12-12-2010, 09:34 AM
  5. Stuck new to Java
    By Jaguar1998 in forum New To Java
    Replies: 3
    Last Post: 04-09-2010, 12:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •