Jump to content

Quick java question


Callipygous

Recommended Posts

im trying to get back into programming java, but ive forgotten a lot.

 

in the program im working on right now im making some buttons, but the Graphics are set to draw it one pixel thick, and it looks really bad. i dont want to widen it by drawing more rectangles, because thats sloppy, annoying, and inefficient. is there a command to make it use a bigger pen when drawing its lines? i seem to remember something along those lines, but that may have been for a different class.

Link to comment
Share on other sites

I'm unsure of exactly what you are looking for but from what you are saying I'm assuming you want to increase the size of or alter the border of the buttons?

 

If so this might be of use, I've never been inclined to do that myself but it looks like this might be the way to do it -

 

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.html#setBorder(javax.swing.border.Border)

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/border/Border.html

 

Thats using a JButton rather than a simple button, not sure how you'd go about it otherwise. If you simply mean changing the size then obv you can just use setSize().

 

If I'm misunderstanding you completely and you are doing something with canvas drawing and 2D drawing then you might want to look here -

 

http://java.sun.com/developer/technicalArticles/GUI/java2d/java2dpart1.html

 

Sorry I'm just providing links, it's just a) I don't really understand what you want and b) I haven't really done much with Canvas drawing if that is what you want and in general am not particularly fussed about aesthetics :P. My Exams finish after this weekend so if your problem still isn't solved by then, I'll be happy to try and give a bit more of a hand.

Link to comment
Share on other sites

Aeternus, right now my buttons are rectangles drawn on the screen. im drawing them using Graphics, not Jbutton (which i probably should be using, but im not used to it) so you know how in ms paint you can pick up a wider brush, and then when you use it it draws a thicker line? thats all im trying to accomplish. setSize sounds right, but is that a method in Graphics or something else?

 

aswokei, no idea what that is.

Link to comment
Share on other sites

AWT and SWING are two different Java GUI frameworks, AWT is older and gives a more basic but standardised look and Swing uses GUI components from the system it is running on (so it looks and feels more natural on Windows or Linux+KDE or Linux+Gnome or Mac OS Xs Aqua etc). They are relatively simple to use and if you google for something like Java GUI tutorial, I'm sure you'll find a lot of information.

 

With respect to your problem, you are using the Graphics Class I take it, as far as I can see from the docs, this doesn't offer a way to change the pen or brush size when drawing elements but if you use the Graphics2D Class, it offers a way you can set the "stroke" for the image which allows you to define the brush or pen attributes when drawing any elements. The Graphics2D Class inherits from the Graphics Class so all the methods etc that you have been using SHOULD be there, it just allows more control over the way things are done. You can do things like setStroke( new BasicStroke(10) ) to have a pen/brush width of 10 pixels (afaik, i havent tested).

 

Take a look here -

 

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html#setStroke(java.awt.Stroke)

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/BasicStroke.html

Link to comment
Share on other sites

yeah, im using awt and the Graphics class.

 

but... moving on, i have a new issue. im using a MouseListener for the buttons. the way i have it implemented now it calls mouseEntered() any time the mouse enters the window at all, not specifically the button. i understand why it would do that with the way i have it implemented, but i cant figure out how to do it so its just for the buttons.

Link to comment
Share on other sites

/shrug

 

hell if i know. i was looking for something that would react to the mouse, both scrolling over it and when clicking it. mouselistener seemed about as perfectly suited as i could imagine...

 

are there reasons action listener would be better?

Link to comment
Share on other sites

As far as I know, either should be fine, I'd say the code is more readable using a MouseListener if that is all you are doing although using an ActionListener would be easier to tie multiple events together under one heading (ie you can check for a mouse click OR a key press etc and run the same code more easily).

 

Are you running addMouseListener on the button itself?

 

Ie youll have a button object and you'll want to call addMouseListener on the button object like button.addMouseListener( this ) , replacing this with whatever object instantiates the class that you defined the MouseListener interface methods in.

