Friday, July 13, 2012

JFrame to JApplet Conversion Project | Dragging JButton

Program Description:

This is a simple Java project, a conversion project from JFrame to JApplet which was requested by someone in my Fan Page. I am trying to make the code as simple as possible and as short as possible so it can be understood easily.

Output:




Original Code:

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

public class Demo extends JFrame implements MouseMotionListener{
JButton btn;
Demo(){
setSize(300, 300);
setVisible(true);
btn = new JButton("Drag me");
getContentPane().setLayout(null);
add(btn);
btn.setBounds(50, 50, 100, 40);
btn.addMouseMotionListener(this);
}
public static void main(String[] args){
new Demo();
}
public void mouseDragged(MouseEvent e) {
int x=(int) getMousePosition().getX();
int y=(int) getMousePosition().getY();
btn.setLocation(x, y);
}
public void mouseMoved(MouseEvent e) {

}

}

Code:

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

public class DemoApplet extends JApplet implements MouseMotionListener{
JButton btn = new JButton("Drag Me");

public void init() {
btn.setBounds(40,40,100,40);
Container pane = getContentPane();
FlowLayout flow = new FlowLayout();
pane.setLayout(flow);
pane.add(btn);
btn.addMouseMotionListener(this);
}

public void mouseDragged(MouseEvent e) {
int x=(int) getMousePosition().getX();
int y=(int) getMousePosition().getY();
btn.setLocation(x, y);
}
public void mouseMoved(MouseEvent e) {
}
}

Monday, July 2, 2012

Creating a simple JTable

Program Description:

Today we are going to create a very simple JTable in Java with inputs which I think this is the shortest, easy-to-understand JTable program you can find in the internet. In this program, there are only three things you need to observe 1.) The Column Names 2.) The Input Data 3.) Adding Scroll Bar. This program will show you how to create those things and add them in the JTable so you can come up with an output similar to the screenshot below and if you have finally understood the whole code, you are now ready to learn the complicated parts of this components. So I hope you'll find this very helpful and don't forget to add comments.

Output:
Code:

