Jump to content


Check out our Community Blogs

Turk4n

Member Since 13 May 2008
Offline Last Active Dec 03 2013 10:12 PM
-----

#601657 Tutorial simple dice game

Posted by Turk4n on 31 May 2011 - 11:22 AM

what is the function of this one,what is protected static scanner?:cursing:

protected static Scanner sc = new Scanner(System.in);

I used protected to ensure only those within the same package could use my thingy. Normally you don't need protected nor static. You could just go instance it normally and bam ready to go. Also the scanner is the input reader of data. I recommend you read up :)
Scanner (Java 2 Platform SE 5.0)
  • 1


#536305 Are These Good Deals?

Posted by Turk4n on 15 January 2010 - 12:12 PM

Where could I get them for free?:confused:


Well you could look for it at sourceforge.
SourceForge.net: Find and Develop Open Source Software
  • 1


#536079 Simple thread - Bouncing ball

Posted by Turk4n on 13 January 2010 - 11:56 PM

Very nice explanation and overall a great tutorial. I learned I bit from this.

Thanks.


Great to know :)
  • 1


#528314 Simple thread - Bouncing ball

Posted by Turk4n on 28 November 2009 - 08:08 AM

Hey Codecall !

I saw some threads with ping pong games and such, however most of them were broken.
So I thought, well let people have something simple to work with?
Maybe a running thread?

Anyways here it is !

Classes needed
import java.awt.*;
First class, our own Thread class that has a function we want...
class XThread extends Thread {
    public static boolean delay(long millis) {
        if (interrupted())
            return false;
        try {
            sleep(millis);
        } catch (InterruptedException e) {
            return false;
        }
        return true;
    }
}
Firstly, we inherit from Thread, since I didn't want to do something heavy, just made something simple. XThread will be the one to run later on...
The ball class
public class Ball extends Panel implements Runnable {
	protected Thread activity;
	private int r,x0,y0;
	private int xStep,yStep;
So, our ball, extends its area from Panel and we implement the runnable interface for our ball to since we are going to work with one thread...
Thread activity is our thread for the main dish...
While r,x0,y0 will represent the r for radius of a ball and x0 y0 start points.
Balls everywhere !
public Ball(int radius,int xSpeed, int ySpeed) {
		r = radius; xStep = xSpeed; yStep = ySpeed;
		x0 = r; y0 = r;
	}
Our constructor that will create the main ball every time we want to have balls.
Thread activity - Start || Stop
public void start() {
		if(activity == null) {
			activity = new Thread(this);
			activity.start();
		}
	}
	public void stop() {
		if(activity != null) {
			activity.interrupt();
			}
		}
As for our methods that will start of the execution of tasking we want(moving a ball...)
We will have to see when the activity is null. Thats when we will start a new thread which will allow the ball to interact with out panel area...
As stop checks if activity isn't null it will interrupt the activity, inherit from Thread applied to our own class called XThread.
Running with a Runnable interface you will need a method called run
public void run() {
		while(XThread.delay(100)) {
			if(x0-r+xStep<0 || x0+r+xStep > getSize().width)
				xStep = -xStep;
				x0 += xStep;
			if(y0-r+yStep<0 || y0+r+yStep > getSize().height)
				yStep = - yStep;
				y0 += yStep;
				repaint();
		}
	}
So ** mentioned, XThread is just a small adjustment of our own taste, my tasted I gotten to taste... Allowing the execution happen while the thread isn't destroyed or interrupted...
So, how does it move, while executing the process we have to have conditions it can follow or be bound to... ifx0-r+xStep<0 or x0+r+xStep>getSize().width Follows to, if start point minus radius+the speed in x axle, is less than 0 or invers, meaning from |<-->|. Literally from first point of wall to the last...
Same goes for in the y axle...
Drawing the ball...
public void paint(Graphics g) {
		g.fillOval(x0-r,y0-r,2*r,2*r);
	}
}
Drawing the ball depending from the radius point of x0 and y0. The rest is simple to get...Math...meh :-P
Demonstration of our ball, first off classes needed
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static javax.swing.JOptionPane.*;
Nothing much to pinpoint at...
Our class
public class BallDemo extends JFrame implements ActionListener {
Inheriting everything from JFrame as well using the interface ActionListener.
Every item we come to need to create a simple interface...
private Ball b;
	private JPanel panel = new JPanel();
	private JMenuBar JMB = new JMenuBar();
	private JMenu JM = new JMenu("Edit");
	private JMenuItem[] JMI = new JMenuItem[3];
	int r,sp;
As we connect a bridge with ball, and gave it the name b, we will be able to reach every method(public or protected) and instances...
Constructor
public  BallDemo() {
		JMI[0] = new JMenuItem("Start");
		JMI[1] = new JMenuItem("Stop");
		JMI[2] = new JMenuItem("Close");
		JMB.setSize(640, 20);
		String s = showInputDialog(null,"Radie");
		r = Integer.parseInt(s);
		s = showInputDialog(null,"Speed");
		sp = Integer.parseInt(s);
		b = new Ball(r,sp,sp);
		setLayout(null);
		add(panel);
		panel.setBackground(Color.white);
		panel.setSize(640,440);
		panel.setLocation(JMB.getX(), JMB.getY()+20);
		b.setLocation(b.getWidth(), b.getHeight());
		panel.setLayout(new BorderLayout());
		panel.add(b);
		add(JMB);
		JMB.add(JM);
		JM.add(JMI[0]);
		JM.add(JMI[1]);
		JM.add(JMI[2]);
		setSize(640,480);
		setResizable(false);
		JMI[0].addActionListener(this);
		JMI[1].addActionListener(this);
		JMI[2].addActionListener(this);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		show();
	}
As we used an array for our buttons, we will have to define every position of the array with a new button option thus allowing us to give them proper name as well use them correct...
Also, as I inheriting everything from JFrame, I can easily just use the methods without a reference variable.
Methods calling the balls stop and start methods.
public void start() {
		b.start();
	}
	public void stop() {
		b.stop();
	}
Nothing much to see, just using our reference to grab .stop and .start for our simple bouncing ball.
Our actionlistener...
public void actionPerformed(ActionEvent e) {
		if(e.getSource()==JMI[0]) {
				start();
			
		}
		else if(e.getSource()==JMI[1]) {
			stop();
		}
		else {
			System.exit(0);
		}
	}
As we used buttons, with names that supposedly do, so while pressing Start we activate our own method which activates the Balls method called start weird right?
Main
public static void main(String[] arg) {
		new BallDemo();
	}
	
}
So, just create a new BallDemo and run it while having fun !
More or less this is it :)
Grab it, evolve it or just reconstruct it the way you want it or, just make your own without looking at this one !