Link to comment
Share on other sites

for some reason my main file will let me call addMouseListener but when i do it for button it says cannot find symbol: method addMouseListener location: class button.

 

the way i have it now the mouselistener methods are defined in button and addMouseListener is called by the frame (which is of course why it calls it anytime the mouse enters the window).

 

but button wont let me call addmouselistener : P

 

forgot to make it extend component : P

 

but now it doesnt work at all. do i need to somehow set its bounds?

Link to comment
Share on other sites

ok..... Sorry, I forgot that your button was a little special, its a Rectangle or something isn't it? You have some custom Rectangle class that inherits from Rectangle??

 

Could you describe a little how exactly you have everything laid out

Link to comment
Share on other sites

for some reason my main file will let me call addMouseListener but when i do it for button it says cannot find symbol: method addMouseListener location: class button.

 

the way i have it now the mouselistener methods are defined in button and addMouseListener is called by the frame (which is of course why it calls it anytime the mouse enters the window).

 

but button wont let me call addmouselistener : P

 

I think that this is because for the button you have to use an ActionListener an if you do don't forget to implement it.

Link to comment
Share on other sites

i have a custom class called button. right now it extends Component and implements MouseListener.

 

i have the bounds set and had it print them out and they are all correct. but it doesnt react at all.

 

in the main file i have a 2d array called nums that has buttons 0-9 in the same layout as a phone

 

this is where i make the listeners:

 

for (int i=0; i<nums.length-1; i++)

{

for (int p=0; p<nums[0].length; p++)

{

nums[p].addMouseListener(nums[p]);

}

}

nums[3][1].addMouseListener(nums[3][1]);

 

 

i dont know if its a problem that the same button is the listener and the implementer. never messed with this stuff before : P

Link to comment
Share on other sites

