import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.net.URL;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
/**
* This program demonstrates GradientPaint and TexturePaint.
* This class has a main() routine and so can be run as an application.
* The static nested class PaintDemo.Applet runs the program as an applet.
*/
public class PaintDemo extends JPanel {
/**
* The main routine simply opens a window that shows a PaintDemo panel.
*/
public static void main(String[] args) {
JFrame window = new JFrame("PaintDemo - Drag the Vertices");
PaintDemo content = new PaintDemo();
window.setContentPane(content);
window.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screenSize.width - window.getWidth())/2,
(screenSize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
}
/**
* The public static class PaintDemo$Applet represents this program
* as an applet. The applet's init() method simply sets the content
* pane of the applet to be a PaintDemo. To use the applet on
* a web page, use code="PaintDemo$Applet.class" as the name of
* the class.
*/
public static class Applet extends JApplet {
public void init() {
PaintDemo content = new PaintDemo();
setContentPane( content );
}
}
/**
* The display area of the program shows a filled polygon that can be filled
* with various kinds of paint. The vertices of the polygon can be dragged
* by the user.
*/
private class Display extends JPanel implements MouseListener, MouseMotionListener {
int[] xcoord, ycoord;
int draggedPoint = -1;
Display() {
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400,300));
addMouseListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if (xcoord == null) {
xcoord = new int[] { scaleX(0.2), scaleX(0.8), scaleX(0.5),
scaleX(0.95), scaleX(0.35), scaleX(0.1) };
ycoord = new int[] { scaleY(0.15), scaleY(0.1), scaleY(0.5),
scaleY(0.45), scaleY(0.9), scaleY(0.7) };
}
g2.setPaint(paint);
g2.fillPolygon(xcoord, ycoord, 6);
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(2));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawPolygon(xcoord, ycoord, 6);
for (int i = 0; i < 6; i++)
g2.fillRect(xcoord[i] - 3, ycoord[i] - 3, 7, 7);
}
private int scaleX(double x) {
return (int)(x * getWidth());
}
private int scaleY(double y) {
return (int)(y * getHeight());
}
public void mousePressed(MouseEvent e) {
draggedPoint = -1;
for (int i = 0; i < 6; i++) {
if (Math.abs(xcoord[i] - e.getX()) < 4 && Math.abs(ycoord[i] - e.getY()) < 4) {
draggedPoint = i;
break;
}
}
}
public void mouseDragged(MouseEvent e) {
if (draggedPoint < 0)
return;
int x = Math.max(0, Math.min(e.getX(),getWidth()));
int y = Math.max(0, Math.min(e.getY(),getHeight()));
xcoord[draggedPoint] = x;
ycoord[draggedPoint] = y;
repaint();
}
public void mouseReleased(MouseEvent e) { }
public void mouseMoved(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
}
/**
* Responds when a use clicks on the radio button to set up the labels and sliders
* to correspond to the kind of paint that has been selected. Calls setPaint()
* to make the display use the new selected paint.
*/
private ActionListener buttonlistener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentButton = (JRadioButton)e.getSource();
slider1.removeChangeListener(sliderlistener); //(Yuck! Had to do this to avoid notifying
slider2.removeChangeListener(sliderlistener); // sliderListener when changes are made.)
if (currentButton == gradientButton1 || currentButton == gradientButton2) {
label1.setText(" Gradient Angle:");
label2.setText(" Gradient Width:");
slider1.setMinimum(0);
slider1.setMaximum(360);
slider1.setValue(gradientAngle);
slider2.setMinimum(10);
slider2.setMaximum(300);
slider2.setValue(gradientWidth);
}
else {
label1.setText(" Texture Offset:");
label2.setText(" Texture Scale:");
slider1.setMinimum(0);
slider1.setMaximum(100);
slider1.setValue(textureOffset);
slider2.setMinimum(25);
slider2.setMaximum(200);
slider2.setValue(textureScale);
}
slider1.addChangeListener(sliderlistener);
slider2.addChangeListener(sliderlistener);
setPaint();
}
};
/**
* When the user changes the value on one of the sliders, this
* ChangeListener responds by changing the Paint to reflect the
* changed value.
*/
private ChangeListener sliderlistener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
setPaint();
}
};
/**
* Called when the type of paint or the values on the sliders are changes, to
* create the new Paint and redraw the display to show the change.
*/
private void setPaint() {
if (currentButton == gradientButton1 || currentButton == gradientButton2) {
gradientAngle = slider1.getValue();
gradientWidth = slider2.getValue();
int x = getWidth()/2;
int y = getHeight()/2;
int dx = (int)( gradientWidth * Math.cos(gradientAngle/180.0 * Math.PI) );
int dy = (int)( gradientWidth * Math.sin(gradientAngle/180.0 * Math.PI) );
if (currentButton == gradientButton1)
paint = new GradientPaint(x,y,Color.LIGHT_GRAY,x+dx,y+dy,Color.BLACK,true);
else
paint = new GradientPaint(x,y,Color.RED,x+dx,y+dy,Color.YELLOW,true);
}
else {
textureOffset = slider1.getValue();
textureScale = slider2.getValue();
BufferedImage texture;
if (currentButton == textureButton1)
texture = smiley;
else
texture = queen;
int width = texture.getWidth() * textureScale / 100;
int height = texture.getHeight() * textureScale / 100;
int offsetX = width * textureOffset / 100;
int offsetY = height * textureOffset / 100;
Rectangle2D anchor = new Rectangle2D.Double(offsetX,offsetY,width,height);
paint = new TexturePaint(texture,anchor);
}
display.repaint();
}
private Display display = new Display(); // The display area where the polygon is drawn.
private Paint paint; // The paint that is used to fill the polygon in the display.
private BufferedImage smiley, queen; // Images for texture paint.
private JRadioButton gradientButton1, gradientButton2; // Select the type of paint.
private JRadioButton textureButton1, textureButton2;
private JRadioButton currentButton; // The currently selected radion button.
private int gradientAngle = 45, gradientWidth = 50; // Settings that affect the paint.
private int textureOffset = 0, textureScale = 100;
private JSlider slider1, slider2; // Sliders that control the settings; Which
// setting is affect depends on currrent paint type.
private JLabel label1 = new JLabel(" Gradient Angle:"); // Labels change, depending
private JLabel label2 = new JLabel(" Gradient Width:"); // on type of paint.
/**
* Constructor.
*/
public PaintDemo() {
setLayout(new BorderLayout(3,3));
setBorder(BorderFactory.createLineBorder(Color.GRAY,3));
setBackground(Color.GRAY);
add(display, BorderLayout.CENTER);
JPanel bottom = new JPanel();
bottom.setLayout(new GridLayout(0,2,5,5));
add(bottom, BorderLayout.SOUTH);
slider1 = new JSlider(0,360,gradientAngle);
slider1.addChangeListener(sliderlistener);
slider2 = new JSlider(10,300,gradientWidth);
slider2.addChangeListener(sliderlistener);
bottom.add(label1);
bottom.add(slider1);
bottom.add(label2);
bottom.add(slider2);
ButtonGroup group = new ButtonGroup();
gradientButton1 = new JRadioButton("Black/Gray Gradient");
gradientButton1.addActionListener(buttonlistener);
bottom.add(gradientButton1);
group.add(gradientButton1);
gradientButton1.setSelected(true);
currentButton = gradientButton1;
gradientButton2 = new JRadioButton("Red/Yellow Gradient");
gradientButton2.addActionListener(buttonlistener);
bottom.add(gradientButton2);
group.add(gradientButton2);
setPaint();
try {
ClassLoader cl = PaintDemo.class.getClassLoader();
URL imageURL = cl.getResource("TinySmiley.png");
if (imageURL != null)
smiley = ImageIO.read(imageURL);
imageURL = cl.getResource("QueenOfHearts.png");
queen = ImageIO.read(imageURL);
}
catch (Exception e) {
return; // Can't load the images, so don't add the texture radion buttons.
}
textureButton1 = new JRadioButton("Smiley Face");
textureButton1.addActionListener(buttonlistener);
bottom.add(textureButton1);
group.add(textureButton1);
textureButton2 = new JRadioButton("Queen Of Hearts");
textureButton2.addActionListener(buttonlistener);
bottom.add(textureButton2);
group.add(textureButton2);
}
}
24 July 2014
Paint program
19 July 2014
Database Connect
Practice with DataBase Connection
import java.sql.*;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
*
* @author Manish
*/
public class DBConnect {
public Connection con;
public Statement st;
public ResultSet rs;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // for Ms Access
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/details","root","");
con = DriverManager.getConnection("jdbc:odbc:demo");
st = con.createStatement();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Error:"+ex,"Error Box",JOptionPane.ERROR_MESSAGE);
}
}
public int getData(int getroll, String getpass ){
int value=0;
try {
String query = "Select * from students where Roll="+getroll+" and Password='"+getpass+"'";
rs= st.executeQuery(query);
while(rs.next()){
value= rs.getInt("Roll");
}
}
catch (Exception e) {
}
finally{
try{ rs.close();
st.close();
}catch(Exception ex){
}
return value;
}
}
public String getAdminData(String getID, String getpass ){
String value=null;
try {
String query = "Select * from admin where ID='"+getID+"' and Password='"+getpass+"'";
rs= st.executeQuery(query);
while(rs.next()){
value= rs.getString("ID");
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error:"+e);
}
finally{
try{ rs.close();
st.close();
}
catch(Exception ex){
}
return value;
}
}
}
import java.sql.*;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
*
* @author Manish
*/
public class DBConnect {
public Connection con;
public Statement st;
public ResultSet rs;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // for Ms Access
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/details","root","");
con = DriverManager.getConnection("jdbc:odbc:demo");
st = con.createStatement();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Error:"+ex,"Error Box",JOptionPane.ERROR_MESSAGE);
}
}
public int getData(int getroll, String getpass ){
int value=0;
try {
String query = "Select * from students where Roll="+getroll+" and Password='"+getpass+"'";
rs= st.executeQuery(query);
while(rs.next()){
value= rs.getInt("Roll");
}
}
catch (Exception e) {
}
finally{
try{ rs.close();
st.close();
}catch(Exception ex){
}
return value;
}
}
public String getAdminData(String getID, String getpass ){
String value=null;
try {
String query = "Select * from admin where ID='"+getID+"' and Password='"+getpass+"'";
rs= st.executeQuery(query);
while(rs.next()){
value= rs.getString("ID");
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error:"+e);
}
finally{
try{ rs.close();
st.close();
}
catch(Exception ex){
}
return value;
}
}
}
15 July 2014
Copy one file to another - An example
// Copies one file into another. The names of both files must
// be specified on the command line.
import java.io.*;
public class CopyFile {
public static void main(String[] args) {
// Terminate program if number of command-line arguments
// is wrong
if (args.length != 2) {
System.out.println("Usage: java CopyFile source dest");
System.exit(-1);
}
try {
// Open source file for input and destination file for
// output
FileInputStream source = new FileInputStream(args[0]);
FileOutputStream dest = new FileOutputStream(args[1]);
// Set up a 512-byte buffer
byte[] buffer = new byte[512];
// Copy bytes from the source file to the destination
// file, 512 bytes at a time
while (true) {
int count = source.read(buffer);
if (count == -1)
break;
dest.write(buffer, 0, count);
}
// Close source and destination files
source.close();
dest.close();
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
} catch (IOException e) {
System.out.println("I/O error during copy");
}
}
}
11 July 2014
Client code Chat software
Now the Client code for our chat software compile it and run only after server code
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import java.io.*;
class Clientnode
{
JButton sendbutton;
BufferedReader reader;
PrintWriter writer;
JTextField outgoing;
JTextArea incoming;
JTextField user;
public Clientnode() // constructor of outer class(creates the GUI interface)....
{
JFrame frame = new JFrame("CHATCLIENT");
JPanel mainpanel = new JPanel();
JLabel name = new JLabel("USERNAME");
user = new JTextField(20);
incoming = new JTextArea(10,30);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
outgoing = new JTextField(30);
sendbutton = new JButton("SEND");
JScrollPane scroller = new JScrollPane(incoming);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
mainpanel.add(name);
mainpanel.add(user);
mainpanel.add(scroller);
mainpanel.add(outgoing);
mainpanel.add(sendbutton);
sendbutton.addActionListener(new Write());
frame.getContentPane().add(BorderLayout.CENTER,mainpanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
connect(); // method connect() called..
Thread readingthread = new Thread(new Reading()); // creates a new Thread Object...
readingthread.start(); // starts the new Thread(calls the run() method )...
frame.setSize(400,310);
frame.setVisible(true);
}
class Reading implements Runnable // inner class implementing Runnable interface
{ // (the new thread class)
public void run() // the overridden run() method (what the new thread does.. )
{
String message;
try
{
while((message = reader.readLine()) != null)
{
System.out.println("read"+message);
incoming.append(message+"\n");
}
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
}
class Write implements ActionListener // inner class(implementing ActionListener interface)
{ // for the send button
public void actionPerformed(ActionEvent a) // the overridden actionperformed() method
{ // (called when the button clicks)for writing to the server
try
{
//user.getText().setColor(Color.blue);
writer.println(user.getText()+" - "+outgoing.getText());
System.out.println(outgoing.getText());
writer.flush();
}
catch(Exception ex)
{
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
void connect() // method for establishing a connection with the server
{
try
{
Socket clientsocket = new Socket("127.0.0.1",4000); // requesting the local host(127.0.0.1),port no.4000
// for connection and creating
// chained streams for reading
// and writing to the socket.
InputStreamReader isr = new InputStreamReader(clientsocket.getInputStream());
reader = new BufferedReader(isr);
writer = new PrintWriter(clientsocket.getOutputStream());
System.out.println("connected");
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] a) // the main() method
{
Clientnode cn = new Clientnode(); // creating an object of Clientnode class(constructor called)
}
}
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import java.io.*;
class Clientnode
{
JButton sendbutton;
BufferedReader reader;
PrintWriter writer;
JTextField outgoing;
JTextArea incoming;
JTextField user;
public Clientnode() // constructor of outer class(creates the GUI interface)....
{
JFrame frame = new JFrame("CHATCLIENT");
JPanel mainpanel = new JPanel();
JLabel name = new JLabel("USERNAME");
user = new JTextField(20);
incoming = new JTextArea(10,30);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
outgoing = new JTextField(30);
sendbutton = new JButton("SEND");
JScrollPane scroller = new JScrollPane(incoming);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
mainpanel.add(name);
mainpanel.add(user);
mainpanel.add(scroller);
mainpanel.add(outgoing);
mainpanel.add(sendbutton);
sendbutton.addActionListener(new Write());
frame.getContentPane().add(BorderLayout.CENTER,mainpanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
connect(); // method connect() called..
Thread readingthread = new Thread(new Reading()); // creates a new Thread Object...
readingthread.start(); // starts the new Thread(calls the run() method )...
frame.setSize(400,310);
frame.setVisible(true);
}
class Reading implements Runnable // inner class implementing Runnable interface
{ // (the new thread class)
public void run() // the overridden run() method (what the new thread does.. )
{
String message;
try
{
while((message = reader.readLine()) != null)
{
System.out.println("read"+message);
incoming.append(message+"\n");
}
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
}
class Write implements ActionListener // inner class(implementing ActionListener interface)
{ // for the send button
public void actionPerformed(ActionEvent a) // the overridden actionperformed() method
{ // (called when the button clicks)for writing to the server
try
{
//user.getText().setColor(Color.blue);
writer.println(user.getText()+" - "+outgoing.getText());
System.out.println(outgoing.getText());
writer.flush();
}
catch(Exception ex)
{
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
void connect() // method for establishing a connection with the server
{
try
{
Socket clientsocket = new Socket("127.0.0.1",4000); // requesting the local host(127.0.0.1),port no.4000
// for connection and creating
// chained streams for reading
// and writing to the socket.
InputStreamReader isr = new InputStreamReader(clientsocket.getInputStream());
reader = new BufferedReader(isr);
writer = new PrintWriter(clientsocket.getOutputStream());
System.out.println("connected");
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] a) // the main() method
{
Clientnode cn = new Clientnode(); // creating an object of Clientnode class(constructor called)
}
}
10 July 2014
Chat software
Here is the server side code for chat software just copy it down and compile and run
import java.util.*;
import java.net.*;
import java.io.*;
class Server // outer class
{
PrintWriter writer;
ArrayList clientoutputstreams; // an Arraylist in which we keep adding writers of different clients
Socket clientsocket;
void go() // go() method which is called in main() method...
{
clientoutputstreams = new ArrayList();
try
{
ServerSocket ss = new ServerSocket(4000); // creating a Server at port no. 4000
while(true) // an infinite loop for accepting connection requests as
{ // long as the program is running..
clientsocket = ss.accept(); // accept() method which returns a Socket for communication
System.out.println(clientsocket);
System.out.println("clientsocket");
writer = new PrintWriter(clientsocket.getOutputStream());
clientoutputstreams.add(writer);
Thread t = new Thread(new Clienthandler(clientsocket)); // a new Thread object created and the Thread is
t.start(); // started whenever a request is accepted....
}
}
catch(Exception e)
{e.printStackTrace();}
}
class Clienthandler implements Runnable // an inner class that implements Runnable interface
{ // making it a Thread class
Socket sock;
BufferedReader reader;
public Clienthandler(Socket clientsocket) // constructor of the inner Thread class that takes the
{ // Socket(returned by accept() method) as argument
// and creates a buffered reader for each client..
try
{
InputStreamReader isr = new InputStreamReader(clientsocket.getInputStream());
reader = new BufferedReader(isr);
}
catch(Exception Ex)
{Ex.printStackTrace();}
}
public void run() // the overridden run() method(what happens in
{ // the new Thread)
String message;
try
{
while((message = reader.readLine()) != null) // reads from each client text until it is null
{ // and stores it in String object 'message'
System.out.println(message);
writeToAll(message); // writeToAll() method called...
}
}
catch(Exception f)
{f.printStackTrace();}
}
} // inner class ends...
public void writeToAll(String message) // writeToAll() method takes the read texts
{ // from all clients,i.e.'message' and writes it to
Iterator it = clientoutputstreams.iterator(); // all the connected clients
while(it.hasNext())
{
try
{
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
System.out.print(message);
writer.flush();
}
catch(Exception c)
{c.printStackTrace();}
}
}
public static void main(String[] man) // main() method
{ // creates an object of Server class and calls
Server s = new Server(); // its go() method...
s.go();
}
} // outer class ends...
07 July 2014
File Handling in Java
File Handling
import java.io.*;
/**
*
* @author Manish Kumar
*/
public class ByteFileInp {
public static void main(String Mad[]){
try{
FileOutputStream
fout = new FileOutputStream("man.txt",true);
String
msz="Today you r cele";
byte arr[]=
msz.getBytes();
fout.write(arr);
fout.close();
FileInputStream finp = new FileInputStream("man.txt");
byte data[]
= new byte[finp.available()];
finp.read(data);
String str =
new String(data);
System.out.println(str);
finp.close();
}
catch(Exception e){
System.err.println("Error is Here"+e);
}
}
}
Another Program
import java.io.*;
class FileHand
{
public static void
main(String args[]){
try{
FileOutputStream
fout = new FileOutputStream("hello Manish",false);
String
msz="Today you r celebrating 68th Independence Day";
byte arr[]=
msz.getBytes();
fout.write(arr);
fout.close();
}
catch(Exception e){
System.out.println("Manish You Have Error");
}
}
}
04 July 2014
Layout mangers
Layout mangers
Layout manager is used to layout (or arrange) the GUI components inside a container.There are many layout managers , but the most frequently used are-
BorderLayout
A BorderLayout places components in up to five areas: top, bottom, left, right, and center. It is the default layout manager for every JFrame
java-border-layout-manager
FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row one after the other.
java-flow-layout-manager
GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing components to span more than one cell.
java-grid-bag-layout
Step 8) How about creating a chat frame like below.
java-swing-chat-frame
//Usually you will require both swing and awt packages
// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui{
public static void main(String args[]){
//Creating the Frame
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
//Creating the MenuBar and adding components
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 =new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);
//Creating the panel at bottom and adding components
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10);// accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label);// Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);
// Text Area at the Center
JTextArea ta = new JTextArea();
//Adding Components to the frame.
frame.getContentPane().add(BorderLayout.SOUTH,panel);
frame.getContentPane().add(BorderLayout.NORTH,mb);
frame.getContentPane().add(BorderLayout.CENTER,ta);
frame.setVisible(true);
}
}
Layout manager is used to layout (or arrange) the GUI components inside a container.There are many layout managers , but the most frequently used are-
BorderLayout
A BorderLayout places components in up to five areas: top, bottom, left, right, and center. It is the default layout manager for every JFrame
java-border-layout-manager
FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row one after the other.
java-flow-layout-manager
GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing components to span more than one cell.
java-grid-bag-layout
Step 8) How about creating a chat frame like below.
java-swing-chat-frame
//Usually you will require both swing and awt packages
// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui{
public static void main(String args[]){
//Creating the Frame
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
//Creating the MenuBar and adding components
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 =new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);
//Creating the panel at bottom and adding components
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10);// accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label);// Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);
// Text Area at the Center
JTextArea ta = new JTextArea();
//Adding Components to the frame.
frame.getContentPane().add(BorderLayout.SOUTH,panel);
frame.getContentPane().add(BorderLayout.NORTH,mb);
frame.getContentPane().add(BorderLayout.CENTER,ta);
frame.setVisible(true);
}
}
Subscribe to:
Posts (Atom)