Run it...
[ATTACH]2366[/ATTACH]
Running...
[ATTACH]2367[/ATTACH]
Stopping...
[ATTACH]2368[/ATTACH]
Closing it...
[ATTACH]2369[/ATTACH]

Cheers ! :amr:

Attached Thumbnails

  • run it4.PNG
  • run it3.PNG
  • run it2.PNG
  • run it.PNG

  • 3


#523229 Microsoft Coffee??

Posted by Turk4n on 07 November 2009 - 10:37 AM

Microsoft | Microsoft device helps police pluck evidence from cyberscene of crime | Seattle Times Newspaper
Enough said, hope you enjoy the read :)

P.S - OLD news just wanted to drop it here just incase !
  • 1


#501602 Polymorphism

Posted by Turk4n on 23 August 2009 - 11:50 AM

Hello today, Codecall !

I will present today my part of lesson with a last tutorial for a loooong while.
Polymorphism.


So let's go on...

Packages
package Polymorphism;
This package will be our own, which means your folder you save the files have to be called Polymorphism. Polymorphism provides the Java coder the wondrous ability to have fun with overloading things. :P

Main class and constructor
public class Forum  {
	Forum() {
	}

Nothing much, just giving the ability to have a main frame for your code. You could call it a template for future work...
main
public static void main(String[] arg) {
The main, nothing much to point out or tell about.
Instances
Human[] H = new Human[4];
		H[0] = new Human("I ist BOT");
		H[1] = new English("Jake");
		H[2] = new Swedish("Bosse");
		H[3] = new Spanish("Joseu");

		System.out.println("Welcoming from around the world"+"\n");
		for(int i=0; i<H.length; i++) {
			H[i].talk();
		}
		
	}
}
This part is where the things are happening. While referring to the human class we will have to give some commands. By giving it a so called "String" name. It's really easy then to see what is happening if you want to have nothing or with a string name... So by creating handles we can get different things for instance. We can use whenever we like.
Super class.(This is not to be confused with superclass)
package Polymorphism;
public class Human {
	String Name;