I think that this is because for the button you have[/i'] to use an ActionListener an if you do don't forget to implement it.

 

I've never come across one having to implement ActionListener on a Button :\

 

 

i dont know if its a problem that the same button is the listener and the implementer. never messed with this stuff before : P

 

ok so have you actually compiled this seperate class first? It won't be visible to the other class you are trying to use it in otherwise, also on the same note, are you sure you are implementing the MouseListener correctly, it will obviously not compile correctly otherwise but I'm wondering if you have compiled your first class (the button class) before trying to compile the second.

 

You'll need to implement all of the MouseListener's methods (there are about 5 of them). They don't need to have code, they just need to be there (ie they can just have a method header and no code in the brackets/code block).

Link to comment
Share on other sites

the program runs, the buttons draw themselves, all if it compiles when i hit the compile project button. i have functions for all the mouselistener methods, some of them are empty like you said, but they are there.

 

it runs, the buttons just dont do anything when the mouse enters or clicks it (which are the two methods that arent empty right now)

Link to comment
Share on other sites

I've never come across one having to implement ActionListener on a Button :\

 

What I meant was:

public class theClass extends JFrame implements ActionListener

 

and then on the button you can write

 

theButton.addActionListener(this);

 

and then create the actionPerformed method

Link to comment
Share on other sites

What I meant was:
public class theClass extends JFrame implements ActionListener

 

and then on the button you can write

 

theButton.addActionListener(this);

 

and then create the actionPerformed method

 

 

Yes..... he's doing the same thing but with MouseListener instead of ActionListener, which is fine.

 

 

Callipygous, could you paste some of the code here so we can see what you are doing? What exactly should it do when you move your mouse over the buttons or click them? Baring in mind if you have made any changes to the actual GUI itself youll need to refresh things by doing something like hiding and reshowing things with setVisible(true) and setVisible(false).

Link to comment
Share on other sites

Yes..... he's doing the same thing but with MouseListener instead of ActionListener, which is fine.

 

I know but I once tried to to it and it didn't work so I opted for using the ActionListener and that solved my problem so it was just a suggestion. :P

Link to comment
Share on other sites

pretty simple really.... it should change some colors and throw out a print line.

 

public void mouseClicked(MouseEvent e)

{}

public void mouseEntered(MouseEvent e)

{

frame1=Color.BLACK;

frame2Color=Color.RED;

middle=Color.WHITE;

System.out.println("Mouse Entered");

}

public void mouseExited(MouseEvent e)

{

}

public void mousePressed(MouseEvent e)

{

System.out.println("Mouse Pressed");

}

public void mouseReleased(MouseEvent e)

{

}

 

 

it does neither.

Link to comment
Share on other sites

So you arent getting anything printed out on the command line?

 

I can understand why if you are changing any colours they wont update, as youll need to refresh the GUI so that everything is redrawn with the new colours (not exactly sure how you are handling the colour change, seems a little odd just to set some vague variable to a different colour, I don't see how that changes anything, perhaps you need to run another method and pass these colours in, and then refresh? It might work through referencing I suppose so you might not have to pass it back in if you passed them in the first time, depends how it all works internally) but if the String aren't printing out on the command line then I don't see what the problem is (you can pass in an object itself to the addMouseListener, i've tried it).

 

Perhaps you could post the code as a whole (ie all the code), there are [ code ] [ / code ] tags (obv remove spaces) on here so you can display things more easily, or you can use things like pastebin. When we can see the code as a whole its easier to debug it ourselves and point out any problems.

Link to comment
Share on other sites

Calculator.java

 

public class Calculator {

   public static void main(String[] args) {
       // Create application frame.
       CalculatorProg frame = new CalculatorProg();

       // Show frame
       frame.setVisible(true);

       frame.play();
   }
}

 

CalculatorProg.java

import java.awt.*;
import java.awt.event.*;
import java.awt.Image.*;

public class CalculatorProg extends Frame {

  button[][] nums= new button[4][3];
 Image theBuffer;
    Graphics BGraphic;
    boolean newEqu=true;

public CalculatorProg() {

    	//set up the menu bar       
       MenuBar menuBar = new MenuBar();
       Menu menuFile = new Menu();
       MenuItem menuFileExit = new MenuItem();
       MenuItem menuFileNew= new MenuItem();

       menuFile.setLabel("File");
       menuFileExit.setLabel("Exit");
       menuFileNew.setLabel("New");

       // Add action listener.for the menu button
       menuFileExit.addActionListener
       (
           new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                   CalculatorProg.this.windowClosed();
               }
           }
       ); 
       menuFileNew.addActionListener
       (

       	new ActionListener(){
       		public void actionPerformed(ActionEvent e){
       			newEqu=true;
       		}
       	}	

       );
       menuFile.add(menuFileNew);
       menuFile.add(menuFileExit);
       menuBar.add(menuFile);

       setTitle("Calculator");
       setMenuBar(menuBar);
       setSize(new Dimension(500, 500));
       setVisible(true);

       // Add window listener.
       this.addWindowListener
       (
           new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                   CalculatorProg.this.windowClosed();
               }
           }
       );  


      theBuffer= createImage(getWidth(),getHeight());
      BGraphic= theBuffer.getGraphics();


}





public void play()
   {
   	initializeButtons();
   	do
   	{

   	drawButtons(BGraphic);
   	paint(getGraphics());
   	}while(true);

   }
   public void paint(Graphics g)
   {   	
   	if(BGraphic == null)
   	{
   		System.out.println("BGraphic is null");
   	}
   	else
   	{

    	try
   		{
   			g.drawImage(theBuffer,0,0,this);
   		}
   		catch(Exception e)
   		{
   			System.out.println("problem drawing image because" + e.toString());

   		}
   	}
}


