NullPointerException in swing at actionPerformed - swing

This is a login form for a slot machine game which will evoke a "NextPage" object. I don't think this LoginDemo.java code has to do anything with the error but I prefer to post the entire code. Thanks in advance..
//LoginDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Login extends JFrame implements ActionListener
{
JButton SUBMIT;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
Login()
{
label1 = new JLabel();
label1.setText("Username:");
label1.setBounds(50,50,100,30);
text1 = new JTextField(15);
text1.setBounds(250,50,100,30);
label2 = new JLabel();
label2.setText("Password:");
label2.setBounds(50,250,100,30);
text2 = new JPasswordField(15);
text2.setBounds(250,250,100,30);
//this.setLayout(new BorderLayout());
SUBMIT=new JButton("SUBMIT");
SUBMIT.setBounds(350,350,100,30);
// panel=new JPanel(new GridLayout(3,1));
panel=new JPanel(null);
panel.setBounds(50,50,1000,1000);
// panel.setLayout(new FlowLayout());
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("a") && value2.equals("a"))
{
NextPage page=new NextPage();
page.setVisible(true);
//JLabel label = new JLabel("Welcome:"+value1);
// page.getContentPane().add(label);
setVisible(false);
}
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(1000,1000);
frame.setVisible(true);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
//NextPage.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.Random;
import java.sql.*;
import java.lang.*;
import java.awt.image.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class NextPage extends JFrame implements Runnable, ActionListener
{
BufferedImage img1,i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,star1;
JFrame f1;
Thread t1,t2,t3;
int x1,y1,i,j,k,l,m,n,r1,r2,r3;
JButton b1;
Random r=new Random();
TextField tf1;
JPanel p1;
NextPage()
{
setBounds(50,50,1000,1000);
p1=(JPanel)(getContentPane());
p1.setBounds(50,50,1000, 1000);
p1.setLayout(null);
//tf1=new TextField(20);
//tf1.setBounds(50,50,100,30);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome");
b1=new JButton("START");
//p1.add(tf1);
b1.setBounds(150,400,100,30);
//try{
b1.addActionListener(this);
//}
/*catch(Exception e)
{
System.out.println(""+e);
}*/
add(b1);
setVisible(true);
try
{
i0=ImageIO.read(new File("tea.jpg"));
i1=ImageIO.read(new File("coffee.jpg"));
i2=ImageIO.read(new File("bhel.jpg"));
i3=ImageIO.read(new File("pizza.jpg"));
i4=ImageIO.read(new File("icecream.jpg"));
i5=ImageIO.read(new File("dosa.jpg"));
i6=ImageIO.read(new File("idli.jpg"));
i7=ImageIO.read(new File("panipuri.jpg"));
i8=ImageIO.read(new File("orange.jpg"));
i9=ImageIO.read(new File("watermelon.jpg"));
i10=ImageIO.read(new File("pavbhaji.jpg"));
i11=ImageIO.read(new File("noodles.jpg"));
i12=ImageIO.read(new File("sandwich.jpg"));
}
catch (IOException ie)
{
System.out.println("Error:"+ie.getMessage());
}
j=0; m=0; n=0;
r1= r.nextInt(13);
r2= r.nextInt(13);
r3= r.nextInt(13);
}
public void init()
{
t1=new Thread(this);
t2=new Thread(this);
t3=new Thread(this);
}
public void start()
{
t2.start();
t3.start();
}
public void run()
{
try
{
if(Thread.currentThread()==t1)
for(j=0; j<150; j++)
//for(i=0; i<=150; i+=20)
{
r1= r.nextInt(13);
repaint();
t1.sleep(10);
}
if(Thread.currentThread()==t2)
for(m=0; m<160; m++)
//for(k=0; k<=150; k+=20)
{
r2= r.nextInt(13);
repaint();
t2.sleep(10);
}
if(Thread.currentThread()==t3)
for(n=0; n<170; n++)
//for(l=0; l<=150; l+=20)
{
r3= r.nextInt(13);
repaint();
t3.sleep(10);
}
}
catch(Exception e)
{
System.out.println(""+e);
}
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawRect(50,300,150,80);
g.drawRect(200,300,150,80);
g.drawRect(350,300,150,80);
switch(r1)
{
case 0: g.drawImage(i0,65,300,this);
break;
case 1: g.drawImage(i1,65,300,this);
break;
case 2: g.drawImage(i2,65,300,this);
break;
case 3: g.drawImage(i3,65,300,this);
break;
case 4: g.drawImage(i4,65,300,this);
break;
case 5: g.drawImage(i5,65,300,this);
break;
case 6: g.drawImage(i6,65,300,this);
break;
case 7: g.drawImage(i7,65,300,this);
break;
case 8: g.drawImage(i8,65,300,this);
break;
case 9: g.drawImage(i9,65,300,this);
break;
case 10: g.drawImage(i10,65,300,this);
break;
case 11: g.drawImage(i11,65,300,this);
break;
case 12: g.drawImage(i12,65,300,this);
break;
}
switch(r2)
{
case 0: g.drawImage(i0,215,300,this);
break;
case 1: g.drawImage(i1,215,300,this);
break;
case 2: g.drawImage(i2,215,300,this);
break;
case 3: g.drawImage(i3,215,300,this);
break;
case 4: g.drawImage(i4,215,300,this);
break;
case 5: g.drawImage(i5,215,300,this);
break;
case 6: g.drawImage(i6,215,300,this);
break;
case 7: g.drawImage(i7,215,300,this);
break;
case 8: g.drawImage(i8,215,300,this);
break;
case 9: g.drawImage(i9,215,300,this);
break;
case 10: g.drawImage(i10,215,300,this);
break;
case 11: g.drawImage(i11,215,300,this);
break;
case 12: g.drawImage(i12,215,300,this);
break;
}
switch(r3)
{
case 0: g.drawImage(i0,365,300,this);
break;
case 1: g.drawImage(i1,365,300,this);
break;
case 2: g.drawImage(i2,365,300,this);
break;
case 3: g.drawImage(i3,365,300,this);
break;
case 4: g.drawImage(i4,365,300,this);
break;
case 5: g.drawImage(i5,365,300,this);
break;
case 6: g.drawImage(i6,365,300,this);
break;
case 7: g.drawImage(i7,365,300,this);
break;
case 8: g.drawImage(i8,365,300,this);
break;
case 9: g.drawImage(i9,365,300,this);
break;
case 10: g.drawImage(i10,365,300,this);
break;
case 11: g.drawImage(i11,365,300,this);
break;
case 12: g.drawImage(i12,365,300,this);
break;
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
t1.start();
}
/*public static void main(String args[])
{
NextPage o=new NextPage();
}*/
}
}
Here are the exceptions that I get-
F:\java\jdk\bin>java LoginDemo
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NextPage.actionPerformed(NextPage.java:235)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
atjavax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6289)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6054)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4652)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:603)
at java.awt.EventQueue$1.run(EventQueue.java:601)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87
at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98
at java.awt.EventQueue$2.run(EventQueue.java:617)
at java.awt.EventQueue$2.run(EventQueue.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87
at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Can't get any solution.. I am a learner..please help..

You used the variable t1 to start the thread that should be assigned to this variable. How ever the function init() that creates the instance of the thread that is assigned to this variable is never called. There for t1 is null and calling any function on a null object causes the NullPointerException.
Simply call the init() function. I think the original idea was to call it within the constructor and you simply forgot to insert it.
For future question please consider only posting the lines close to the point where the StackTrace reports the error. To find that spots of interest look into the StackTrace and look for entries in classes you wrote. In this case NextPage.actionPerformed(NextPage.java:235) is a point of interest. In your question best mark those spots to get a good resolution quickly.

You do not call the init method, hence your t1 variable is still null when you enter the actionPerformed method.
This is rather obvious from the stacktrace (there is only one thing that can be null on that line), and if not obvious from the stacktrace a debugger would have shown this immediately. Way faster then creating a post with hundreds of lines of irrelevant code

Related

Handling multiple key events libgdx

I am trying to make a game using the libgdx framework.
I am using an InputAdapter to check for key press events, everything works fine until more than 3 keys are pressed at once.
I need 3 or more than 3 key events if player is moving diagonally and shooting at the same time.
For some reason the input adapter only registers first 2 key events and no new press event is registered until one of the keys is up.
public class MyInputProcessor extends InputAdapter{
public boolean keyDown(int k)
{
switch (k)
{
case Keys.LEFT:
MyInput.setKey(MyInput.LEFT, true);
break;
case Keys.UP:
MyInput.setKey(MyInput.UP, true);
break;
case Keys.DOWN:
MyInput.setKey(MyInput.DOWN, true);
break;
case Keys.RIGHT:
MyInput.setKey(MyInput.RIGHT, true);
break;
case Keys.Z:
MyInput.setKey(MyInput.SHOOT, true);
break;
case Keys.ESCAPE:
MyInput.setKey(MyInput.ESC, true);
break;
}
return true;
}
public boolean keyUp(int k)
{
switch (k)
{
case Keys.LEFT:
MyInput.setKey(MyInput.LEFT, false);
break;
case Keys.UP:
MyInput.setKey(MyInput.UP, false);
break;
case Keys.DOWN:
MyInput.setKey(MyInput.DOWN, false);
break;
case Keys.RIGHT:
MyInput.setKey(MyInput.RIGHT, false);
break;
case Keys.Z:
MyInput.setKey(MyInput.SHOOT, false);
break;
case Keys.ESCAPE:
MyInput.setKey(MyInput.ESC, false);
break;
}
return true;
}
}

Flash as3 class wont call ADDED_TO_STAGE event when using addChild()

I don't know why, but for some reason I can't get my InputEngine class to listen for ADDED_TO_STAGE.
package Input{
import flash.display.*;
import flash.events.*;
import flash.ui.Keyboard;
public class InputEngine extends Sprite{
public function InputEngine() {
addEventListener(Event.ADDED_TO_STAGE, stageAddHandler);
leftPressed = false;
rightPressed = false;
upPressed = false;
downPressed = false;
}
public function stageAddHandler(e:Event)
{
trace("worke");
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyIsPressed, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_UP, keyIsReleased, false, 0, true);
}
public function keyIsPressed(e:KeyboardEvent)
{
switch(e.keyCode)
{
case Keyboard.LEFT : leftPressed = true; break;
case Keyboard.RIGHT : rightPressed = true; break;
case Keyboard.UP : upPressed = true; break;
case Keyboard.DOWN : downPressed = true; break;
}
}
public function keyIsReleased(e:KeyboardEvent)
{
switch(e.keyCode)
{
case Keyboard.LEFT : leftPressed = false; break;
case Keyboard.RIGHT : rightPressed = false; break;
case Keyboard.UP : upPressed = false; break;
case Keyboard.DOWN : downPressed = false; break;
}
}
public var leftPressed:Boolean = new Boolean;
public var rightPressed:Boolean = new Boolean;
public var upPressed:Boolean = new Boolean;
public var downPressed:Boolean = new Boolean;
}
}
This is the main game file:
package {
import Input.InputEngine;
import flash.display.*;
import flash.events.*;
public class System extends Sprite{
public function System() {
trace("System created");
addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addChild(inputEngine);
// constructor code
}
public function gameLoop(e:Event)
{
if(inputEngine.leftPressed == true)
{
trace("Left pressed");
}
}
public var inputEngine:InputEngine = new InputEngine();
}
}
for some reason I cannot get InputEngine to initialize the keyboard listeners. What am I doing wrong here?
Your problem based on your comments of the error is that your instance of the System class has not been added to the display list. Without seeing all your code, it's hard to help you.
You didn't mention there was a runtime error in your question. But if we assume that you actually have an instance of inputEngine and things are happening as you 'expect' them to, the problem is that your instance of System class has not been added to the stage. Therefore... inputEngine is never attached to the display list of the stage.