	Human() {
	}
	public Human(String name) {
		this.Name = name;
	}
	public void talk() {
		System.out.println("Teh bot: "+Name);
	}
}
As human will represent the rest classes we have, such as sweden/spanish/english. We will have to make methods that will be simple to follow. Making it easy for us to close and open various functions, such as closed instance methods inside packages or open instance methods from other packages or available for other...
English class
package Polymorphism;
public class English extends Human {
	English() {
	}
	public English(String in) {
		super.Name = in;
	}
	public void talk() {
		System.out.println("Hey my name is "+Name);
	}
}
Now we are inheriting ever thing from the so while referring to the same class instance method we also overload the old one. So we are not replacing it but we are overloading it with another one. Most likely to do like this. Put a plate with food on another plate with food.
Spanish class
package Polymorphism;
public class Spanish extends Human {
	Spanish() {
	}
	public Spanish(String in) {
		super.Name = in;
	}
	public void talk() {
		System.out.println("Hola jouso "+Name);
	}
}
Same as the english part, we are inheriting from Human, and overloading the talk method.
Swedish class
package Polymorfism;
public class Swedish extends Human {
	Swedish() {
	}
	public Swedish(String in) {
		super.Name = in;
	}
	public void talk() {
		System.out.println("Hej jag heter "+Name); 
	}
}
So here comes swedish part :D, well same as the rest inheriting the instances and reference we overload for fun.
Output
Welcoming from around the world

Teh bot: I ist BOT
Hey my name is Jake
Hej jag heter Bosse
Hola jouso Joseu
Here is our output of the thing...

To summarize everything from now. Polymorphism allows user to override and overload simultaneously as well objecting instance methods and instance variables. Overriding a method allows users to change the whole concept of the originate method while overloading one is to apply a self made one identical from the original to the current one you making. So thus you can add different methods while using the same concept. Our human can talk, however our swedish person can sing out from the talk method. So generally these types of learning are needed when working with multiply classes and you want to have some control of them but still want them to be unique. Like a food store or corner menu list. You choices overrides every time you change your mind...

Cheers !
:amr:
  • 3


#497750 Simple Chat Client.

Posted by Turk4n on 10 August 2009 - 10:57 AM

Me too...



But really nice stuff, dude!


Haha, thanks :D
No problem on rep I don't mind if you rep- me even :D
  • 1


#497642 Color Mixer and JSlider

Posted by Turk4n on 10 August 2009 - 04:09 AM

Well, why not have fun with colors?

So let me introduce you guys to my color mixer and Slider tutorial !

Packages
import javax.swing.*;
import static javax.swing.JOptionPane.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
Note by using a static import I can easily just type in instances instead of referring to the class then use the instance method...