private void initializeButtons()
{
	System.out.println("initializing num pad");
	int num=1;
	for (int i=0; i<nums.length-1; i++)
	{
		for (int p=0; p<nums[0].length; p++)
		{
			nums[i][p]=new button();
			nums[i][p].initialize(i,p,Integer.toString(num));
			num++;

		}
	}
	nums[3][1]=new button();
	nums[3][1].initialize(3,1,"0");
	for (int i=0; i<nums.length-1; i++)
	{
		for (int p=0; p<nums[0].length; p++)
		{
			nums[i][p].addMouseListener(nums[i][p]);
			System.out.println("makin the buttons listen");

		}
	}
	nums[3][1].addMouseListener(nums[3][1]);


}

private void drawButtons(Graphics BGraphic)
{
	for (int i=0; i<nums.length-1; i++)
	{
		for (int p=0; p<nums[0].length; p++)
		{
			nums[i][p].draw(BGraphic);	
		}
	}
	nums[3][1].draw(BGraphic);
}

protected void windowClosed() {

   	// TODO: Check if it is save to close the application

       // Exit application.
       System.exit(0);
   }
   public void pause(long milliPause)// leave this alone!
// continues to query the system for the time until the first time - current time 
// exceeds the long passed into the function	
{
	long start = System.currentTimeMillis();
	while(System.currentTimeMillis()-start < milliPause)
	{
	// do nothing	
	}	

}

}

 

(yes, i know initializebuttons could just as easily be one loop, it was a copy and paste thing : P)

 

button.java

import java.awt.*;
import java.awt.event.*;
import java.awt.Color.*;
public class button extends Component implements MouseListener{
private int xCoor;
private int yCoor;
private int width=30;
private int length=30;
private String value= "1";
private Color frame1=Color.BLACK;
private Color frame2Color=new Color(255,0,0);
private Color middle=Color.WHITE;
private int frame2=0;



public button()
{

}

public void draw(Graphics g)
{

	Color temp= frame2Color;
	g.setColor(frame1);
	g.drawRect(xCoor,yCoor,length,width);
	g.setColor(middle);
	g.fillRect(xCoor+1,yCoor+1,length-2,width-2);
	for (int i=5; i>0; i--)
	{
		g.setColor(temp);
		temp=new Color(255,255-(51*i),255-(51*i));

		g.drawRect(xCoor+1+(5-i),yCoor+1+(5-i),length-2-(2*(5-i)),width-2-(2*(5-i)));
	}

	g.setColor(Color.BLACK);
	g.drawString(value, xCoor+10,yCoor+width-10);


}
public void initialize(int a, int b, String c)
{
	yCoor=(a*width)+100;
	xCoor=(b*length)+50;
	setBounds(xCoor,yCoor,length,width);
	value=c;
	System.out.println("bounds are set at"+xCoor+","+yCoor+","+length+","+width+ " for button  " + value);
}

public void mouseClicked(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{
	frame1=Color.BLACK;
	frame2Color=Color.RED;
	middle=Color.WHITE;
	System.out.println("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
	System.out.println("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
}


}

Link to comment
Share on other sites

From what I can see you seem to just be drawing rectangles onto a graphics buffer but you aren't adding the actual Component objects to the frame and all you have is an image. I'm not entirely sure if the way in which you are doing this is a good way to do it, I would've thought if you wanted custom buttons, that all the Graphics work would be on each component and then the button can just be treated like a normal Button like in AWT, however each to their own.

 

Adding the additional add() calls here seems to fix the problem -

 

	for (int i=0; i<nums.length-1; i++)
	{
		for (int p=0; p<nums[0].length; p++)
		{
			nums[i][p].addMouseListener(nums[i][p]);
			this.add(nums[i][p]);
			System.out.println("makin the buttons listen");

		}
	}
	nums[3][1].addMouseListener(nums[3][1]);
	add(nums[3][1]);

Link to comment
Share on other sites

im sure its not the best way to do it... for some reason thats just how ive always programmed. i figure out a way to make it happen and dont really like trying to use things like jButton. : P

 

my old programming teacher is also telling me im stupid and should just use jButton, so i might look into it... then again i might just be my usual stubborn self : D

 

thanks for the help.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.