/**
* File: simpleJTable.java
* Tiltle: Creating a simple JTable
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class simpleJTable extends JFrame {

//Initializing the Column Names of the Table
String columnNames[] = {"First Name","Middle Name","Last Name"};

//Initializing the Specific Data input of the Table
Object data[] [] = {{"Jack","Denzil","Smith"},{"Robert","Smack","Gregory"},{"Stephen","Den","Stash"},{"Evelyn","Baaclo","Kontes"}};

//Setting up GUI
public simpleJTable() {

//Setting up the Title of the Window
super("Creating a simple JTable");

//Creating a JTable with its property
JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);

//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Setting up the container layout
GridLayout grid = new GridLayout(1,0);
pane.setLayout(grid);

//Adding the Component JScrollPane so the JTable can be visible in the container
//with Scroll Bar on the right side if JTable input data exceeds the visible count
pane.add(scrollPane);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
pack(); //Group all the components together
}

//Main Method
public static void main (String[] args) {
simpleJTable pjtf = new simpleJTable();
}
}

Thursday, May 10, 2012

Transparent JTextField | The Simple and Basic way to do it

Program Description:

Today I have created a very simple Java Program on how to create a transparent JTextField. This is just a basic way on how to create a 100% transparent JTextField which means you won't see anything but can type a text or an input. Even if you change the background color still you won't see anything because it is totally transparent. To know how, see the code below and the sample screenshots.

Output:


Code:

/**
* File: simpleTransparentJTF.java
* Tiltle: Transparent JTextField | The Simple and Basic way to do it.
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class simpleTransparentJTF extends JFrame {

//Constructing JTextField
JTextField field = new JTextField("Type your Text Here...",20);

//Initiazlizing the class Font to set our JTextField text style
Font defualtFont;

//Setting up GUI
public simpleTransparentJTF() {

//Setting up the Title of the Window
super("Transparent JTextField");

//Set Size of the Window (WIDTH, HEIGHT)
setSize(370,85);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Constructing class Font property
defualtFont = new Font("Arial", Font.BOLD, 18);

//Setting JTextField Properties
field.setFont(defualtFont);
field.setPreferredSize(new Dimension(150,40));
field.setForeground(Color.BLACK);

//Step 1: Remove the border line to make it look like a flat surface.
field.setBorder(BorderFactory.createLineBorder(Color.white, 0));

//Step 2: Set the background color to null to remove the background.
field.setBackground(null);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Change the background color of the container to see
//if the JTextField is really transparent.
pane.setBackground(Color.YELLOW);

//Adding JTextField to our container
pane.add(field);

//Setting up the container layout
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
pane.setLayout(flow);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);

//Disable Frame Size
setResizable(false);
}

//Main Method
public static void main (String[] args) {
simpleTransparentJTF pjtf = new simpleTransparentJTF();
}
}

To test if it is really transparent, you can change the background color of the window by just changing the color if this line below:

//Change the background color of the container to see
//if the JTextField is really transparent.
pane.setBackground(Color.YELLOW);

Important Part of the Program:

//Step 1: Remove the border line to make it look like a flat surface.
field.setBorder(BorderFactory.createLineBorder(Color.white, 0));

//Step 2: Set the background color to null to remove the background.
field.setBackground(null);

Note: This techniques won't give you a very nice output if you are going to put a graphic image at the back of the JTextField because it will just ignore the image. Do not use images as background of your window if you are going to use this technique. You can use different background colors using the class Color.

If you have any questions or comments about the program, feel free to post it here.

Wednesday, May 9, 2012

Resizing or Changing JTextField Size using simple Java Code

Program Description:

This program is just a simple java code to illustrate on how to re-size the JTextField in a simple way using simple code. Similar to JPanel, the way on how to change JTextField size is through the method setPreferredSize(); and the class Dimension.

Output:
Code:

/**
* File: resizeJTextField.java
* Tiltle: Simple way in Resizing JTextField
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class resizeJTextField extends JFrame {

//Constructing JTextFields
JTextField size1 = new JTextField("RESIZING JTEXTFIELD");
JTextField size2 = new JTextField("RESIZING JTEXTFIELD");
JTextField size3 = new JTextField("RESIZING JTEXTFIELD");
JTextField size4 = new JTextField("RESIZING JTEXTFIELD");

//Setting up GUI
public resizeJTextField() {

//Setting up the Title of the Window
super("Simple way in Resizing JTextField");

//Set Size of the Window (WIDTH, HEIGHT)
setSize(500,435);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Setting up the layout of the container
pane.setLayout(new FlowLayout(FlowLayout.CENTER));

//Setting the JTextField text to center
size1.setHorizontalAlignment(SwingConstants.CENTER);
size2.setHorizontalAlignment(SwingConstants.CENTER);
size3.setHorizontalAlignment(SwingConstants.CENTER);
size4.setHorizontalAlignment(SwingConstants.CENTER);

//Spicify the size of the JTextField using the method setPreferredSize() and the class Dimension
size1.setPreferredSize(new Dimension(450,150));
size2.setPreferredSize(new Dimension(450,100));
size3.setPreferredSize(new Dimension(450,75));
size4.setPreferredSize(new Dimension(450,50));

//add the JTextFields in the container
pane.add(size1);
pane.add(size2);
pane.add(size3);
pane.add(size4);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}

//Main Method
public static void main (String[] args) {
resizeJTextField pjtf = new resizeJTextField();
}
}

Important Part of the Program:

//Spicify the size of the JTextField using the method setPreferredSize() and the class Dimension
size1.setPreferredSize(new Dimension(450,150));
size2.setPreferredSize(new Dimension(450,100));
size3.setPreferredSize(new Dimension(450,75));
size4.setPreferredSize(new Dimension(450,50));

Sunday, May 6, 2012

Fixing CCB-A Problem in JCreator Pro 4.5 or any version or any software | The safe way to do it.

When you encounter CCB-A problem, a pop-up window that says

Your system clock appears to have been changed, possibly in an attempt to defeat the security system on this program. Please correct your system clock before trying to run this program again. If your clock is already correct, rebooting the system may fix this problem, otherwise contact the author of this program for instructions (report code CCB-A).
everytime you open an application. This can happen to any trial version software since it is used to protect trial version software from being abused by changing the system time so it won’t expire. This problem also exist if you are using trial version software then you apply a crack to make it a full version, so be careful with cracks.

There are lots of ways on how to solve this problem but most of them are too risky since it involves changing the registry which could damaged other software if it is not handled properly.

In my experience, I am using JCreator Pro 4.5 and installed it in my computer. I forgot to register it so I closed the application without registering. When I opened it again, I was shocked because a pop-up window saying that “My system clock appears to have changed and so on...” which was the CCB-A error. It was so annoying because I can’t register it anymore. I tried to change my system clock but still it didn’t worked. I tried uninstalling and installing it again but still it didn’t worked out. I did almost everything from registry to my CMOS but it didn’t change anything. The problem was still there. So I did these very simple steps as my last resort in solving the problem.

1.    I uninstall the JCreator Pro and install it again to have a fresh copy. (Note: Don’t open the application yet).
2.    I turned off the computer and remove the battery of my computer. The battery is used to make your system clock up to date.
3.    I turned on the computer without the battery and set the CMOS time manually to current date and time and saved it.
4.    As I was in the desktop, I changed the CLOCK in the TASKBAR and set it to current date and time.
5.    I opened the application and BOOMM!!! The solution was perfect. It runs perfectly and I was able to register the software.

I hope my solution works on your computer. Please give me some feedback if you have further questions or comments or if it works or not.

Thursday, May 3, 2012

My First JApplet | How to create an Applet

Program Description:

Today we are going to create our first basic java applet program using JApplet component. This is just a very short and simple java code that you can really understand.

JApplet is a subclass of Applet, a class in the java.applet package. An applet is a visual window inside a webpage that means they need to be run as part of a World Wide Web page.

In creating an Applet it involves two files the java file where our java codes resides of course and the HTML file where our java codes will be running using the ".class" file.

In creating our class it should always extends to JApplet. Example:

public class myFirstApplet extends JApplet {

}

then next to our java applet code is our HTML code where we embed our java code using the ".class" file. Here is the basic code on how to embed our java applet code in a webpage.




1. Starts with an opening HTML tag <html>
2. Followed by an opening Applet tag <applet>
3. specify your java applet code by locating the ".class" file which is usually created if you compile your java codes.
4. Specify the width and the height of your applet in the webpage.
5. Closing the applet tag </applet>
6. Closing the html tag </html>

Note: Compile your java code and your HTML code then run the HTML file. I am using JCreatorPro so I automatically load the HTML file, then compile, and run. See output below:

Output:
Code:

Java Code

/**
* File: myFirstApplet.java
* Tiltle: My First JApplet | How to create an Applet
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class myFirstApplet extends JApplet {

//Creating paint method so we can draw text on applet's background
public void paint(Graphics g) {

//Call the method paint
super.paint(g);

//Draw 3 strings at different locations
g.drawString("Welcome to my First Java Applet",30,30);
g.drawString("Welcome to Java Programming",30,50);
g.drawString("Thank you for Visiting: http://java-code-complete.blogspot.com",30,90);
}
}

HTML Code:




Monday, April 23, 2012

How to put a JTextField, JLabel, and JButton above image

Program Description:

This Java program demonstrates on how to add JComponents above an image. The technique is simple, it is just a JPanel inside another JPanel.

We created a class called "backgroundClass" which extends to JPanel so that means our class "backgroundClass" is a JPanel. In our main JPanel the class "backgroundClass", we set there our background image then inside our main JPanel we added two JPanels which holds the JLabel, JTextField, and JButton.

By setting the background color of our JPanel 1 to transparent, we can see in the output that it is like the label, the buttons, and the textfields are actually placed above the image but it is not, instead it is a layer of panels, a JPanel placed inside another JPanel.

Output:
Code:

Main Program

/**
* File: interfaceAndImage.java
* Tiltle: How to put a JTextField, JLabel, and JButton above image
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class interfaceAndImage extends JFrame {

//Constructing the class we created called "backgroundClass" so we can
//use it here in our main program as a parent panel.
backgroundClass bc;

//Initializing our JComponents and the labels of our JButton and JLabel
JPanel panel1, panel2;
JLabel labels[];
JButton choices[];
JTextField inputs[];
String lebelName[] = {"Name:","Age:","Sex:","Address:","Tel. No.:"};
String buttonChoice[] = {"Register","Reset","Cancel"};

//Setting up GUI
public interfaceAndImage() {

//Setting up the Title of the Window
super("How to put a JTextField, JLabel, and JButton above image");

//Set Size of the Window (WIDTH, HEIGHT)
setSize(310,170);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Constructing the class "backgroundClass" and call the keyword "this" so it can
//be recognizable by our main program.
bc = new backgroundClass(this);

//Constructing JPanel 1 and set its layout property including the background property
//which is transparent
panel1 = new JPanel();
panel1.setLayout(new GridLayout(5,2));

//Constructing the class Color and set its property to 0,0,0,0 means no color.
Color trans = new Color(0,0,0,0);
panel1.setBackground(trans); //Setting JPanel 1 background to transparent


//Constructing JPanel 2 and set its layout property
panel2 = new JPanel();
panel2.setLayout(new GridLayout());

//Constructing our JComponents setting its specific array size
labels = new JLabel[5];
inputs = new JTextField[5];
choices = new JButton[3];

//Adding our JPanel 1 and 2 to our class "backgroundClass" which is our parent panel
bc.add(panel1, BorderLayout.NORTH);
bc.add(panel2, BorderLayout.SOUTH);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Constructing JLabel and JTextField using "for loop" in their desired order
for(int count=0; count<inputs.length && count<labels.length; count++) {
labels[count] = new JLabel(lebelName[count], JLabel.RIGHT);
inputs[count] = new JTextField(30);

//Adding the JLabel and the JTextFied in JPanel 1
panel1.add(labels[count]);
panel1.add(inputs[count]);
}

//Constructing all 4 JButtons using "for loop" and add them in the panel 1
for(int count=0; count<choices.length; count++) {
choices[count] = new JButton(buttonChoice[count]);
panel2.add(choices[count]);
}

//Adding the class "backgroundClass" to our container as parent panel
pane.add(bc);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);

//Disable window size
setResizable(false);
}

//Main Method
public static void main (String[] args) {
interfaceAndImage iai = new interfaceAndImage();
}
}

Main JPanel (class "backgroundClass")

This is our main JPanel which holds our background image. This is where we also place our JButtons, JLabel, JTextField, and another JPanel by calling this class to our main Program.

/**
* File: backgroundClass.java
* Tiltle: Adding Image Above Another Image (class extention)
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class backgroundClass extends JPanel {

//Initializing the class Image
Image background;

//Setting up GUI
public backgroundClass(interfaceAndImage iai) {

//Constructing the class "Toolkit" which will be used to manipulate our images.
Toolkit kit = Toolkit.getDefaultToolkit();

//Getting the "background.jpg" image we have in the folder
background = kit.getImage("background.jpg");
}

//Manipulate Images with JAVA2D API. . creating a paintComponent method.
public void paintComponent(Graphics comp) {

//Constructing the class Graphics2D. Create 2D by casting the "comp" to Graphics2D
Graphics2D comp2D = (Graphics2D)comp;

//creating a graphics2d using the images in the folder and place it in a specific coordinates.
comp2D.drawImage(background, 0, 0, this);
}
}

Thursday, April 19, 2012

JPanel Transparency Demo

Program Description:

I've been surfing in the internet about JPanel transparency and I found out that there are lots of code versions out there on how to make JPanel background color transparent and to tell you, the codes are not so easy to digest which means very bad for beginners.

So today I created a very simple code on how to make a semi-transparent JPanel and a total transparent JPanel which is very easy to follow and understand. I always make sure to organize my codes into a uniform format so the errors can easily be tracked, modified, and understand.

Kindly post a comment if there is something in the code you didn't understand.

Output:



Code:

/**
* File: jpanelTransparency.java
* Tiltle: JPanel Transparency Demo
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;

public class jpanelTransparency extends JFrame {

//Initializing JComponents
JPanel testSubject, top, buttonPanel;
JButton normal, semiTrans, transparent;

//Setting up GUI
public jpanelTransparency() {

//Setting up the Title of the Window
super("JPanel Transparency Demo");

//Set Size of the Window (WIDTH, HEIGHT)
setSize(430,200);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Constructing testSubject JPanel
testSubject = new JPanel();

//Constructing top JPanel and setting up its background color property
top = new JPanel();
top.setBackground(Color.blue);

//Constructing buttonPanel JPanel and setting up its layout property
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,3));

//Constructing all 3 JButtons
normal = new JButton("Normal");
semiTrans = new JButton("Semi-Transparent");
transparent = new JButton("Transparent");

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Setting up testSubject JPanel properties
testSubject.setBorder(BorderFactory.createLineBorder(Color.black,1));
testSubject.setBackground(Color.WHITE);
testSubject.setPreferredSize(new Dimension(100,100));

//Adding the "testSubject" JPanel inside "top" JPanel
top.add(testSubject);

//Adding all 3 JButtons inside buttonPanel JPanel
buttonPanel.add(normal);
buttonPanel.add(semiTrans);
buttonPanel.add(transparent);

//Implemeting Even-Listener on JButton using ActionListener
normal.addActionListener(
new ActionListener() {

//Handle JButton event if Enter key is pressed or if mouse is clicked.
public void actionPerformed(ActionEvent event) {

//Creating a white color as normal background color to our testSubject panel
Color whiteColor = new Color (255, 255, 255, 255);
testSubject.setBackground(whiteColor);
}
}
);

//Implemeting Even-Listener on JButton using ActionListener
semiTrans.addActionListener(
new ActionListener() {

//Handle JButton event if Enter key is pressed or if mouse is clicked.
public void actionPerformed(ActionEvent event) {

//Creating a semi-transparent red backgroud color to our testSubject panel
Color transparentRed = new Color (255, 0, 0, 25);
testSubject.setBackground(transparentRed);
}
}
);

//Implemeting Even-Listener on JButton using ActionListener
transparent.addActionListener(
new ActionListener() {

//Handle JButton event if Enter key is pressed or if mouse is clicked.
public void actionPerformed(ActionEvent event) {

//Set the background color to empty
testSubject.setBackground(null);
}
}
);

//Adding JPanel top and buttonPanel to the container
pane.add(top, BorderLayout.NORTH);
pane.add(buttonPanel, BorderLayout.SOUTH);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}

//Main Method
public static void main (String[] args) {
jpanelTransparency jt = new jpanelTransparency();
}
}

Important Part of the Program:

//Implemeting Even-Listener on JButton using ActionListener
semiTrans.addActionListener(
new ActionListener() {

//Handle JButton event if Enter key is pressed or if mouse is clicked.
public void actionPerformed(ActionEvent event) {

//Creating a semi-transparent red backgroud color to our testSubject panel
Color transparentRed = new Color (255, 0, 0, 25);
testSubject.setBackground(transparentRed);
}
}
);

//Implemeting Even-Listener on JButton using ActionListener
transparent.addActionListener(
new ActionListener() {

//Handle JButton event if Enter key is pressed or if mouse is clicked.
public void actionPerformed(ActionEvent event) {

//Set the background color to empty
testSubject.setBackground(null);
}
}
);

Specify JPanel size inside a JPanel which size is also being specified

Program Description:

This is another JPanel Demonstration which gives you the idea on how to specify a JPanel size inside another JPanel which size is also being specified. This is very useful if you are handling multiple panels with different sizes and again, layout plays a bigger role in manipulating JPanel size which mean you must know what layout to which panel. Knowing the boundery of your layout can help you create a very nice GUI Design. So I hope this topic can assist you.

Output:
Code:

/**
* File: jpanelSize2.java
* Tiltle: Specify JPanel size inside a JPanel which size is also being specified.
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class jpanelSize2 extends JFrame {

//Constructing JPanel Components
JPanel outer = new JPanel();
JPanel inner = new JPanel();

//Setting up GUI
public jpanelSize2() {

//Setting up the Title of the Window
super("Specify JPanel size inside a JPanel");

//Set Size of the Window (WIDTH, HEIGHT)
setSize(300,300);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Setting up the container layout
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
pane.setLayout(flow);

//Setting up the property of our inner panel
inner.setBorder(BorderFactory.createTitledBorder("Inner Panel (220,210) size"));
inner.setBackground(Color.yellow);
inner.setPreferredSize(new Dimension(220,210));

//Setting up the property of our outer panel
outer.setBorder(BorderFactory.createTitledBorder("Outer Panel (270,255) size"));
outer.setBackground(Color.cyan);
outer.setPreferredSize(new Dimension(270,255));

//Adding our inner panel inside outer panel
outer.add(inner);

//Adding outer panel to the container
pane.add(outer);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}

//Main Method
public static void main (String[] args) {
jpanelSize2 js2 = new jpanelSize2();
}
}

Important Part of the Program:

//Setting up the property of our inner panel
inner.setBorder(BorderFactory.createTitledBorder("Inner Panel (220,210) size"));
inner.setBackground(Color.yellow);
inner.setPreferredSize(new Dimension(220,210));

//Setting up the property of our outer panel
outer.setBorder(BorderFactory.createTitledBorder("Outer Panel (270,255) size"));
outer.setBackground(Color.cyan);
outer.setPreferredSize(new Dimension(270,255));

//Adding our inner panel inside outer panel
outer.add(inner);

Monday, April 16, 2012

Specify JPanel Size using the Class Dimension and the method setPreferredSize();

Program Description:

This is just a simple and short java program on how to set or customize JPanel size using the class Dimension and setPreferredSize(); method.

The program is very easy to understand and one of the important thing you need to remember is that customizing JPanel size depends on what layout you are going to use. In this program I am using FlowLayout because with FlowLayout, all the JComponents being added to the container are free in terms of length, width, and height meaning you can manipulate its size property easily unlike GridLayout, BoxLayout, CardLayout, and so on where the JComponent are being forced to fit in a certain size meaning JComponent size property manipulation is disabled.

So I hope this simple code can help. 100% runnable.

Output:
Code:

/**
* File: jpanelSize.java
* Tiltle: Specify JPanel Size
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class jpanelSize extends JFrame {

//Initializing JPanel
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();

//Setting up GUI
public jpanelSize() {

//Setting up the Title of the Window
super("Specify JPanel Size");

//Set Size of the Window (WIDTH, HEIGHT)
setSize(570,250);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Setting the layout of the container
pane.setLayout(new FlowLayout(FlowLayout.CENTER));

//Creating different JPanel sizes using the class Dimension and the method setPreferredSize()
panel1.setBorder(BorderFactory.createLineBorder(Color.black, 1));
panel1.setPreferredSize(new Dimension(200,200));
panel1.setBackground(Color.BLUE);

panel2.setBorder(BorderFactory.createLineBorder(Color.black, 1));
panel2.setPreferredSize(new Dimension(150,150));
panel2.setBackground(Color.CYAN);

panel3.setBorder(BorderFactory.createLineBorder(Color.black, 1));
panel3.setPreferredSize(new Dimension(100,100));
panel3.setBackground(Color.RED);

panel4.setBorder(BorderFactory.createLineBorder(Color.black, 1));
panel4.setPreferredSize(new Dimension(50,50));
panel4.setBackground(Color.GREEN);

//Adding all four JPanel in the container
pane.add(panel1);
pane.add(panel2);
pane.add(panel3);
pane.add(panel4);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}

//Main Method
public static void main (String[] args) {
jpanelSize js = new jpanelSize();
}
}

Important Part of the Program:

//Creating different JPanel sizes using the class Dimension and the method setPreferredSize()
panel1.setBorder(BorderFactory.createLineBorder(Color.black, 1));
panel1.setPreferredSize(new Dimension(200,200));
panel1.setBackground(Color.BLUE);

panel2.setBorder(BorderFactory.createLineBorder(Color.black, 1));
panel2.setPreferredSize(new Dimension(150,150));
panel2.setBackground(Color.CYAN);

panel3.setBorder(BorderFactory.createLineBorder(Color.black, 1));
panel3.setPreferredSize(new Dimension(100,100));
panel3.setBackground(Color.RED);

panel4.setBorder(BorderFactory.createLineBorder(Color.black, 1));
panel4.setPreferredSize(new Dimension(50,50));
panel4.setBackground(Color.GREEN);

Sunday, April 8, 2012

Creating a simple Progress Bar using JProgressBar

Program Description:

Today, I have created a simple progress bar program in Java using JProgressBar which consists of two separate programs/classes, the Main Program and the Plugin which is the progress bar property. The reason I separate these two classes is to understand the flow of the progress bar property easily which is our main objective in this project. So enjoy and leave some comments.

Output:
Code:

simpleProgressBar.java
/**
* File: simpleProgressBar.java
* Tiltle: Creating a Simple Progress Bar
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;

public class simpleProgressBar extends JFrame {

//Constructing JProgressBar and JButton
JProgressBar bar = new JProgressBar();
JButton button = new JButton("Test Progress Bar");

//Setting up GUI
public simpleProgressBar() {

//Setting up the Title of the Window
super("Creating a Simple Progress Bar");

//Set Size of the Window (WIDTH, HEIGHT)
setSize(350,100);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Display the progress bar completion percentage label
bar.setStringPainted(true);

//Setting up the container layout
GridLayout grid = new GridLayout(2,1);
pane.setLayout(grid);

//Adding the progress bar and the button to the container
pane.add(bar);
pane.add(button);

//Implemeting Even-Listener on JButton
button.addActionListener(
new ActionListener() {

//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
button.setEnabled(false); //Disable the JButton if the progress bar starts the progress
Thread run = new threadPlugin(bar); //Calling the class "threadPlugin" we created that extends with Thread
run.start(); //run the thread to start the progress
}
}
);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}

//Main Method
public static void main (String[] args) {
simpleProgressBar spb = new simpleProgressBar();
}
}

threadPlugin.java
/**
* File: threadPlugin.java
* Tiltle: Creating a Simple Progress Bar (PLUGIN)
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class threadPlugin extends Thread {

int Delay = 100; //Creating a delay or the speed of the progress bar
JProgressBar pb; //Constructing Progress Bar

//Creating a threadPlugin Method initializing JProgressBar so the Main Program "simpleProgressBar.java"
//can recognize by the time we call this class for JProgressBar action.
public threadPlugin(JProgressBar progressbar) {
pb = progressbar;
}

//run Method. This is the area where we can adjust the performance of our progress bar.
public void run() {
int minimum = pb.getMinimum(); //initializing minimum value of the progress bar
int maximum = pb.getMaximum(); //initializing maximum value of the progress bar

//Initializing Progress from its minimum value 0 to its maximum value 100
for (int i = minimum; i < maximum; i++) {
try {
int value = pb.getValue();
pb.setValue(value + 1);

//Testing the progress bar if it already reaches to its maximum value
if (pb.getValue() >= maximum) {

//Test confirmation if it runs perfectly
JOptionPane.showMessageDialog(null, "Test Successful!","Success!",JOptionPane.INFORMATION_MESSAGE);
}

Thread.sleep(Delay); //Implementing the speed of the progress bar
} catch (InterruptedException ignoredException) { //Catch an error if there is any
}
}
}
}

Wednesday, April 4, 2012

Adding Image above another Image using the class Toolkit and Graphics2D

Program Description:

Today I have created an easy and short Java program on how to add image above another image using the class Toolkit and Graphics2D. This technique is very useful in creating maps, games, applications that involve layers, and so on. There are many java programs out there which is similar to this but some of the programs contain codes and techniques that are hard to understand and some of them doesn't run, so I created this program to give you a more simple and easy way on how to put image above another image.

In this program, you will also learn how to link two programs that have different extensions.

Download: imageAboveAnotherImage.rar

Output:
Code:

Main Program (JFrame)

/**
* File: imageAboveAnotherImage.java
* Tiltle: Adding Image Above Another Image
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;

//Java Extension Package
import java.awt.*;

public class imageAboveAnotherImage extends JFrame {

//Initializing the class pluginExt
private pluginExt px;

//Setting up GUI
public imageAboveAnotherImage() {

//Setting up the Title of the Window
super("Adding Image Above Another Image");

//Set Size of the Window (WIDTH, HEIGHT)
setSize(455,540);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Constructing the class pluginExt
px = new pluginExt(this);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();

//Adding the class pluginExt in the container so it will be visible when running the program
pane.add(px);

//Setting up the content of the container using the class "pluginExt"
setContentPane(px);

//Lock the size of the window
setResizable(false);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);

}

//Main Method
public static void main(String[] args) {

imageAboveAnotherImage iaai = new imageAboveAnotherImage();

}
}

Extension Program (JPanel)

/**
* File: pluginExt.java
* Tiltle: Adding Image Above Another Image (class extention)
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;

//Java Extension Package
import java.awt.*;

public class pluginExt extends JPanel {

//Initializing the class "imageAboveAnotherImage"
imageAboveAnotherImage iaai;

//Initializing the images to be displayed
Image image1, image2, image3;

//Setting up GUI
public pluginExt(imageAboveAnotherImage iaai) {

//Constructing the class "Toolkit" which will be used to manipulate our images.
Toolkit kit = Toolkit.getDefaultToolkit();

//Getting all 3 images we have in the folder
image1 = kit.getImage("image1.jpg");
image2 = kit.getImage("image2.jpg");
image3 = kit.getImage("image3.gif");

}

//Manipulate Images with JAVA2D API. . creating a paintComponent method.
public void paintComponent(Graphics comp) {

//Constructing the class Graphics2D. Create 2D by casting the "comp" to Graphics2D
Graphics2D comp2D = (Graphics2D)comp;

//creating a graphics2d using the images in the folder and place them in a specific coordinates.
comp2D.drawImage(image1, 0, 0, this);
comp2D.drawImage(image2, 100, 150, this);
comp2D.drawImage(image3, 200, 350, this);

}
}