The class
public class JMyColor extends JFrame implements ActionListener,ChangeListener {
Inheriting everything from the JFrame class and implementing instructions from the ActionListener and ChangeListener interface :D
Variables and instances...
JFrame JF = new JFrame();
	private JLabel mix = new JLabel("Mix Colors",JLabel.CENTER);
	private JTextField X = new JTextField("0");
	private JTextField Y = new JTextField("0");
	private JTextField Z = new JTextField("0");
	private JPanel ColorPanel = new JPanel();
	private JSlider Alpha = new JSlider();
	private JSlider Beta = new JSlider();
	private JSlider Zeta = new JSlider();
	private JButton MixColor = new JButton("Mix");
	private JMenuBar JMB = new JMenuBar();
	private JMenu JM = new JMenu("Actions");
	private JMenuItem quit = new JMenuItem("Close");
	private JLabel CopyRight = new JLabel("Copyright - Turk4n",JLabel.CENTER);
Everything in here will be used. The text fields will present the numbers you can add to change the colors. Remember we are using RGB color scheme(DEC=INTEGERS) LOL :D Plus the sliders will change the colors :D
Constructor GUI
public JMyColor() {
		setLayout(null);
		add(JMB);
		JMB.add(JM);
		JM.add(quit);
		add(MixColor);
		add(CopyRight);
		add(ColorPanel);
		add(mix); add(X); add(Y); add(Z);
		add(Alpha); add(Beta); add(Zeta);
		
		CopyRight.setBounds(0,215,100,20);
		CopyRight.setFont(new Font("Sanserif",Font.ITALIC,10));
		JMB.setBounds(0,0,300,15);
		X.setBounds(10,30,60,20);
		Y.setBounds(10,60,60,20);
		Z.setBounds(10,85,60,20);
		Alpha.setBounds(200,35,90,20);
		Alpha.setValue(0);
		Alpha.setMinimum(0);
		Alpha.setMaximum(255);
		Beta.setBounds(200,60,90,20);
		Beta.setValue(0);
		Beta.setMinimum(0);
		Beta.setMaximum(255); 
		Zeta.setBounds(200,80,90,20);
		Zeta.setValue(0);
		Zeta.setMinimum(0);
		Zeta.setMaximum(255);
		mix.setBounds(100,25,80,40);
		MixColor.setBounds(110,60,60,20);
		ColorPanel.setBounds(100,130,80,80);
		MixColor.addActionListener(this);
		quit.addActionListener(this);
		Alpha.addChangeListener(this);
		Zeta.addChangeListener(this);
		Beta.addChangeListener(this);
		
		setSize(305,270);
		setVisible(true);
                setTitle("Color Mixer");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		show();
	}
As more or less, we are adding each item without following a Layout. This not recommended for users who likes to have something prebuild and easy to use. However if you want it to be positionable in your way you have to follow like I did... Our sliders will add a change as they are moved. That's why we are using Change Listener instead of the Action Listener that we are using for our close operation and mixer !
Sliders Listener
public void stateChanged(ChangeEvent e) {
		Color c = new Color(Alpha.getValue(),Beta.getValue(),Zeta.getValue());
		
		String NewAlpha = String.valueOf(Alpha.getValue());
		String NewBeta = String.valueOf(Beta.getValue());
		String NewZeta = String.valueOf(Zeta.getValue());
		
		X.setText(NewAlpha);
		Y.setText(NewBeta);
		Z.setText(NewZeta);
		ColorPanel.setBackground(c);
	}
As we have sliders that are move able. they also generate an integer value from 0-255
So basically we set the values the sliders are on to the ColorPanel and to the textfields :>
Action Listener
public void actionPerformed(ActionEvent e) {
		
			if(e.getSource()==MixColor) {
				
				String x = X.getText();
				String y = Y.getText();
				String z = Z.getText();
				
				int NewX = 0;
				int NewY = 0;
				int NewZ = 0;
				
				try
				{
					NewX = Integer.parseInt(x);
					NewY = Integer.parseInt(y);
					NewZ = Integer.parseInt(z);
					Alpha.setValue(NewX);
					Beta.setValue(NewY);
					Zeta.setValue(NewZ);
					
					Color c = new Color(NewX, NewY, NewZ);
						ColorPanel.setBackground(c);
				}catch(NumberFormatException NFE) {
					showMessageDialog(JF,"Does not compute !","String Error/One or two fields incorrect",JOptionPane.ERROR_MESSAGE);
				}
				catch(Exception OtherException){
					showMessageDialog(JF,"Does not compute !","Out of range 0-255",JOptionPane.ERROR_MESSAGE);
				}
			}
			else if(e.getSource()==quit) {
				System.exit(0);
			}
	}
Now the action listener will read in from our textfields. However the fields are strings and we can't use strings when integers are needed to display the color... We parse it and represent them as numbers from 0-255. Now. When the user is doing something wrong, like posting something out of boundary or just plain stupid and typing in color names...It will run some error messages for their own safety...
The main
public static void main(String[] arg) {
		new JMyColor();
	}
}
Here is the end and we are going to start the application and see the power of sliders :D And of course the colors !

Output
[ATTACH]1881[/ATTACH]
Cheers !

Attached Thumbnails

  • ColorMixer.png

  • 3


#497618 Multiply windows

Posted by Turk4n on 10 August 2009 - 01:24 AM

Good morning CodeCall !

I had before a request of how to create a multiply window function on a frame. Which gives the user ability to open new frames and dispose it without affecting nor freezing the previous window.

So let's get going !


Packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Since the user requested a detailed one I will explain it with a bit more heart...
By creating GUI tools, we need to have something that will draw the windows and tools for it. Java presents their own GUI API, swing. The awt presents our Listener functions and the awt.event presents our "event" accordance...