how to display image from hard drive in flash

i want to Load image from hard disk and display in my flash movie i have little code when i click on button it open hyperlink so anybody know about image loading function
package{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.navigateToURL;
import flash.net.URLRequest;
public class Main extends Sprite{
public function Main():void{
z_cst.addEventListener(MouseEvent.CLICK,buttonClick);
z_kp.addEventListener(MouseEvent.CLICK,buttonClick);
z_kr.addEventListener(MouseEvent.CLICK,buttonClick);
z_ka.addEventListener(MouseEvent.CLICK,buttonClick);
z_rs.addEventListener(MouseEvent.CLICK,buttonClick);
z_c.addEventListener(MouseEvent.CLICK,buttonClick);
z_vp.addEventListener(MouseEvent.CLICK,buttonClick);
z_cr.addEventListener(MouseEvent.CLICK,buttonClick);
z_cs.addEventListener(MouseEvent.CLICK,buttonClick);
}
private function buttonClick(e:MouseEvent):void{
var url:URLRequest=new URLRequest();
switch(e.target.name){
case "z_cst": url.url="http://www.star.com"; break;
case "z_kp": url.url="http://www.star.com"; break;
case "z_kr": url.url="http://www.star.com"; break;
case "z_ka": url.url="http://www.star.com"; break;
case "z_rs": url.url="http://www.gear.com"; break;
case "z_c": url.url="http://www.apple.com"; break;
case "z_vp": url.url="http://www.images.com"; break;
case "z_cr": url.url="http://www.buy.com"; break;
case "z_cs": url.url="http://www.contact.com"; break;
}
navigateToURL(url,"_blank");
}
}
}
Look up the Loader{} class for loading images - http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Loader.html
Added some code - (wish code in comments could be formatted as code)
From your comment, it looks like you would have gotten it. What you were missing was that you needed to call the Loader object's load() method and pass in the URLRequest object to it. Here is some code that does this loosely following your previous code:
private function buttonClick(e:MouseEvent):void {
var loader:Loader = new Loader();
this.addChild(loader);
switch(e.target.name) {
case "z_cst":
loader.load(new URLRequest("/data/1.jpg"));
break;
case "z_kp":
loader.load(new URLRequest("/data/2.jpg"));
break;
case "z_kr":
loader.load(new URLRequest("/data/3.jpg"));
break;
default:
trace("buttonClick() - No matching name found");
this.removeChild(loader); // remove the Loader object from the stage as it is 'empty'
break;
}
}
I added the 'default' block to the switch block to help check for possible errors. A Loader object is a display object, so you can position it just like any other display object.

