import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
//import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
class Rectangle extends JPanel {
private static int rect_x = 40;
private static int rect_y = 40;
private static final int rect_width = 100;
private static final int rect_height = rect_width;
KeyListener listener;
public Rectangle() {
this.listener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
//System.out.println(e.getKeyCode());
// w
if(e.getKeyCode() == 87)
{
rect_y -= 10;
//revalidate();
repaint();
}
// s
else if (e.getKeyCode() == 83)
{
rect_y += 10;
repaint();
}
// a
else if (e.getKeyCode() == 65)
{
rect_x -= 10;
repaint();
}
// d
else if (e.getKeyCode() == 68)
{
rect_x += 10;
repaint();
}
}
#Override
public void keyReleased(KeyEvent e)
{
}
}; }
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawRect(rect_x, rect_y, rect_width, rect_height);
g.fillRect(rect_x, rect_y, rect_width, rect_height);
g.setColor(Color.BLACK);
}
#Override
public Dimension getPreferredSize() {
// so that our GUI is big enough
return new Dimension(rect_width + 2 * rect_x, rect_height + 2 * rect_y);
}
// create the GUI explicitly on the Swing event thread
private void createAndShowGui() {
Rectangle mainPanel = new Rectangle();
JFrame frame = new JFrame("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addKeyListener(listener);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Rectangle Rct = new Rectangle();
Rct.createAndShowGui();
}
});
}
}
this code is meant to move a rectangle across the screen.
For some reason it does not update unless the window is minimised or resized.
I realise this has been asked many times before, but the answers I have found were very case specific or above my understanding.
I am new to java so sorry if I seem like a blockhead.
You're creating an Extra Rectangle object, and calling repaint() on it, and this is not the displayed object, and so your listener does not repaint the displayed JPanel. Don't do this. Only create one Rectangle object, so your repaints go to the correct reference.
e.g., change this:
Rectangle mainPanel = new Rectangle(); // ***** no!!! ****
JFrame frame = new JFrame("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel); // **** no ****
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addKeyListener(listener);
to this:
// Rectangle mainPanel = new Rectangle();
JFrame frame = new JFrame("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(this); // ****** note change
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addKeyListener(listener);
Other side issues:
Prefer Key Bindings to a KeyListener
Avoid magic numbers such as your key code numbers, which make debugging difficult. Instead use the KeyEvent.VK_? constants.
Follow Java naming conventions: constants should be all upper-case.
Your rect_x and y fields should not be static.
Related
I am doing a java assignment for next Saturday.
Its going really well, however I'm struggling with one section.
Here I want to reveal a set of numbers in a String, one at a time.
I tried slowing down the loop with 'Thread.sleep(1000);'
however nothing is displaying until the thread is finished
the following is a section of the graphics class where the problem is occuring
is there something I'm missing?
public void paint(Graphics g)
{
setSize(550, 300);
//this draws all the random numbers, revealing the ans to the user
if (revealNum == 0)
{
g.setColor(Color.BLUE);
g.drawString(randomNumber, 20, 20); //draw String ("the String", x, y)
}
//this reveals the numbers 1 by 1 to the user at the start of the game
if (revealNum==1)
{
for (int x = 0; x < limit; x++)
{
g.setColor(Color.BLUE);
g.drawString(""+x, 20, 20); //draw String ("the String", x, y)
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
System.out.print("Error");
}
repaint();
}
//slow down the loop to show the user
}
Since yours is a GUI, calling Thread.sleep will put the entire app to sleep. Instead use a Swing Timer. Inside the Timer's ActionListener, add another letter to the displayed String, and then stop the Timer via the stop() method once the String is complete.
e.g.,
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class SimpleAnimation extends JPanel {
public static final int TIMER_DELAY = 1000;
private JTextField textField = new JTextField(10);
private JLabel displayLabel = new JLabel("", SwingConstants.CENTER);
public SimpleAnimation() {
Action btnAction = new DoItBtnAction("Do It!", KeyEvent.VK_D);
JPanel topPanel = new JPanel();
topPanel.add(textField);
topPanel.add(new JButton(btnAction));
textField.addActionListener(btnAction);
setLayout(new GridLayout(2, 1));
add(topPanel);
add(displayLabel);
}
private class DoItBtnAction extends AbstractAction {
private String textFieldText = "";
public DoItBtnAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
displayLabel.setText("");
setEnabled(false);
textFieldText = textField.getText();
new Timer(TIMER_DELAY, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (i >= textFieldText.length()) {
((Timer) e.getSource()).stop();
DoItBtnAction.this.setEnabled(true);
} else {
displayLabel.setText(displayLabel.getText() + textFieldText.charAt(i));
i++;
}
}
}).start();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SimpleAnimation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SimpleAnimation());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Also,
If yours is a Swing GUI, it would be easier to display your text in a JLabel or a JTextField rather than trying to paint it on the GUI.
If this is Swing, don't override paint(Graphics g) but rather the paintComponent(Graphics g) method of a JPanel or JComponent.
You should use a javax.swing.Timer
Here is an example
JLabel l = ...;
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (l.getText().equals("1")) l.setText("2");
else if (l.getText().equals("2)) l.setText("1");
}
});
I need a little help with java, I am new to the language hence I have no idea on how to implement such.
I have already made a basic 15;40 grid JLabel Image, thanks to this site as well, what I need help with is about how to make a player(Supposed to be an Image, also shown on the grid) move around using either WASD(I don't know if Ascii-approach works on java) or Arrow Keys.
Here's my code for the Grid
public class GUI {
static Scanner cns = new Scanner(System.in);
JFrame frame = new JFrame();
ImageIcon ImageIcon = new ImageIcon("Grass.png");
JLabel[][] grid;
public GUI(int width, int length) {
Container pane = frame.getContentPane();
frame.setLayout(new GridLayout(width,length));
grid = new JLabel[width][length];
for(int y = 0; y < length; y++) {
for(int x = 0; x < width; x++) {
grid[x][y] = new JLabel();
grid[x][y].setBorder(BorderFactory.createLineBorder(Color.black));
grid[x][y].setBorder(BorderFactory.createEmptyBorder());
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
for(int y = 0; y < length; y++) {
for(int x = 0; x < width; x++) {
pane.add(grid[x][y]= new JLabel(new ImageIcon("Grass.png")));
grid[x][y].setBorder(BorderFactory.createLineBorder(Color.black));
grid[x][y].setBorder(BorderFactory.createEmptyBorder());
frame.add(grid[x][y]);
}
}
}
public static void main(String[] args) {
new GUI(15, 40);
}
}
Couple of suggestions here:
1 - Make GUI extend JFrame and implement KeyListener.
You have to override KeyListener methods (keyPressed, keyReleased, and keyTyped) and you should override repaint() from JFrame.
The repaint method should call super.repaint() at the end to update frames.
2 - Have the fields of GUI store data about the things that need to be drawn.
You probably should store the grid, or what's in the grid as fields.
3 - The constructor should initialize, not render.
Rendering should be done in repaint(). The constructor should do something like this:
super();
JPanel frame = new JPanel();
add(frame);
pack();
addKeyListener(this);
repaint();
This answer is kinda unfinished but I'll look more into it and update this. Particularly, the JPanel is an element in the JFrame.
UPDATE: Here is a small working example. Use WASD to move the rectangle around the screen.
This is the JFrame.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class MyJFrame extends JFrame implements KeyListener {
private MyJPanel frame;
public MyJFrame() {
super();
frame = new MyJPanel();
add(frame);
pack();
addKeyListener(this);
repaint();
}
public static void main(String[] args) {
MyJFrame window = new MyJFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setTitle("Test");
}
#Override
public void repaint() {
super.repaint();
}
#Override
public void keyPressed(KeyEvent e) {
frame.keyPressed(e);
repaint();
}
#Override
public void keyTyped(KeyEvent e) { }
#Override
public void keyReleased(KeyEvent e) { }
}
This is the JPanel.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
public class MyJPanel extends JPanel {
private int x = 0;
private int y = 0;
public MyJPanel() {
setPreferredSize(new Dimension(200,200));
}
#Override
public void update(Graphics g) {
paint(g);
}
#Override
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect(x,y,20,20);
}
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
switch (k) {
case KeyEvent.VK_D:
x++;
break;
case KeyEvent.VK_A:
x--;
break;
case KeyEvent.VK_W:
y--;
break;
case KeyEvent.VK_S:
y++;
break;
}
}
}
Good luck!
There is a Canvas object in my game and this object is not set in focus, because of this my snake is not moving on the Board .
Basically i am working on snake game project, and i want is when play button is clicked from PlayGame.java JDialog ,game should start ,but problem i am facing is after clicking button gamescreen appearing on window but snake is not moving, so someone suggest me that your canvas object is not in focus whenever it is called.
that is why KeyLisener not able to listen to keyPresses /key strokes.
This is the class in which canvas object is declared and implemented.
package org.psnbtech;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import org.psnbtech.GameBoard.TileType;
import org.psnbtech.Snake.Direction;
public class Engine extends KeyAdapter {
private static final int UPDATES_PER_SECOND = 15;
private static final Font FONT_SMALL = new Font("Arial", Font.BOLD, 20);
private static final Font FONT_LARGE = new Font("Arial", Font.BOLD, 40);
public Canvas canvas;
public GameBoard board;
public Snake snake;
public int score;
public boolean gameOver;
public Engine(Canvas canvas) {
this.canvas = canvas;
this.board = new GameBoard();
this.snake = new Snake(board);
resetGame();
canvas.addKeyListener(this);
//new Engine(canvas).startGame();
}
public void startGame() {
canvas.createBufferStrategy(2);
Graphics2D g = (Graphics2D)canvas.getBufferStrategy().getDrawGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
long start = 0L;
long sleepDuration = 0L;
while(true) {
start = System.currentTimeMillis();
update();
render(g);
canvas.getBufferStrategy().show();
g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
sleepDuration = (1500L / UPDATES_PER_SECOND) - (System.currentTimeMillis() - start);
if(sleepDuration > 0) {
try {
Thread.sleep(sleepDuration);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
public void update() {
if(gameOver || !canvas.isFocusable()) {
return;
}
TileType snakeTile = snake.updateSnake();
if(snakeTile == null || snakeTile.equals(TileType.SNAKE)) {
gameOver = true;
} else if(snakeTile.equals(TileType.FRUIT)) {
score += 10;
spawnFruit();
}
}
public void render(Graphics2D g) {
board.draw(g);
g.setColor(Color.WHITE);
if(gameOver) {
g.setFont(FONT_LARGE);
String message = new String("Your Score: " + score);
g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 250);
g.setFont(FONT_SMALL);
message = new String("Press Enter to Restart the Game");
g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 350);
} else {
g.setFont(FONT_SMALL);
g.drawString("Score:" + score, 10, 20);
}
}
public void resetGame() {
board.resetBoard();
snake.resetSnake();
score = 0;
gameOver = false;
spawnFruit();
}
public void spawnFruit() {
int random = (int)(Math.random() * ((GameBoard.MAP_SIZE * GameBoard.MAP_SIZE) - snake.getSnakeLength())); // if '*' replace by '/' then only one fruit is there for snake
int emptyFound = 0;
int index = 0;
while(emptyFound < random) {
index++;
if(board.getTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE).equals(TileType.EMPTY)) { // if '/' replaced by '*' then nothing displays on the board
emptyFound++;
}
}
board.setTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE, TileType.FRUIT); // it also show nothing when replacing '/' by '/'
}
#Override
public void keyPressed(KeyEvent e) {
if((e.getKeyCode() == KeyEvent.VK_UP)||(e.getKeyCode() == KeyEvent.VK_W)) {
snake.setDirection(Direction.UP);
}
if((e.getKeyCode() == KeyEvent.VK_DOWN)||(e.getKeyCode() == KeyEvent.VK_S)) {
snake.setDirection(Direction.DOWN);
}
if((e.getKeyCode() == KeyEvent.VK_LEFT)||(e.getKeyCode() == KeyEvent.VK_A)) {
snake.setDirection(Direction.LEFT);
}
if((e.getKeyCode() == KeyEvent.VK_RIGHT)||(e.getKeyCode() == KeyEvent.VK_D)) {
snake.setDirection(Direction.RIGHT);
}
if(e.getKeyCode() == KeyEvent.VK_ENTER && gameOver) {
resetGame();
}
}
public static void main(String[] args) {
new PlayGame().setVisible(true);
/**JFrame frame = new JFrame("SnakeGame");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setResizable(false);
Canvas canvas = new Canvas();
canvas.setBackground(Color.black);
canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
frame.getContentPane().add(canvas);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Engine(canvas).startGame();*/
}
}
And also i am attching actionPerformed() method of Play Button where i am referring canvas object
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFrame frame = new JFrame("SnakeGame");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setResizable(false);
Canvas canvas = new Canvas();
canvas.setBackground(Color.black);
canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE *GameBoard.TILE_SIZE,GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
frame.add(canvas);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Engine(canvas).startGame();
}
So please tell/suggest me how can i set canvas object in focus.
Suggestions from someone who has been there:
Your focus problem is really an XY problem.
Instead you should not mix AWT (Canvas) and Swing (JFrame) components but instead should stick with all-Swing components
Use Key Bindings instead of a KeyListener and your focus problems will just melt away.
Do your drawing in a JPanel's paintComponent(...) method as per this tutorial.
Do not override the update method for Swing apps.
So the objective (well the starting point anyway) of this program is to press the arrow keys and have bullets come from the middle of the screen in the direction of the arrow. I have four images of bullets I created in paint and am using these two classes:
this is the class that creates and organizes the bullets:
public class BulletAnimator extends JPanel implements ActionListener
{
int startX,startY;
boolean yAxis = false;
boolean xAxis = false;
Timer animator;
String direction;
public BulletAnimator(int sX, int sY, String d)
{
direction = d;
startX = sX;
startY = sY;
animator = new Timer (10, this);
animator.start();
}
//chooses the right picture for the right direction
public ImageIcon chooseBulletPicture ()
{
String path = "bullet";
if (direction.equals("left"))
path += "LEFT";
else if (direction.equals ("right"))
path += "RIGHT";
else if (direction.equals ("up"))
path += "UP";
else
path += "DOWN";
path += ".png";
ImageIcon b= new ImageIcon (path);
return b;
}
public void paintComponent (Graphics g)
{
super. paintComponent(g);
if (startX >= 500 || startY >= 500)
animator.stop();
if (direction.equals ("up"))
startY -=2;
else if (direction.equals ("down"))
startY +=2;
else if (direction.equals ("right"))
startX += 2;
else
startX -=2;
chooseBulletPicture().paintIcon (this, g, startX, startY);
}
public void actionPerformed(ActionEvent e)
{
repaint ();
}
}
and this is the class is to add keyListeners and test it:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame implements KeyListener
{
JFrame f;
public Test ()
{
addKeyListener (this);
setFocusable (true);
f = new JFrame ();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(500, 500);
}
public void keyPressed(KeyEvent e)
{
BulletAnimator s = new BulletAnimator (250, 250, "initialized---blank");
//creates bullet w/ correct direction
if (e.getKeyCode() == KeyEvent.VK_RIGHT )
{
s = new BulletAnimator (250, 250, "right");
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT )
{
s = new BulletAnimator (250, 250, "left");
}
else if (e.getKeyCode() == KeyEvent.VK_UP )
{
s = new BulletAnimator (250, 250, "up");
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN )
{
s = new BulletAnimator (250, 250, "down");
}
System.out.println ("keyPressed method read");//checks if keyPressed method was looked at
f.add (s);
repaint();
}
public void keyReleased (KeyEvent e)
{}
public void keyTyped (KeyEvent e)
{}
public static void main (String [] args)
{
Test t = new Test ();
}
}
As you can see I tried to put in a test that says "keyPressed method read"... when the program runs it doesn't print. In fact nothing at all happens its just a grey screen... quite frustrating really. Well thank you in advance if you took the time to look at it, I would greatly appreciate any advice!
Again, don't use KeyListeners, use key bindings which will allow you to listen to key strokes application-wide without as much worry about focus and at a much higher level of abstraction (so safer to use too).
For example:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Test2 extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final int TIMER_DELAY = 50;
private Timer leftKeyTimer = new Timer(TIMER_DELAY , new TimerListener());
public Test2() {
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition );
ActionMap actionMap = getActionMap();
String leftDownKey = "Left Down";
String leftUpKey = "Left Up";
KeyStroke leftDown = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT , 0, false);
KeyStroke leftUp = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT , 0, true);
inputMap.put(leftDown, leftDownKey);
inputMap.put(leftUp, leftUpKey);
actionMap.put(leftDownKey, new LeftKeyAction(false));
actionMap.put(leftUpKey, new LeftKeyAction(true));
leftKeyTimer.setActionCommand("Left Key");
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private class LeftKeyAction extends AbstractAction {
private boolean onKeyRelease;
public LeftKeyAction(boolean onKeyRelease) {
this.onKeyRelease = onKeyRelease;
}
#Override
public void actionPerformed(ActionEvent e) {
if (onKeyRelease) {
if (leftKeyTimer != null && leftKeyTimer.isRunning()) {
leftKeyTimer.stop();
}
} else {
if (leftKeyTimer != null && !leftKeyTimer.isRunning()) {
leftKeyTimer.start();
}
}
}
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent actEvt) {
System.out.println(actEvt.getActionCommand());
}
}
private static void createAndShowGui() {
Test2 mainPanel = new Test2();
JFrame frame = new JFrame("Test2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You are extending the JFrame class so that new Test() is creating an (extended) instance of a JFrame and then you are adding a KeyListener to this instance. However, the frame you are making visible is the one you created in the Test() constructor through
f = new JFrame ();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(500, 500);
You did not add your KeyListener to this instance of JFrame. So the KeyListener would only respond if the Test instance was visible and in focus.
I would suggest doing this:
public class Test extends JFrame implements KeyListener {
JFrame f; // Remove this.
public Test () {
super();
addKeyListener (this);
setFocusable (true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(500, 500);
}
}
To paint the Icons, you also need to modify BulletAnimator code:
public void actionPerformed( ActionEvent e ) {
repaint();
revalidate(); // new line
}
And change f.add(s) to add(s) in keyPressed method to add the icons to the Test frame.
Disclaimer: As others pointed out, there are better solutions to handling key presses. My suggestions above only identified the problems with your original code posted above.
My code does not work:
JFrame frame = new JFrame("mull");
mull panel = new mull();
// add panel to the center of window
frame.getContentPane().add("Center", panel);
frame.setSize(500, 300); // << not working!!!
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); // give a suitable size to window automatically
frame.setVisible(true); // make window visible
I am getting very small window. How to fix it?
Well, you are using both frame.setSize() and frame.pack().
You should use one of them at one time.
Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.
Try removing frame.pack() from your code or putting it before setting size and then run it.
Most layout managers work best with a component's preferredSize, and most GUI's are best off allowing the components they contain to set their own preferredSizes based on their content or properties. To use these layout managers to their best advantage, do call pack() on your top level containers such as your JFrames before making them visible as this will tell these managers to do their actions -- to layout their components.
Often when I've needed to play a more direct role in setting the size of one of my components, I'll override getPreferredSize and have it return a Dimension that is larger than the super.preferredSize (or if not then it returns the super's value).
For example, here's a small drag-a-rectangle app that I created for another question on this site:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MoveRect extends JPanel {
private static final int RECT_W = 90;
private static final int RECT_H = 70;
private static final int PREF_W = 600;
private static final int PREF_H = 300;
private static final Color DRAW_RECT_COLOR = Color.black;
private static final Color DRAG_RECT_COLOR = new Color(180, 200, 255);
private Rectangle rect = new Rectangle(25, 25, RECT_W, RECT_H);
private boolean dragging = false;
private int deltaX = 0;
private int deltaY = 0;
public MoveRect() {
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (rect != null) {
Color c = dragging ? DRAG_RECT_COLOR : DRAW_RECT_COLOR;
g.setColor(c);
Graphics2D g2 = (Graphics2D) g;
g2.draw(rect);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
Point mousePoint = e.getPoint();
if (rect.contains(mousePoint)) {
dragging = true;
deltaX = rect.x - mousePoint.x;
deltaY = rect.y - mousePoint.y;
}
}
#Override
public void mouseReleased(MouseEvent e) {
dragging = false;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
Point p2 = e.getPoint();
if (dragging) {
int x = p2.x + deltaX;
int y = p2.y + deltaY;
rect = new Rectangle(x, y, RECT_W, RECT_H);
MoveRect.this.repaint();
}
}
}
private static void createAndShowGui() {
MoveRect mainPanel = new MoveRect();
JFrame frame = new JFrame("MoveRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Note that my main class is a JPanel, and that I override JPanel's getPreferredSize:
public class MoveRect extends JPanel {
//.... deleted constants
private static final int PREF_W = 600;
private static final int PREF_H = 300;
//.... deleted fields and constants
//... deleted methods and constructors
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
Also note that when I display my GUI, I place it into a JFrame, call pack(); on the JFrame, set its position, and then call setVisible(true); on my JFrame:
private static void createAndShowGui() {
MoveRect mainPanel = new MoveRect();
JFrame frame = new JFrame("MoveRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Try this, but you can adjust frame size with bounds and edit title.
package co.form.Try;
import javax.swing.JFrame;
public class Form {
public static void main(String[] args) {
JFrame obj =new JFrame();
obj.setBounds(10,10,700,600);
obj.setTitle("Application Form");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}