The class
public class DrawWindow extends JFrame implements ActionListener {
By using extends we inherit every single method from the JFrame class itself. Which residents inside our javax.swing package...Which makes it really neat :D
Our variables
private static int totNumbers = 0;
	private static int nextNr = 0;
	private int Nr;
	private JMenuBar mb = new JMenuBar();
	private JMenu men = new JMenu("Window");
	private JMenuItem New = new JMenuItem("New window");
	private JMenuItem reset = new JMenuItem("Reset");
	private JMenuItem close = new JMenuItem("Quit");
By creating 2 static integers to keep the track of numbers of window we create we are able to give a future method which I will present soon, which will help us to dispose and open windows with any bother.
The int Nr will present the numbers of window created to our WindowAdapter later on.While creating a JMenuBar, you can add buttons and items to it, you can also just add icons.
Constructor
public DrawWindow() {
		totNumbers++;
		Nr = nextNr++;
		setTitle("Drawing "+ (Nr+1));
		setLocation(30*Nr,30*Nr);
		setJMenuBar(mb);
		mb.add(men);
		men.add(New); men.add(close);
		
		New.addActionListener(this);
		close.addActionListener(this);
		addWindowListener(w);
		setSize(300,300);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
The constructor is our base frame. Now, every single time we are about to launch a new window, we will use these standards we point out. As well does it add the total numbers of windows as the current windows open. Now comes the part. Why didn't I use a JFrame instance? Well if I can inherit it instead. Then you don't need to refer to an instance variable. Just type out the methods and add your components !
Action methods...
public void actionPerformed(ActionEvent e) {
		if(e.getSource()==New) {
			new DrawWindow();
		}
		else if (e.getSource()==close) {
			dispose();
		}
	}
Here we have our actions. While pressing New in the JMenuItem inside the Bar. We can launch a new DrawWindow. Hence this is the method of launching a new frame.
While our close is disposing the old ones.
WindowAdapter
private WindowListener w = new WindowAdapter() {
		public void windowClosed(WindowEvent e) {
			if(--totNumbers==0)
				System.exit(0);
		}
	};
Here we have our Window listener. To keep track of our windows we are checking if the totNumbers equals to 0. Making it simple for use to exit without crashing application.
The main
public static void main(String arg[]) {
		new DrawWindow();
	}
}
Our main, the heart of launch our application. Which makes it simple to understand we are only launching the method. DrawWindow, the rest is just the windows :)

Hope this will help for the rest and the requester !
Output
[ATTACH]1880[/ATTACH]

P.S - Every window are on they own, you can move every of them without stopping the other !

Cheers !

Attached Thumbnails

  • outputDrawWindow.png

  • 2


#497468 Simple Chat Client.

Posted by Turk4n on 09 August 2009 - 12:55 PM

So, I wanted to present a ****ty chat client. I thought might be something cool to add in codecall. Since the IRC channel seems dead...
Why not have an Applet chat client, so I done a simple chat client making it possible for multiply users to type and chat, hopefully it will work...PROPERLY :D


To the code !


Packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
For does who are unfamiliar with these packages try to go read them later on...to get a hum about.

The receiver class
class Receiver implements Runnable {

		Thread activity = new Thread(this);
		MulticastSocket so;
		JTextArea txt;
		
	Receiver(MulticastSocket sock, JTextArea txtAr) {
		so = sock;
		txt = txtAr;
		activity.start();
		}
Here is our class that will represent the data we recieve :> MulticastSocket. This is something we will need if we want to have computers communicating each other. Since we are going to use a server holding up this client...So the MulticastSocket would be your "real" ip to the users.(Also 127.0.0.1 does not work :X)
Running the application(Not the main)
public void run() {
			byte[] data = new byte[1024];
			while(true)
				try {
					DatagramPacket packet = new DatagramPacket(data,data.length);
					so.receive(packet);
					String mess = new String(data,0,packet.getLength());
					txt.append(mess+ "\n");
				}
				catch(IOException e) {
			break;
		}
	}
}
While running we need to have something that actually will respond to our needs and so. Hence we send data in form of byte...(You can change if you want to something else like long or so...)Our data, will be represented as text lines.(Which is the lines you send and get...).
The Constructor and GUI base.
public class JChat extends JFrame implements ActionListener {
		String name;
		InetAddress iadr;
		int port;
		MulticastSocket so;
		JTextArea txt = new JTextArea();
		JScrollPane sp = new JScrollPane(txt);
		JTextField write = new JTextField();
		JButton quit = new JButton("Go Offline");
		public JChat(String username, String groupAdr, int portNr) throws IOException {
			name = username;
			iadr = InetAddress.getByName(groupAdr);
			port = portNr;
			
			so = new MulticastSocket(port);
			so.joinGroup(iadr);
			new Receiver(so,txt);
			[B]sendMess[/B]("Online");
			setTitle("Chatting with "+ name);
			txt.setEditable(true);
			add(quit,BorderLayout.NORTH);
			add(sp,BorderLayout.CENTER);
			add(write,BorderLayout.SOUTH);
			quit.addActionListener(this);
			write.addActionListener(this);
			setSize(400,250);
			setVisible(true);
			setDefaultCloseOperation(EXIT_ON_CLOSE);
		}
Here we have our constructor and GUI base for the client.By using standards, such as username and port and IP we can actually send and receive data...With ScrollPane we are able to use the scrolling function that a normal window have when content tend to be more than viewable by standard resolution...Plus we are adding each component to a bordered layout, making it simple for us to just place components and items.
sendMess method
public void sendMess(String s) {
			byte[] data = (name + ": " + s).getBytes();
			DatagramPacket packet = new DatagramPacket(data,data.length,iadr,port);
			try {
				so.send(packet);
			}
			catch(IOException ie) {
				Toolkit.getDefaultToolkit().beep();
				JOptionPane.showMessageDialog(null, "Data overflow !");
			}
		}
Now, by sending out text lines as bytes through Datagram packets we can view our sent lines... else we will get an overflow(Our Exception...)
Our actionListener
public void actionPerformed(ActionEvent e) {
		if(e.getSource()==write) {
			sendMess(write.getText());
			write.setText("");
			}
		else if(e.getSource()==quit) {
			sendMess("Offline");
			try {
				so.leaveGroup(iadr);
			}
			catch(IOException ie) {
				Toolkit.getDefaultToolkit().beep();
				JOptionPane.showMessageDialog(null, "Data overflow, connection error !");
				}
			so.close();
			dispose();
			System.exit(0);
			}
		}
The action listener, will register everything we do by the GUI. Typing and sending it...Also by using our offline button we can exit the application and terminate our connection with the client...
The main
public static void main(String[] arg) throws IOException {
		String in = JOptionPane.showInputDialog(null,"What's your name?");
		if(arg.length>0) 
			in = arg[0];
		new JChat(in,"Add a D-Class IP",9876);
	}
}
Now. with our main we are actually going to start the application and do something creative :D
While I am using our arg(which is also a container), to store the currently user(YOU and no one else...). Which makes it covient in my opinion... SO by adding our parameters while creating a new JChat(username,D-Class IP,port).
And we have our fantastic chat client !
Cheers !
Output
[ATTACH]1879[/ATTACH]