Margins with LineBorders

I want to have a JTextArea with a LineBorder and leave a little padding between the text and the LineBorder.
Is this possible with the standard classes or do I need a custom "DoubleLine" border (one with the color and one with the margin)?
Some sample code is below...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class TextAreaLineBorder extends JFrame
{
private static final long serialVersionUID = 1L;
private class MyPanel extends JPanel
{
private static final long serialVersionUID = 1L;
public MyPanel()
{
setLayout(new FlowLayout());
JTextArea ta = new JTextArea("Some text");
ta.setSize(200, 50);
boolean useDefaultBorder = false;
if (useDefaultBorder)
{
// Setting the margin works fine, with the default border
ta.setMargin(new Insets(12, 12, 12, 12));
Border b = ta.getBorder();
Insets defaultInsets = b.getBorderInsets(ta);
System.out.println("Default Insets: "
+ defaultInsets);
}
else
{
// Try using a non-default LineBorder
LineBorder lb = (LineBorder) BorderFactory.createLineBorder(Color.YELLOW, 2);
ta.setBorder(lb);
// TODO: What should be done so that the LineBorder has Insets?
ta.setMargin(new Insets(12, 12, 12, 12));
Insets lineBorderInsets = lb.getBorderInsets(ta);
System.out.println("LineBorder Insets: " + lineBorderInsets);
}
add(ta);
}
}
public TextAreaLineBorder()
{
setResizable(true);
setName(getClass().getSimpleName());
setTitle("My Frame");
setSize(300, 300);
JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP);
// Add the panel
tabbedPane.addTab("Button panel", new MyPanel());
add(tabbedPane, BorderLayout.CENTER);
getContentPane().add(tabbedPane);
}
private static void createAndShowGUI()
{
// Create and set up the window.
TextAreaLineBorder frame = new TextAreaLineBorder();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
createAndShowGUI();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
});
}
}
You can add the JTextArea to a JScrollPane and put the border around that.
JTextArea JTA = new JTextArea();
JScrollPane JSP = new JScrollPane(JTA);
JSP.setBorder(BorderFactory.createLineBorder(Color.blue));
I created a class that helped me solve this problem. The same solution can likely be used for all JTextComponents.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JTextAreaWithPaddedBorder extends JTextArea
{
// **********************************************************************
// To modify the sample program using GWT Designer, uncomment this code
// **********************************************************************
// public JTextAreaWithPaddedBorder()
// {
// }
//
// /**
// * Bogus Constructor
// *
// * #wbp.parser.constructor (Use this method in the GWT Designer)
// */
//
// public JTextAreaWithPaddedBorder(int ignore)
// {
// createAndShowGUI();
// }
// **********************************************************************
// To modify the sample program using GWT Designer, uncomment this code
// **********************************************************************
public static void createAndShowGUI()
{
// Create and set up the frame
JFrame frmTextareawithpaddedborder = new JFrame();
frmTextareawithpaddedborder.setTitle("TextAreaWithPaddedBorder");
frmTextareawithpaddedborder.setName("frmTextareawithpaddedborder");
frmTextareawithpaddedborder.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTextareawithpaddedborder.setBounds(100, 100, 514, 495);
frmTextareawithpaddedborder.setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frmTextareawithpaddedborder.setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 5, 490, 395);
scrollPane.setName("scrollPane");
contentPane.add(scrollPane);
final JTextAreaWithPaddedBorder textArea = new JTextAreaWithPaddedBorder();
textArea.setBorder(new LineBorder(new Color(0, 0, 0), 2));
textArea.setName("textArea");
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
String text = "The iPhone is a line of smartphones designed and marketed by Apple Inc. The first iPhone was unveiled by Steve Jobs, then CEO of Apple, on January 9, 2007,[1] and released on June 29, 2007. The 5th generation iPhone, the iPhone 4S, was announced on October 4, 2011, and released 10 days later. An iPhone can function as a video camera (video recording was not a standard feature until the iPhone 3GS was released), a camera phone, a portable media player, and an Internet client with email and web browsing capabilities, can send texts and receive visual voicemail, and has both Wi-Fi and cellular data (2G and 3G) connectivity. The user interface is built around the device's multi-touch screen, including a virtual keyboard rather than a physical one.";
textArea.setText(text);
textArea.append("\n\nThis is the text within the TextArea. As the border of the TextArea is changed, the text should display properly.");
contentPane.setLayout(null);
textArea.setBackground(Color.WHITE);
scrollPane.setViewportView(textArea);
btnChangeMargins = new JButton("Change Margins");
btnChangeMargins.setBounds(13, 430, 152, 23);
btnChangeMargins.setName("btnChangeMargins");
btnChangeMargins.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
long t = (new Date()).getTime() % 100;
int top = (int) (t * 18) % 15;
int bottom = (int) (t * 34) % 15;
int left = (int) (t * 52) % 15;
int right = (int) (t * 52) % 15;
Insets insets = new Insets(top, left, bottom, right);
textArea.setMargin(insets);
}
});
contentPane.add(btnChangeMargins);
btnChangeBGColor = new JButton("Change BG Color");
btnChangeBGColor.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
long t = (new Date()).getTime() % 100;
int r = 100 + (int) (t * 18) % 100;
int g = 100 + (int) (t * 34) % 100;
int b = 100 + (int) (t * 52) % 100;
Color c = new Color(r, g, b);
textArea.setBackground(c);
}
});
btnChangeBGColor.setBounds(178, 430, 152, 23);
btnChangeBGColor.setName("btnChangeBGColor");
contentPane.add(btnChangeBGColor);
btnChangeBorder = new JButton("Change Border");
btnChangeBorder.setBounds(343, 430, 152, 23);
btnChangeBorder.setName("btnChangeBorder");
btnChangeBorder.addActionListener(new ActionListener()
{
int last = 0;
#Override
public void actionPerformed(ActionEvent e)
{
Border nextBorder;
switch (last++ % 8)
{
case 0:
nextBorder = BorderFactory.createLoweredBevelBorder();
break;
case 1:
nextBorder = BorderFactory.createEmptyBorder();
break;
case 2:
nextBorder = BorderFactory.createEtchedBorder();
break;
case 3:
nextBorder = BorderFactory.createLineBorder(Color.black, 2);
break;
case 4:
nextBorder = BorderFactory.createRaisedBevelBorder();
break;
case 5:
nextBorder = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.red, 3), BorderFactory
.createLoweredBevelBorder());
break;
case 6:
nextBorder = BorderFactory.createMatteBorder(2, 15, 1, 15, new Color(255, 0, 0));
break;
case 7:
nextBorder = BorderFactory.createTitledBorder("Titled Border");
break;
default:
nextBorder = BorderFactory.createTitledBorder("Titled Border");
}
textArea.setBorder(nextBorder);
}
});
contentPane.add(btnChangeBorder);
frmTextareawithpaddedborder.setVisible(true);
}
private static final long serialVersionUID = 1L;
private static JButton btnChangeMargins;
private static JButton btnChangeBGColor;
private static JButton btnChangeBorder;
#Override
public void setBorder(Border border)
{
int paddingWidth = 0;
Border currentBorder = getBorder();
if (currentBorder != null)
{
// The padding width will be the minimum width specified in the insets
Insets insets = getMargin();
paddingWidth = Math.min(insets.bottom, insets.top);
paddingWidth = Math.min(paddingWidth, insets.left);
paddingWidth = Math.min(paddingWidth, insets.right);
}
/*
* Use a LineBorder for the padding.
*
* The color must be the same as the background color of the TextComponent
*/
super.setBorder(new CompoundBorder(border, BorderFactory.createLineBorder(getBackground(), paddingWidth)));
}
#Override
public void setBackground(Color c)
{
super.setBackground(c);
Border b = getBorder();
if (b != null)
{
setBorder(((CompoundBorder) b).getOutsideBorder());
}
}
#Override
public void setMargin(Insets m)
{
super.setMargin(m);
Border b = getBorder();
if (b != null)
{
setBorder(((CompoundBorder) b).getOutsideBorder());
}
}
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
createAndShowGUI();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}

