Академический Документы
Профессиональный Документы
Культура Документы
In this section, you will learn how to sum of a number using swing. JTextField, JButton
is a component of GUI.
1. JFrame is used to creating java standalone application, you must provide GUI for a
user. The most common way of creating a frame is,
using single argument constructor of the JFrame class. The argument of the constructor
is the title of the window or frame.
JFrame f = new JFrame("Calculate");
2. JTextField is a lightweight component that allows the editing of a single line of text.
JTextField has a method to establish the string
used as the command string for the action event that gets fired. The java.awt.TextField
used the text of the field as the command string
or the ActionEvent. JTextField will use the command string set with the
setActionCommand method if not null, otherwise it will use the
text of the field as a compatibility with java.awt.TextField.
final JTextField text1 = new JTextField(20);
final JTextField text2 = new JTextField(20);
3. JButton with a String as a label, and then drop it in a window. Events are normally
handled just as with a Button: you attach an
ActionListener via the addActionListener method.
JButton button = new JButton("Calculate");
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculate extends JTextField {
public static void main(String[] args) {
JFrame f = new JFrame("Calculate");
f.getContentPane().setLayout(new BoxLayout(f.getContentPane(),
BoxLayout.Y_AXIS));
final JTextField text1 = new JTextField(20);
final JTextField text2 = new JTextField(20);
Page 1 of 8
LIAT,Rajagiriy Swing Examples
JPanel panel = new JPanel();
JButton button = new JButton("Calculate");
panel.add(button);
f.getContentPane().add(text1);
f.getContentPane().add(panel);
f.getContentPane().add(text2);
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Action event from a text field");
}
};
text1.addActionListener(l);
text2.addActionListener(l);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int a=Integer.parseInt(text1.getText());
int sum = 0;
int count=1;
while(count<=a)
{
sum+=count;
count++;
}
text2.setText(String.valueOf(sum));
}
});
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output :
Page 2 of 8
LIAT,Rajagiriy Swing Examples
In the LoginDemo.java, we have create two text fields text1 and text2 to set the text for
username and password. A button is created to perform an action. The method
text1.getText() get the text of username and the method text2.getText() get the text of
password which the user enters. Then we have create a condition that if the value of text1
and text2 is roseindia, the user will enter into the next page on clicking the submit button.
The NextPage.java is created to move the user to the next page. In case if the user enters
the invalid username and password , the class JOptionPane provides the MessageDialog
to shows the error message.
import javax.swing.*;
import java.awt.*;
class NextPage extends JFrame
{
NextPage()
{
setDefaultCloseOperation(jav
ax.swing.
WindowConstants.DISPOSE_ON_CLOSE)
;
setTitle("Welcome");
setSize(400, 200);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Login extends JFrame implements ActionListene
r
{
JButton SUBMIT;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
Login()
{
label1 = new JLabel();
Page 3 of 8
LIAT,Rajagiriy Swing Examples
label1.setText("Username:");
text1 = new JTextField(15);
label2 = new JLabel();
label2.setText("Password:");
text2 = new JPasswordField(15);
SUBMIT=new JButton("SUBMIT");
panel=new JPanel(new GridLayout(3,1));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(SUBMIT);
add(panel,BorderLayout.CENTER);
SUBMIT.addActionListener(this);
setTitle("LOGIN FORM");
}
public void actionPerformed(ActionEvent ae)
{
String value1=text1.getText();
String value2=text2.getText();
if (value1.equals("roseindia") && value2.eq
uals("roseindia")) {
NextPage page=new NextPage();
page.setVisible(true);
JLabel label = new JLabel("Welcome:"+value1);
page.getContentPane().add(label);
}
else{
System.out.println("enter the valid username
and password");
JOptionPane.showMessageDialog(this,"Incorrect
login or password",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
class LoginDemo
{
public static void main(String arg[])
{
try
{
Login frame=new Login();
frame.setSize(300,100);
frame.setVisible(true);
}
catch(Exception e)
{JOptionPane.showMessageDialog(null, e.getMessa
ge());}
}
}
Page 4 of 8
LIAT,Rajagiriy Swing Examples
In this section, you will learn how to create chess game in java swing.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ChessGameDemo extends JFrame implements MouseListener, Mous
eMotionListener {
JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
Page 5 of 8
LIAT,Rajagiriy Swing Examples
int xAdjustment;
int yAdjustment;
public ChessGameDemo(){
Dimension boardSize = new Dimension(600, 600);
// Use a Layered Pane for this this application
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
layeredPane.addMouseMotionListener(this);
//Add a chess board to the Layered Pane
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout( new GridLayout(8, 8) );
chessBoard.setPreferredSize( boardSize );
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel( new BorderLayout() );
chessBoard.add( square );
int row = (i / 8) % 2;
if (row == 0)
square.setBackground( i % 2 == 0 ? Color.blue : Color.wh
ite );
else
square.setBackground( i % 2 == 0 ? Color.white : Color.b
lue );
}
//Add a few pieces to the board
JLabel piece = new JLabel( new ImageIcon("/home/vinod/amarexampl
es/chess.jpg") );
JPanel panel = (JPanel)chessBoard.getComponent(0);
panel.add(piece);
piece = new JLabel(new ImageIcon("/home/vinod/amarexamples/chess
1.jpg"));
panel = (JPanel)chessBoard.getComponent(15);
panel.add(piece);
piece = new JLabel(new ImageIcon("/home/vinod/amarexamples/king.
jpg"));
panel = (JPanel)chessBoard.getComponent(16);
panel.add(piece);
piece = new JLabel(new ImageIcon("/home/vinod/amarexamples/camel.jpg")
);
panel = (JPanel)chessBoard.getComponent(20);
panel.add(piece);
}
Page 6 of 8
LIAT,Rajagiriy Swing Examples
public void mousePressed(MouseEvent e){
chessPiece = null;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel)
return;
Point parentLocation = c.getParent().getLocation();
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
chessPiece = (JLabel)c;
chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjus
tment);
chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight()
);
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
}
//Move the chess piece around
public void mouseDragged(MouseEvent me) {
if (chessPiece == null) return;
chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAd
justment);
}
//Drop the chess piece back onto the chess board
public void mouseReleased(MouseEvent e) {
if(chessPiece == null) return;
chessPiece.setVisible(false);
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JLabel){
Container parent = c.getParent();
parent.remove(0);
parent.add( chessPiece );
}
else {
Container parent = (Container)c;
parent.add( chessPiece );
}
chessPiece.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e) {
Page 7 of 8
LIAT,Rajagiriy Swing Examples
}
public static void main(String[] args) {
JFrame frame = new ChessGameDemo();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE );
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
Page 8 of 8