Attached Thumbnails

  • jchatclient.png

  • 4


#497040 Simple Text Editor

Posted by Turk4n on 08 August 2009 - 01:37 PM

Good day CC !

Today, early in the morning I made my first notepad clone... with less options and solutions !
So today I am going to show you ! How to make a less of a notepad in java !


Packages we will need
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;

The class
class TextEditor extends JFrame {

Base variables.
private JTextArea area = new JTextArea(20,120);
	private JFileChooser dialog = new JFileChooser(System.getProperty("user.dir"));
	private String currentFile = "Untitled";
	private boolean changed = false;

Our JTextArea will be the area where you can write documents and etc...
Also if you are unfamiliar with JFileChooser, then try to read more about the swing lib in Javas API page. Also by changed it will represent our flag of when things in our area changes.

Constructor Part #1
public TextEditor() {
		area.setFont(new Font("Monospaced",Font.PLAIN,12));
		JScrollPane scroll = new JScrollPane(area,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		add(scroll,BorderLayout.CENTER);
		
		JMenuBar JMB = new JMenuBar();
		setJMenuBar(JMB);
		JMenu file = new JMenu("File");
		JMenu edit = new JMenu("Edit");
		JMB.add(file); JMB.add(edit);
So here we are our area and the toolbar we will use... with JScrollPane we will be able to view a bit more of our text and area...Most likely as anything else :>
Constructor Part #2
file.add(New);file.add(Open);file.add(Save);
		file.add(Quit);file.add(SaveAs);
		file.addSeparator();
		
		for(int i=0; i<4; i++)
			file.getItem(i).setIcon(null);
		
		edit.add(Cut);edit.add(Copy);edit.add(Paste);

		edit.getItem(0).setText("Cut out");
		edit.getItem(1).setText("Copy");
		edit.getItem(2).setText("Paste");
Now by adding methods and arguments we haven't implemented from the beginning will of course complain in an active IDE...However fear not we will come to the point what New/Open/Save/Quit/SaveAs are...
While adding we also position them in a correct order with our for loop and set every icon to null.
Constructor Part #3
JToolBar tool = new JToolBar();
		add(tool,BorderLayout.NORTH);
		tool.add(New);tool.add(Open);tool.add(Save);
		tool.addSeparator();
		
		JButton cut = tool.add(Cut), cop = tool.add(Copy),pas = tool.add(Paste);
		
		cut.setText(null); cut.setIcon(new ImageIcon("cut.gif"));
		cop.setText(null); cop.setIcon(new ImageIcon("copy.gif"));
		pas.setText(null); pas.setIcon(new ImageIcon("paste.gif"));
		
		Save.setEnabled(false);
		SaveAs.setEnabled(false);
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		pack();
		area.addKeyListener(k1);
		setTitle(currentFile);
		setVisible(true);
	}
We are currently adding our functions and giving some proper icons for our toolbar items ! Note we are adding in icons and giving null text to each item.
Our Save and SaveAs functions will represent the standard every time we launch the application...hence it's false...

Listener
private KeyListener k1 = new KeyAdapter() {
		public void keyPressed(KeyEvent e) {
			changed = true;
			Save.setEnabled(true);
			SaveAs.setEnabled(true);
		}
	};
Now here we have our listener which will listen when any key is pressed thus making the changed statement true and allowing us to save or saveas.Quite good right?

Action #1
Action Open = new AbstractAction("Open", new ImageIcon("open.gif")) {
		public void actionPerformed(ActionEvent e) {
			saveOld();
			if(dialog.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) {
				readInFile(dialog.getSelectedFile().getAbsolutePath());
			}
			SaveAs.setEnabled(true);
		}
	};
By pressing on our ItemIcon we will trigger an Action(Abstract one). Also by triggering the Icon action we will be able to preserve the moment of our text. Resulting us to be able choose where to save and use it later :>

Action #2
Action Save = new AbstractAction("Save", new ImageIcon("save.gif")) {
		public void actionPerformed(ActionEvent e) {
			if(!currentFile.equals("Untitled"))
				saveFile(currentFile);
			else
				saveFileAs();
		}
	};
So here is our save function. We will be able to save our current file. So by playing along I thought like this. If the currentFile doesn't equal to Untitled then just save it as it's called... else save as thus allowing the sure to give it a title :P

Action #3
Action SaveAs = new AbstractAction("Save as...") {
		public void actionPerformed(ActionEvent e) {
			saveFileAs();
		}
	};
Nothing much with this action. We are just allowing the user to saveAs...thus giving it a title...

Action #4
Action Quit = new AbstractAction("Quit") {
		public void actionPerformed(ActionEvent e) {
			saveOld();
			System.exit(0);
		}
	};
A quit function is needed also we are saving the old one. Which means... we will see later on :P

Action Maping
ActionMap m = area.getActionMap();
	Action Cut = m.get(DefaultEditorKit.cutAction);
	Action Copy = m.get(DefaultEditorKit.copyAction);
	Action Paste = m.get(DefaultEditorKit.pasteAction);
By allowing us, to give absolute correct power we are using the DefaultEditorKit in the Swing package...(IO too..)

Methods #1
private void saveFileAs() {
		if(dialog.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
			saveFile(dialog.getSelectedFile().getAbsolutePath());
	}
So now we have defined what saveFileAs will result to. However what will saveFile do, is something I will return to.

Methods #2
private void saveOld() {
		if(changed) {
			if(JOptionPane.showConfirmDialog(this, "Would you like to save "+ currentFile +" ?","Save",JOptionPane.YES_NO_OPTION)== JOptionPane.YES_OPTION)
				saveFile(currentFile);
		}
	}
By using a saveOld giving us an option to save the changed state thus naming it old doesn't seem wrong, right~?

Method #3
private void readInFile(String fileName) {
		try {
			FileReader r = new FileReader(fileName);
			area.read(r,null);
			r.close();
			currentFile = fileName;
			setTitle(currentFile);
			changed = false;
		}
		catch(IOException e) {
			Toolkit.getDefaultToolkit().beep();
			JOptionPane.showMessageDialog(this,"Editor can't find the file called "+fileName);
		}
	}
As we are allowed to save, how do we open a file? Easy making a filereader method... The beep sound isn't required however I feel that making it kinda "cooler" why not give it an extra touch?

Method #4
private void saveFile(String fileName) {
		try {
			FileWriter w = new FileWriter(fileName);
			area.write(w);
			w.close();
			currentFile = fileName;
			setTitle(currentFile);
			changed = false;
			Save.setEnabled(false);
		}
		catch(IOException e) {
		}
	}
Our savefile method. Allowing the user to define a name for the title as well to his/her document.

The main
public  static void main(String[] arg) {
		new TextEditor();
	}
}
Creating a new TextEditor everytime we launch !
Hope you enjoyed to follow this tutorial as I created it for you guys !
Cheers !

Output.
[ATTACH]1877[/ATTACH]
IconPictures
[ATTACH]1878[/ATTACH]

Attached Thumbnails

  • TextEditorOutPut.png

Attached Files


  • 4


#493640 Polygon tutorial

Posted by Turk4n on 28 July 2009 - 01:12 PM

Hello and welcome to a CodeCall Java tutorial. Today I will talk about Pentagons in Java and how you can draw one also using it for fun with javas buildin GUI set; swing.
Firstly we all no what a Pentagons is, however for those unfamiliar with what a pentagons is here is an example of a pentagon.
Posted Image

So mainly a pentagon is a five edged figure. So how do I draw a pentagon with swing?
Well let's get going and do the thing.

Step #1
Make the pentagon(Object !)

Import the needed packages

Packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

Create the object

Class
public class Pent extends JPanel implements ActionListener {

Add up the needed variables
private int n,r;
	private double angle;
	private int[] x,y;
	private double dv = 5*2*Math.PI/360;
	private double turn = 0.0;
	private Timer tim = new Timer(100, this);

What are our variables for? Firstly we need two integers which represents the sum of every part and time. We need angle to deiced the angle of our pentagon you could do as you suit with it later on. We need two arrays to represent the 2-D figure. Dv will represent our edges and turn how much it will turn since I want to show one possibility with swing why not show off?
tim presents the time it will take to go around and around the world...


Build up functions

Pentagon

public Pent(int pieces, int radie) {
		n=pieces; r=radie;
		x = new int[n];
		y = new int[n];
		angle= 2*Math.PI/n;
	}
Our pentagon will take form soon, this is it's bones...

Start and Stop
public void start() {
		tim.start();
	}
	public void stop() {
		tim.stop();
	}

Movement of our pentagon
public void actionPerformed(ActionEvent E) {
		turn= turn+dv;
		if(turn>2*Math.PI)
			turn-= 2*Math.PI;
		repaint();
	}

Pentagon behavior
public void paintComponent(Graphics G) {
		super.paintComponents(G);
		int x0 = getSize().width/2;
		int y0 = getSize().height/2;
		
		for(int i=0; i<n; i++) {
			double v = i*angle- turn;
		x[i] = x0 + (int)Math.round(r*Math.cos(v));
		y[i] = y0 + (int)Math.round(r*Math.sin(v));
		}
		G.fillPolygon(x, y, n);
	}
}
Here we are actually filling the figure in a component that will we later present up into a frame with a start and stop button. The math.round presents the rotation that will happen.
Lets work on the main class now.

Main packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

Main class
public class PentDemo extends JFrame implements ActionListener {
Main variables
private JButton On= new JButton("On");
	private JButton Off = new JButton("Off");
        private JPanel a = new JPanel();
	private Pent p = new Poly(5,50);
We are going to use a Frame as our container for the Panel which will contain the pentagram allowing us to have it in a fine motion without disturbance, you could do it on the frame if you like to instead of my way. As we do not extend from the Pentagon class(pent) instead we are creating a reference to it and adding values to the constructor.

The main constructor and GUI build...
public PentDemo() {
		add(y,BorderLayout.CENTER);
		add(a,BorderLayout.SOUTH);
		a.add(On); a.add(Off); 
		On.addActionListener(this);
		Off.addActionListener(this);
		setSize(200,180);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setTitle("Pentagon");
	}
Simple frame build adding the components Panel and our Pent into the frame allowing us to use it for our own purpose I guess :X?(LOL).
Note as I told before you can add everything directly to the Frame we are extending from, instead of using a seperate Panel.(the variable called 'a')


Actions
public void actionPerformed(ActionEvent e) {
		if(e.getSource() == On) {
			y.start();
		}
		else
			y.stop();
	}
As we using our reference from pent we can use methods inside from pent to our main, which is start and stop...

The main application...
public static void main(String[] arg) {
		PentDemo pd = new PentDemo();
	}
}
And that's about it hope you enjoy this vague tutorial and hopefully you will do something more creative than I did...
Cheers !

Output
Posted Image
[ATTACH]1858[/ATTACH]

Attached Thumbnails

  • Pentagon.png

  • 8


#487879 Sigbars...

Posted by Turk4n on 21 July 2009 - 09:39 AM

So I made these out of my own will for myself however a good member told me I should present them to others and I thought why not?
Flame me or praise me - Doesn't matter

Cheers !

#1
http://forum.codecal...=1&d=1248215654
#2
http://forum.codecal...=1&d=1248215654
#3
http://forum.codecal...=1&d=1248215654
#4
http://forum.codecal...=1&d=1248215654

EDIT - Correct spelled now :>

Attached Thumbnails

  • cc_userbar4.png
  • cc_userbar2.png
  • cc_userbar3.png
  • cc_userbar.png

  • 1


#475213 instanceof?

Posted by Turk4n on 21 June 2009 - 05:39 AM

Looks, clean and simple enough, hence you done it right, I mean to check current position if true, and create a new situation if not true is as you have done...
So I would say you have done it very clean. Since your using a Listener right?
  • 1


#462378 What Anime is this?

Posted by Turk4n on 26 May 2009 - 09:23 PM

Bawh Why do I know this.... Its Tsubasa Chronicles, its an anime by CLAMP that re-uses most of the Cardcaptor characters.


Almost right, it is Cardcaptor Sakura. Not Tsubasa Chronicles :)
  • 1




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download