Refactoring AS3 automatic game loop into controlled one

I need to take control of how my base game class updates:
package
{
import flash.display.Sprite;
import flash.events.KeyboardEvent;
public class Test extends Sprite
{
private var sprite:Sprite;
public function Test()
{
sprite = new Sprite();
sprite.graphics.beginFill(0xFF0000, 1);
sprite.graphics.drawRect(0, 0, 20, 20);
sprite.graphics.endFill();
addChild(sprite);
this.stage.addEventListener(KeyboardEvent.KEY_UP,
moveSprite);
this.stage.addEventListener(KeyboardEvent.KEY_DOWN,
moveSprite);
}
private function moveSprite(keyEvent:KeyboardEvent):void
{
switch (keyEvent.keyCode)
{
case 37:
sprite.x--
break;
case 38:
sprite.y--;
break;
case 39:
sprite.x++
break;
case 40:
sprite.y++;
break;
default:
break;
}
}
}
}
Here after every key press/release AS3 takes care of automatically drawing a sprite onto screen, but I need to do this manualy. Haw to get my hands on updating mechanism here? I need something like this - all time repeating game loop that is set to be updated/redrawn every time at its end. Are there any ideas how could I achieve this?
Thanks everyone for help.
You could convert this into a MovieClip which has a timeline, then update the animation as you wish on Event.ENTER_FRAME.
package
{
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.Event;
public class Test extends MovieClip
{
private var sprite:Sprite;
public function Test()
{
sprite = new Sprite();
sprite.graphics.beginFill(0xFF0000, 1);
sprite.graphics.drawRect(0, 0, 20, 20);
sprite.graphics.endFill();
addChild(sprite);
this.stage.addEventListener(KeyboardEvent.KEY_UP,
moveSprite);
this.stage.addEventListener(KeyboardEvent.KEY_DOWN,
moveSprite);
this.stage.addEventListener(Event.ENTER_FRAME,
moveSpriteRight);
}
private function moveSprite(keyEvent:KeyboardEvent):void
{
switch (keyEvent.keyCode)
{
case 37:
sprite.x--
break;
case 38:
sprite.y--;
break;
case 39:
sprite.x++
break;
case 40:
sprite.y++;
break;
default:
break;
}
}
private function moveSpriteRight(e:Event):void
{
sprite.x++;
}
}
}
You can also use a Timer loop for these sorts of things:
package
{
import flash.display.Sprite;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Game
{
private var _timerTickRate : int = 500; //milliseconds
private var _timer : Timer;
public function Game()
{
init();
}
private function init() : void
{
_timer = new Timer( _timerTickRate );
_timer.addEventListener( TimerEvent.TIMER, onTimerTick );
_timer.start(); //to stop, call _timer.stop() and remove this listener
}
private function onTimerTick( event : TimerEvent ) : void
{
//do game loop stuff here.
}
}
}