Rotate JLabel containing a imgicon
I want to rotate a jlabel when its clicked. The label is containing a imgicon.
I have tried to do like
http://www.codeguru.com/java/articles/199.shtml
but the label dont rotate, just the image (i think).
The image image is a vertical filled rectangle, but when i try to click it, it becomes a square...
The code for adding the ship to the contentpane
ImageIcon img = new ImageIcon("bigship.gif");
JLabel jLship = new JLabel( "ship", img, SwingConstants.LEFT );
jLship.setName("ship");
jLship.setBounds(
ship.getPosition().x * (jlPOpoGame.getWidth() / 11) + 5,
ship.getPosition().y * (jlPOpoGame.getHeight() / 11) + 5,
img.getIconWidth(),
img.getIconHeight());
getJPOwnGame().add(jLship ,new Integer(1), 0);And the code for changing the label inside a mouselistener.
selected.setUI(new VerticalLabelUI(true));And the code for the UI:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
class VerticalLabelUI extends BasicLabelUI
static {
labelUI = new VerticalLabelUI(false);
protected boolean clockwise;
VerticalLabelUI( boolean clockwise )
super();
this.clockwise = clockwise;
public Dimension getPreferredSize(JComponent c)
Dimension dim = super.getPreferredSize(c);
return new Dimension( dim.height, dim.width );
private static Rectangle paintIconR = new Rectangle();
private static Rectangle paintTextR = new Rectangle();
private static Rectangle paintViewR = new Rectangle();
private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
public void paint(Graphics g, JComponent c)
JLabel label = (JLabel)c;
String text = label.getText();
Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();
if ((icon == null) && (text == null)) {
return;
FontMetrics fm = g.getFontMetrics();
paintViewInsets = c.getInsets(paintViewInsets);
paintViewR.x = paintViewInsets.left;
paintViewR.y = paintViewInsets.top;
// Use inverted height & width
paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
String clippedText =
layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);
Graphics2D g2 = (Graphics2D) g;
AffineTransform tr = g2.getTransform();
if( clockwise )
g2.rotate( Math.PI / 2 );
g2.translate( 0, - c.getWidth() );
else
g2.rotate( - Math.PI / 2 );
g2.translate( - c.getHeight(), 0 );
if (icon != null) {
icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
if (text != null) {
int textX = paintTextR.x;
int textY = paintTextR.y + fm.getAscent();
if (label.isEnabled()) {
paintEnabledText(label, g, clippedText, textX, textY);
else {
paintDisabledText(label, g, clippedText, textX, textY);
g2.setTransform( tr );
}Why dont the JLabel rotate?
I found the error, but one new occured... :(
I rotate the label with
selected.setBounds(e.getX(), e.getY(), selected.getHeight(), selected.getWidth());But the rotation works fine only one time, then it gets wrong! Look at
http://mrserver.pointclark.net/tmp/rotate.jpg
to how it looks.
Picture 1: Start position.
Picture 2: First click, rotate around where i clicked, OK.
Picture 3: Second click, the image gets cropped! The label is rotated thoug, i can select it and drag it if i click where the image should be.
Picture 4: Third click. The image is back to horizontal, looks ok!
And then it switched between 3 and 4 when i continue to click!
Can somebody help me?
Similar Messages
-
I have a combo box which i have rotated 270 degrees so that
it is now vertical. Unfortunately the parent container (have tried
with a Vbox, HBox and Canvas) does not recognize the height and
width of the rotated combo box, and keeps the size according to the
standard (horizontal) combo box. therefore there is a large space
to accomodate the combo box when instead thespace should be narrow
to accomodate the vertical combo. Any ideas how to go about this?
Aboslute x y coordinates is a solution but am trying to avoid that
so that resizing the screen doesnt cut off the combo box. please
help!!!"Greg Lafrance" <[email protected]> wrote in
message
news:gr3dft$ike$[email protected]..
> You may need to set this property:
>
> includeInLayout="false"
>
> That way the container does not try to resize/reposition
as is its default
> behavior.
If you want it included in the layout, you'll need to extend
ComboBox and
override the measure() method to switch the width and height.
HTH;
Amy -
HOW TO SHOW JLABEL IN JDIALOG WHILE MAIN CLASS IS SLEEPING? (CODE EDITED)
I have done a code below and it is working but the only problem is when the main program start to sleep by use Thread.sleep(10000) for 10 secs and it will prompt out a JDialog contain JLabel inside it with message "Please wait.... program is sleeping.". And when the thread ends the JDialog will auto disappear and it back to the main program.
I am using TimerTask to run the JDialog while the main class is sleeping.
The problem is:
When the JDialog appear, it doesn't show the component so I only be able to view the JDialog window without contain any component. I already use container to add the component into JDialog but it still doesn't show. I only be able to see the JDialog window contain empty component when the main window is sleeping.
How to make the components also appear in the JDialog when the main program is sleeping?
Below is the code pls have a try:
public class testThread extends JFrame
public static void main(String args[])
new testThread();
public testThread()
* other code not related is here
// WHEN USER PRESS startThreadBtn it will make the application sleep for 15 secs and pop out JDialog window contain JLabel msg wrote "Please wait... program is sleeping"
JButton startThreadBtn = new JButton("Start Thread");
startThreadBtn.addActionListener
( new ActionListener()
public void actionPerformed(ActionEvent e)
try{
doTask a = new doTask();
java.util.Timer thisTimer = new java.util.Timer();
thisTimer.schedule(a, 0); // when this code executed, will pop out a JDialog containing JLabel message --> refer to class doTask
Thread.sleep(10000);
a.terminate()
thisTimer.cancel();
catch(InterruptedException ie)
ie.printStackTrace();
public class doTask extends TimerTask
JDialog infoDialog;
public void run()
infoDialog = new JDialog(true);
infoDialog.setTitle("Please Wait!!!");
Container c = infoDialog.getContentPane();
c.setLayout(new BorderLayout());
JLabel infoLbl = new JLabel("Please Wait... Program is sleeping!!!", JLabel.CENTER);
c.add(infoLbl, BorderLayout.CENTER);
infoDialog.setVisible(true);
public void terminate()
infoDialog.setVisible(false);
infoDialog.dispose();
Why I can not show the JLabel inside the JDialog? The JDialog window is opened but it contain empty component.
PLEASE HELP ME .... THIS IS VERY URGENTI have the complete code and it is working. I can posted it here but it will be longer thats the reason why i shortened the code in here and displaying the important information.
The problem is the JDialog only will display the JLabel after the thread woke up. Thats mean it is too late for me to display the information. I need the JLabel containing the information to be displayed when the thread is sleeping....
Below is the complete code:
you can have a try to recompile it and u will understand what i mean. It is working and the only problem is JLabel component did not displayed in the JDialog.
Just copy the whole code into the txt file and save as testThread.java and recompile it. Inside the code has one inner class extends TimerTask call "doTask"
THE CODE START BELOW:
import java.util.*;
import java.lang.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testThread extends JFrame
public static java.util.Timer thisTimer;
public static doTask a;
public static testThread tT;
public Container cMain;
public Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public JButton exitBtn;
public JButton startThreadBtn;
/** Creates a new instance of testThread */
public static void main(String args[])
new testThread();
public testThread()
//System.out.println("Start to call JDialog");
tT = this;
int realW = (int)screenSize.getWidth();
int realH = (int)screenSize.getHeight();
int mainW = 500;
int mainH = 300;
exitBtn = new JButton("EXIT");
exitBtn.setBounds((int)((500-100)/2), (int)((300-50)/5), 100, 50);
exitBtn.addActionListener
new ActionListener()
public void actionPerformed(ActionEvent e)
System.exit(0);
startThreadBtn = new JButton("Start Thread");
startThreadBtn.setBounds((int)((500-200)/2), (int)((300-50)/5*4), 200, 50);
startThreadBtn.addActionListener
new ActionListener()
public void actionPerformed(ActionEvent e)
try
System.out.println("Start to call JDialog");
a = new doTask();
thisTimer = new java.util.Timer();
thisTimer.schedule(a, 0);
System.out.println("Thread start to sleep first 10 secs");
Thread.sleep(10000);
System.out.println("Thread start to sleep second 5 secs");
Thread.sleep(5000);
System.out.println("Thread Wake Up");
a.terminate();
thisTimer.cancel();
catch(InterruptedException ie)
ie.printStackTrace();
cMain = this.getContentPane();
cMain.setLayout(null);
cMain.add(exitBtn);
cMain.add(startThreadBtn);
setBounds((int)((realW-mainW)/2), (int)((realH-mainH)/2), mainW, mainH);
setVisible(true);
public class doTask extends TimerTask
JDialog infoDialog;
public void run()
System.out.println("TASK IS RUNNING");
int screenWidth = (int)screenSize.getWidth();
int screenHeight = (int)screenSize.getHeight();
int w = 300;
int h = 200;
infoDialog = new JDialog(tT, true);
infoDialog.setTitle("Please Wait!!!");
Container c = infoDialog.getContentPane();
c.setLayout(new BorderLayout());
JLabel infoLbl = new JLabel("Please Wait... Program is sleeping!!!", JLabel.CENTER);
c.add(infoLbl, BorderLayout.CENTER);
infoDialog.setBounds((int)((screenWidth-w)/2), (int)((screenHeight-h)/2), w, h);
infoDialog.setVisible(true);
public void terminate()
infoDialog.setVisible(false);
infoDialog.dispose();
this.cancel();
****************************************************************************************************************************************************************************************************************************************** -
Illustrator CS4 Text Rotation not working as it has in the past
When I attempt to rotate a text element, the text does not rotate along with the textbox that it was created inside. Instead, it always stays at the top of the text box and moves left/right (I hope that is an accurate description). Anyone know what is going on with this?
I think I know what it is happening in this case.... I have time and was trying to reproduce the issue..
1. Here I have a text and a text inside a container (Block text)
2. Here I use the rotate tool, every thing goes as expected
3. Here I used the free Transform tool. and as you can see, that tool rotates the container but not the text itself, so that's the "problem"...
use the rotate tool instead the transfor tool... -
Hi,
I found an interesting tutorial (link) and created a working model, adapting it as needed.
So far, when I center the container sprite and rotate it, it appears to first rotate from a 0,0 registration point, instead of from its center. I've tried to changet he sprite's registration point, but so far this hasn't worked/helped. Nothing else has worked to fix this rotation problem.
I must be doing something wrong.
Here's the AS3 (to view, add to first frame of new FLA, 1024X768 stage, color black). Rotation segments below are commented as //ROTATION.:
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.text.TextField;
//import flash.geom.ColorTransform;
stop();
//public class bejewelled extends Sprite {
var gems_array:Array=new Array();
var aGem:Sprite;
var selectorBox:Sprite=new Sprite();
var selectorRow:int=-10;
var selectorColumn:int=-10;
var red:uint = 0xFF0000;
var green:uint = 0xFF00;
var blue:uint = 0xFF;
var yellow:uint = 0xFFFF00;
var cyan:uint = 0xFFFF;
var magenta:uint = 0xFF00FF;
var white:uint = 0xFFFFFF;
var colours_array:Array=new Array(red,green,blue,yellow,cyan,magenta,white);
var clickPossible:Boolean=false;
var score_txt:TextField=new TextField();
var hint_txt:TextField=new TextField();
var score:uint=0;
var inaRow:uint=0;
var match:Boolean = true;
var gemSize:uint = 96;
var format:TextFormat = new TextFormat();
var rotate:Boolean=false;
var container:Sprite = new Sprite(); // Create the container sprite
//var newColorTransform:ColorTransform = exitBtn.transform.colorTransform;
//newColorTransform.color = 0xff0000;
//exitBtn.transform.colorTransform = newColorTransform;
function bejewelled() {
// Game initiation
format.size = 40;
format.font = 'Arial';
// Create and style score text
addChild(score_txt);
score_txt.textColor=0xFFFFFF;
score_txt.x=gemSize*9.6;
score_txt.autoSize = TextFieldAutoSize.LEFT;
score_txt.defaultTextFormat = format;
// Create and style hint text
addChild(hint_txt);
hint_txt.textColor=0xFFFFFF;
hint_txt.x=gemSize*9.6;
hint_txt.y=gemSize;
hint_txt.autoSize = TextFieldAutoSize.LEFT;
hint_txt.defaultTextFormat = format;
// Create Gems in rows and columns
addChild(container); // Add the container to the display list (stage)
for (var i:uint=0; i<8; i++) {
gems_array[i]=new Array();
for (var j:uint=0; j<8; j++) {
do {
gems_array[i][j]=Math.floor(Math.random()*7);
while (rowLineLength(i,j)>2 || columnLineLength(i,j)>2);
aGem=new Sprite();
aGem.graphics.beginFill(colours_array[gems_array[i][j]]);
aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
aGem.graphics.endFill();
aGem.name=i+"_"+j;
aGem.x=j*gemSize;
aGem.y=i*gemSize;
container.addChild(aGem);
//Center the container sprite
container.width = container.width - 10;
container.height = container.height - 10;
container.x = (stage.stageWidth-container.width)/2;
container.y = (stage.stageHeight-container.height)/2;
// Create and style selector box
container.addChild(selectorBox);
selectorBox.graphics.lineStyle(2,red,1);
selectorBox.graphics.drawRect(0,0,gemSize,gemSize);
selectorBox.visible=false;
// Listen for user input
container.addEventListener(MouseEvent.CLICK,onClick);
addEventListener(Event.ENTER_FRAME,everyFrame);
// Every frame...
function everyFrame(e:Event):void {
//Assume that gems are not falling
var gemsAreFalling:Boolean=false;
// Check each gem for space below it
for (var i:int=6; i>=0; i--) {
for (var j:uint=0; j<8; j++) {
// If a spot contains a gem, and has an empty space below...
if (gems_array[i][j] != -1 && gems_array[i+1][j]==-1) {
// Set gems falling
gemsAreFalling=true;
gems_array[i+1][j]=gems_array[i][j];
gems_array[i][j]=-1;
trace("#");
trace(i+"_"+j);
container.getChildByName(i+"_"+j).y+=gemSize;
container.getChildByName(i+"_"+j).name=(i+1)+"_"+j;
break;
// If a gem is falling
if (gemsAreFalling) {
// don't allow any more to start falling
break;
// If no gems are falling
if (! gemsAreFalling) {
// Assume no new gems are needed
var needNewGem:Boolean=false;
// but check all spaces...
for (i=7; i>=0; i--) {
for (j=0; j<8; j++) {
// and if a spot is empty
if (gems_array[i][j]==-1) {
// now we know we need a new gem
needNewGem=true;
// pick a random color for the gem
gems_array[0][j]=Math.floor(Math.random()*7);
// create the gem
aGem=new Sprite();
aGem.graphics.beginFill(colours_array[gems_array[0][j]]);
aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
aGem.graphics.endFill();
// ID it
aGem.name="0_"+j;
// position it
aGem.x=j*gemSize;
aGem.y=0;
// show it
container.addChild(aGem);
// stop creating new gems
break;
// if a new gem was created, stop checking
if (needNewGem) {
break;
// If no new gems were needed...
if (! needNewGem) {
// assume no more/new lines are on the board
var moreLinesAvailable:Boolean=false;
// check all gems
for (i=7; i>=0; i--) {
for (j=0; j<8; j++) {
// if a line is found
if (rowLineLength(i,j)>2 || columnLineLength(i,j)>2) {
// then we know more lines are available
moreLinesAvailable=true;
// creat a new array, set the gem type of the line, and where it is
var lineGems:Array=[i+"_"+j];
var gemType:uint=gems_array[i][j];
var linePosition:int;
// check t's a horizontal line...
if (rowLineLength(i,j)>2) {
// if so, find our how long it is and put all the line's gems into the array
linePosition=j;
while (sameGemIsHere(gemType,i,linePosition-1)) {
linePosition--;
lineGems.push(i+"_"+linePosition);
linePosition=j;
while (sameGemIsHere(gemType,i,linePosition+1)) {
linePosition++;
lineGems.push(i+"_"+linePosition);
// check t's a vertical line...
if (columnLineLength(i,j)>2) {
// if so, find our how long it is and put all the line's gems into the array
linePosition=i;
while (sameGemIsHere(gemType,linePosition-1,j)) {
linePosition--;
lineGems.push(linePosition+"_"+j);
linePosition=i;
while (sameGemIsHere(gemType,linePosition+1,j)) {
linePosition++;
lineGems.push(linePosition+"_"+j);
// for all gems in the line...
for (i=0; i<lineGems.length; i++) {
// remove it from the program
container.removeChild(container.getChildByName(lineGems[i]));
// find where it was in the array
var cd:Array=lineGems[i].split("_");
// set it to an empty gem space
gems_array[cd[0]][cd[1]]=-1;
// set the new score
score+=inaRow;
// set the score setter up
inaRow++;
// if a row was made, stop the loop
break;
// if a line was made, stop making more lines
if (moreLinesAvailable) {
break;
// if no more lines were available...
//ROTATION
if (! moreLinesAvailable) {
if(rotate){
container.rotation+=5;
if(container.rotation%90==0){
rotate=false;
container.rotation=0;
rotateClockwise(gems_array);
while(container.numChildren>0){
container.removeChildAt(0);
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
aGem=new Sprite();
aGem.graphics.beginFill(colours_array[gems_array[i][j]]);
aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
aGem.graphics.endFill();
aGem.name=i+"_"+j;
aGem.x=j*gemSize;
aGem.y=i*gemSize;
container.addChild(aGem);
container.addChild(selectorBox);
selectorBox.graphics.lineStyle(2,red,1);
selectorBox.graphics.drawRect(0,0,gemSize,gemSize);
selectorBox.visible=false;
else{
// allow new moves to be made
clickPossible=true;
// remove score multiplier
inaRow=0;
// display new score
score_txt.text=score.toString();
// When the user clicks
function onClick(e:MouseEvent):void {
// If a click is allowed
if (clickPossible) {
// If the click is within the game area...
if (mouseX<container.x+gemSize*8 && mouseX>0 && mouseY<container.y+gemSize*8 && mouseY>0) {
// Find which row and column were clicked
var clickedRow:uint=Math.floor((mouseY-container.y)/gemSize);
//var clickedRow:uint=Math.floor(e.target.y/gemSize);
var clickedColumn:uint=Math.floor((mouseX-container.x)/gemSize);
//var clickedColumn:uint=Math.floor(e.target.x/gemSize);
// Check if the clicked gem is adjacent to the selector
// If not...
if (!(((clickedRow==selectorRow+1 || clickedRow==selectorRow-1)&&clickedColumn==selectorColumn)||((clickedColumn==selectorColumn+1 || clickedColumn==selectorColumn-1) && clickedRow==selectorRow))) {
// Find row and colum the selector should move to
selectorRow=clickedRow;
selectorColumn=clickedColumn;
// Move it to the chosen position
selectorBox.x=gemSize*selectorColumn;
selectorBox.y=gemSize*selectorRow;
// If hidden, show it.
selectorBox.visible=true;
// If it is not next to it...
else {
// Swap the gems;
swapGems(selectorRow,selectorColumn,clickedRow,clickedColumn);
// If they make a line...
if (rowLineLength(selectorRow,selectorColumn)>2 || columnLineLength(selectorRow,selectorColumn)>2||rowLineLength(clickedRow,clickedColumn)>2 || columnLineLength(clickedRow,clickedColumn)>2) {
// remove the hint text
hint_txt.text="";
// dis-allow a new move until cascade has ended (removes glitches)
clickPossible=false;
// move and rename the gems
container.getChildByName(selectorRow+"_"+selectorColumn).x=e.target.x;//clickedColumn*gemSize;
container.getChildByName(selectorRow+"_"+selectorColumn).y=e.target.y;//clickedRow*gemSize;
container.getChildByName(selectorRow+"_"+selectorColumn).name="t";
container.getChildByName(clickedRow+"_"+clickedColumn).x=selectorColumn*gemSize;
container.getChildByName(clickedRow+"_"+clickedColumn).y=selectorRow*gemSize;
container.getChildByName(clickedRow+"_"+clickedColumn).name=selectorRow+"_"+selectorColumn;
container.getChildByName("t").name=clickedRow+"_"+clickedColumn;
match = true;
rotate = true;
// If not...
else {
// Switch them back
swapGems(selectorRow,selectorColumn,clickedRow,clickedColumn);
match = false;
if (match) {
// Move the selector position to default
selectorRow=-10;
selectorColumn=-10;
// and hide it
selectorBox.visible=false;
else {
// Set the selector position
selectorRow=clickedRow;
selectorColumn=clickedColumn;
// Move the box into position
selectorBox.x=gemSize*selectorColumn;
selectorBox.y=gemSize*selectorRow;
match = false;
// If hidden, show it.
selectorBox.visible=true;
// If the click is outside the game area
else {
// For gems in all rows...
for (var i:uint=0; i<8; i++) {
// and columns...
for (var j:uint=0; j<8; j++) {
// if they're not too close to the side...
if (i<7) {
// swap them horizontally
swapGems(i,j,i+1,j);
// check if they form a line
if ((rowLineLength(i,j)>2||columnLineLength(i,j)>2||rowLineLength(i+1,j)>2||columnLineLength(i+1,j)>2)) {
// if so, name the move made
selectorBox.x = j*gemSize;
selectorBox.y = i*gemSize;
selectorBox.visible = true;
hint_txt.text = (i+1).toString()+","+(j+1).toString()+"->"+(i+2).toString()+","+(j+1).toString();
// swap the gems back
swapGems(i,j,i+1,j);
// then if they're not to close to the bottom...
if (j<7) {
// swap it vertically
swapGems(i,j,i,j+1);
// check if it forms a line
if ((rowLineLength(i,j)>2||columnLineLength(i,j)>2||rowLineLength(i,j+1)>2||columnLineLength(i,j+1)>2) ) {
// if so, name it
selectorBox.x = j*gemSize;
selectorBox.y = i*gemSize;
selectorBox.visible = true;
hint_txt.text = (i+1).toString()+","+(j+1).toString()+"->"+(i+1).toString()+","+(j+2).toString();
// swap the gems back
swapGems(i,j,i,j+1);
//Swap given gems
function swapGems(fromRow:uint,fromColumn:uint,toRow:uint,toColumn:uint):void {
//Save the original position
var originalPosition:uint=gems_array[fromRow][fromColumn];
//Move original gem to new position
gems_array[fromRow][fromColumn]=gems_array[toRow][toColumn];
//move second gem to saved, original gem's position
gems_array[toRow][toColumn]=originalPosition;
//Find out if there us a horizontal line
function rowLineLength(row:uint,column:uint):uint {
var gemType:uint=gems_array[row][column];
var lineLength:uint=1;
var checkColumn:int=column;
//check how far left it extends
while (sameGemIsHere(gemType,row,checkColumn-1)) {
checkColumn--;
lineLength++;
checkColumn=column;
//check how far right it extends
while (sameGemIsHere(gemType,row,checkColumn+1)) {
checkColumn++;
lineLength++;
// return total line length
return (lineLength);
//Find out if there us a vertical line
function columnLineLength(row:uint,column:uint):uint {
var gemType:uint=gems_array[row][column];
var lineLength:uint=1;
var checkRow:int=row;
//check how low it extends
while (sameGemIsHere(gemType,checkRow-1,column)) {
checkRow--;
lineLength++;
//check how high it extends
checkRow=row;
while (sameGemIsHere(gemType,checkRow+1,column)) {
checkRow++;
lineLength++;
// return total line length
return (lineLength);
function sameGemIsHere(gemType:uint,row:int,column:int):Boolean {
//Check there are gems in the chosen row
if (gems_array[row]==null) {
return false;
//If there are, check if there is a gem in the chosen slot
if (gems_array[row][column]==null) {
return false;
//If there is, check if it's the same as the chosen gem type
return gemType==gems_array[row][column];
//ROTATION
function rotateClockwise(a:Array):void {
var n:int=a.length;
for (var i:int=0; i<n/2; i++) {
for (var j:int=i; j<n-i-1; j++) {
var tmp:String=a[i][j];
a[i][j]=a[n-j-1][i];
a[n-j-1][i]=a[n-i-1][n-j-1];
a[n-i-1][n-j-1]=a[j][n-i-1];
a[j][n-i-1]=tmp;
bejewelled();
Any help appreciated.OK, way too much code. By default, everything will rotate from top left. If you want to change that you need to change the positions of the content within the container, not the container itself.
For example if you do something like this:
var a:Sprite = new Sprite(); //container
addChild(a);
a.x = 100; a.y = 100;
var b:MovieClip = new car(); //clip from library
a.addChild(b);
addEventListener(Event.ENTER_FRAME, up);
function up(e:Event):void
a.rotation += 1;
The car added to the container will rotate about it's top left point... because that's where the container rotates about. To fix, move the car so the containers top/left is at the car's center like so:
var a:Sprite = new Sprite();
addChild(a);
a.x = 100; a.y = 100;
var b:MovieClip = new car();
a.addChild(b);
b.x -= b.width / 2;
b.y -= b.height / 2;
addEventListener(Event.ENTER_FRAME, up);
function up(e:Event):void
a.rotation += 1;
You'll notice all that changed is moving the car 1/2 it's width and height.
HTH -
Centering a JLabel in an application
Excuse me for being a noob, but it is really annoying me:
I just started with Java and wanted to create something simple and i though; what could be more simple than a program which displays your current IP and hostname. I got everything working exept the fact that i'm having trouble centering the JLabels containing the results on the screen. I was hoping someone could help me with this.
Many thanks in advanceimport javax.swing.*;
public class Test {
public static void main(String[] args) {
JLabel label = new JLabel("text", SwingConstants.CENTER);
final JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.setSize(400, 50);
SwingUtilities.invokeLater(new Runnable(){
public void run() {
f.setLocationRelativeTo(null);
f.setVisible(true);
}There is a whole forum devoted to Swing, by the way... -
How to show an empty JLabel?
Hi,
I tried to create a JLabel containing nothing, gave it a size and a background color...but when i add it to a JFRame, it just won't show! I tried setVisible(true), and it's not either! Anyone knows what i should do?To get the background color to show you need to setOpaque(true);
Otherwise the layout may be shrinking it to zer size. You may need to setSize(), setPreferredSize() or setMinimumSize() depending on the layout you are using. -
JLabel.getText doesn't work properly
I have a main JFrame to build up the application GUI (using NetBeans 6.0.1). This mainPanel contains a JSplitPane and a StatusBar beneath. In the right side of the JSplitPane I put a JPanel with JComboBoxes and JButtons. After selecting an item in the JComboBox and clicking a JButton, the text in the StatusBar (implemented using a simple JLabel) shall be faded out by simply removing the first character until the text is erased and I use a Timer for this. This works well for itself.
The problem now is that I want to start the 'fading' only if the StatusBar (the JLabel) contains a text at all. Checking this with:
if ( !targetLabel.getText().equals("") ) {
<start fading>
}the getText() method returns "" (an empty string) ever. Even although I initialized this JLabel with a dummy text during initialization. Why?
Here's the code for trying to set a JLabel in the StatusBar (this part works well) and fading a probably displayed text prior:
class StatusMessageSetter implements Runnable{
String myText;
Color color;
JLabel target;
public StatusMessageSetter(JLabel target, Color color, String text) {
myText = text;
this.color = color;
this.target = target;
public void run() {
//try {
System.out.println("StatusMessageSetter: target=" + target);
//SwingUtilities.invokeLater(new Runnable(){
// public void run() {
System.out.println("StatusMessageSetter: target.getText()=" + target.getText());
if ( !target.getText().trim().equals("") ) {
try {
MessageFader fader = new MessageFader(target);
Thread th = new Thread(fader);
th.start();
th.join();
} catch(InterruptedException intEx){}
}//end if
Thread t = new Thread(new Runnable(){
public void run(){
try {
SwingUtilities.invokeAndWait(new Runnable() {
//SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Setting label...: " + myText);
target.setForeground(color);
target.setText(myText);
}//end run
} catch(InterruptedException intEx) {}
catch(InvocationTargetException invocEx) {}
}); //end new Runnable
t.start();
}//end run
};+(Even when I only request the text from the JLabel when the JButton is clicked (in the JButton's actionPerformed() method) and doing nothing else the result is an empty String!!! And it doesn't matter if I do this directly or using SwingUtilities.invokeLater(); Why? I don't undertand this. I am asking: parentView.getStatusMessageLabel().getText(); (No NullPointerException is thrown. Thus, parentView as well as statusMessageLabel exist and I can see the set text in the statusBar.)+
What I want to do (and I didn't managed this for the time being) is, that I want to display a message to the user what the app is going to do and inform the user afterwards about the result (failure/success) using the JLabel in the StatusBar. (Saying: "I'm going to do this...", executing a time consuming action (parsing a website) and the display the result in the StatusBar. Of course, the messages MUST be displayed well synchronized which means:
Displaying what the app is currently doing and after the action returns this messagfe shall fade and the new message will be displayed.
Maybe anyone could give me some code to solve my problem?!!?
Thanks in advance
Dirk
Edited by: dirku on May 8, 2008 5:05 AMdirku wrote:
2. A time consuming operation needs to be executed:
--> In this case the time consuming operation begins but the message which should tell the user what the time consuming operation does is displayed
only AFTER the operation has already completed. (The time consuming operation connects to parses a website and must return a state (OK,
ERROR, ...).
Thus, I think I need some kind of synchronization, don't I?Hm, not sure. You're probably not even going to see this, but no matter. I played with my code some more and got something like so:
StatusMessageSetter .java
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.Timer;
class StatusMessageSetter
private static final int DELAY = 1000;
private String myText;
private Color color;
private JLabel target;
private int delay = DELAY;
public StatusMessageSetter(JLabel target)
this.target = target;
public void setDelay(int delay)
this.delay = delay;
public void fadeLabel(Color color, String text)
this.color = color;
this.myText = text;
if (!target.getText().trim().equals(""))
new Timer(delay, new MessageFader(target, color, myText)).start();
private class MessageFader implements ActionListener
private JLabel label;
private StringBuilder sb;
private Color color;
private String text;
public MessageFader(JLabel target, Color c, String t)
label = target;
color = c;
text = t;
sb = new StringBuilder(label.getText().trim());
@Override
public void actionPerformed(ActionEvent e)
if (sb.length() > 0)
sb.deleteCharAt(0);
if (sb.length() == 0)
label.setText(" ");
else
label.setText(sb.toString());
else
label.setForeground(color);
label.setText(text);
Timer timer = (Timer)e.getSource();
timer.stop();
}StatusBr.java
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class StatusBr
private JPanel mainPanel = new JPanel();
private JLabel label = new JLabel();
public StatusBr()
mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
mainPanel.add(label);
public JLabel getLabel()
return label;
public void setColor(Color c)
label.setForeground(c);
public void setText(String text)
label.setText(text);
public String getText()
return label.getText();
public void setBorder(Border border)
mainPanel.setBorder(border);
public JPanel getMainPanel()
return mainPanel;
}StatusMsgrTester.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.Timer;
public class StatusMsgrTester
private static final String STATUS_BAR = "Status Bar";
private static final String CONFIRMED = "Confirmed";
private static final String QUICK_CONFIRM = "Quick Confirmation";
private static final String SLOW_CONFIRM = "Slow Confirmation";
private static final String RESET = "Reset";
private JPanel mainPanel = new JPanel();
private StatusBr statusbar = new StatusBr();
StatusMessageSetter statusMsgSetter = new StatusMessageSetter(statusbar
.getLabel());
public StatusMsgrTester()
JButton quickConfirmBtn = new JButton(QUICK_CONFIRM);
JButton slowConfirmBtn = new JButton(SLOW_CONFIRM);
JButton resetBtn = new JButton(RESET);
ConfirmBtnListener confirmListener = new ConfirmBtnListener();
quickConfirmBtn.addActionListener(confirmListener);
slowConfirmBtn.addActionListener(confirmListener);
resetBtn.addActionListener(confirmListener);
JPanel confirmPanel = new JPanel(new GridLayout(1, 0, 10, 10));
confirmPanel.add(quickConfirmBtn);
confirmPanel.add(slowConfirmBtn);
confirmPanel.add(resetBtn);
JPanel buttonPanel = new JPanel();
buttonPanel.add(confirmPanel);
statusMsgSetter.setDelay(60);
statusbar.setText(STATUS_BAR);
statusbar.setBorder(BorderFactory.createCompoundBorder(BorderFactory
.createRaisedBevelBorder(), BorderFactory
.createLoweredBevelBorder()));
mainPanel.setPreferredSize(new Dimension(500, 200));
mainPanel.setLayout(new BorderLayout());
mainPanel.add(statusbar.getMainPanel(), BorderLayout.SOUTH);
mainPanel.add(buttonPanel, BorderLayout.NORTH);
private class ConfirmBtnListener implements ActionListener
@Override
public void actionPerformed(ActionEvent e)
String command = e.getActionCommand();
if (command.equals(QUICK_CONFIRM))
statusMsgSetter.fadeLabel(Color.blue, CONFIRMED);
else if (command.equals(SLOW_CONFIRM))
slowConfirmation();
else if (command.equals(RESET))
statusbar.setColor(null);
statusbar.setText(STATUS_BAR);
public JPanel getMainPanel()
return mainPanel;
private void slowConfirmation()
final Timer timer = new Timer(2000, new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
statusMsgSetter.setDelay(30);
statusMsgSetter.fadeLabel(Color.red, "Confirming User, Please Wait.......");
timer.setInitialDelay(5);
timer.start();
SwingWorker<String, Void> swingworker = new SwingWorker<String, Void>()
@Override
protected String doInBackground() throws Exception
System.out.println("Long process");
for (int i = 0; i < 10; i++)
System.out.println(String.valueOf(i));
Thread.sleep(1400);
return null;
@Override
protected void done()
timer.stop();
System.out.println("Done");
statusMsgSetter.fadeLabel(Color.blue, CONFIRMED);
swingworker.execute();
private static void createAndShowUI()
JFrame frame = new JFrame("StatusMsgrTester");
frame.getContentPane().add(new StatusMsgrTester().getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
createAndShowUI();
} -
Hello all. I am fairly new to Java and having a problem setting the text in a JLabel. I am trying to create a calculator program and when the user clicks a button I want that number to appear in a JLabel at the top. I used output.setText("7"); but when I compiled it said <identifier> expected. I will paste the full code below and would appreciate any help. Also, is there a getText function with JLabel, because I need to get what is currently in the output field and concatenate it with the number pressed.
Thanks in advance for your help,
Jeremy
* Write a description of class calculator here.
* @author (Jeremy Kruer)
* @version (11/19/02)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class calculator extends JFrame
private JButton one, two, three, four, five, six, seven, eight, nine, zero, dec, eq, plus, minus, mult, div;
private JLabel output;
private Container container;
//set up GUI
public calculator()
//Create Title
super("Calculator");
//Set size and make visible
setSize( 400, 400 );
setVisible( true );
container = getContentPane();
container.setLayout( new FlowLayout() );
//set up output
output = new JLabel();
container.add( output );
//set up seven and register its event handler
seven = new JButton( " 7 " );
seven.addActionListener(
//anonymouse inner class
new ActionListener()
//add a seven to the output diplay when clicked
output.setText( "7" );
}//end anonymouse inner class
); //end call to addActionListener
container.add( seven );
//set up eight
eight = new JButton( " 8 " );
container.add( eight );
//set up nine
nine = new JButton( " 9 " );
container.add( nine );
//set up div
div = new JButton( " / " );
container.add( div );
//set up four
four = new JButton( " 4 " );
container.add( four );
//set up five
five = new JButton( " 5 " );
container.add( five );
//set up six
six = new JButton( " 6 " );
container.add( six );
//set up mult
mult = new JButton( " * " );
container.add( mult );
//set up one
one = new JButton( " 1 " );
container.add( one );
//set up two
two = new JButton( " 2 " );
container.add( two );
//set up three
three = new JButton( " 3 " );
container.add( three );
//set up minus
minus = new JButton( " - " );
container.add( minus );
//set up zero
zero = new JButton( " 0 " );
container.add( zero );
//set up dec
dec = new JButton( " . " );
container.add( dec );
//set up eq
eq = new JButton( " = " );
container.add( eq );
//set up plus
plus = new JButton( " +" );
container.add( plus );
//Set size and make visible
setSize( 220, 250 );
setVisible( true );
//execute application
public static void main( String args[] )
calculator application = new calculator();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}I played with the lauout a bit and added the actionListener:
you will see what you click on !!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class calcu extends JFrame implements ActionListener
private JButton one, two, three, four, five, six, seven, eight, nine, zero, dec, eq, plus, minus, mult, div;
private JLabel output;
public calcu()
super("Calculator");
JPanel container = new JPanel();
container.setLayout(new FlowLayout(FlowLayout.LEFT));
output = new JLabel("");
output.setBorder(new MatteBorder(2,2,2,2,Color.gray));
output.setPreferredSize(new Dimension(1,26));
getContentPane().setBackground(Color.white);
getContentPane().add("North",output);
getContentPane().add("Center",container);
//set up seven and register its event handler
seven = new JButton(" 7 ");
container.add(seven);
seven.addActionListener(this);
//set up eight
eight = new JButton(" 8 ");
container.add(eight);
eight.addActionListener(this);
//set up nine
nine = new JButton( " 9 " );
container.add( nine );
nine.addActionListener(this);
//set up div
div = new JButton( " / " );
container.add( div );
div.addActionListener(this);
//set up four
four = new JButton( " 4 " );
container.add( four );
four.addActionListener(this);
//set up five
five = new JButton( " 5 " );
container.add( five );
five.addActionListener(this);
//set up six
six = new JButton( " 6 " );
container.add( six );
six.addActionListener(this);
//set up mult
mult = new JButton( " * " );
container.add( mult );
mult.addActionListener(this);
//set up one
one = new JButton( " 1 " );
container.add( one );
one.addActionListener(this);
//set up two
two = new JButton( " 2 " );
container.add( two );
two.addActionListener(this);
//set up three
three = new JButton( " 3 " );
container.add( three );
three.addActionListener(this);
//set up minus
minus = new JButton( " - " );
container.add( minus );
minus.addActionListener(this);
//set up zero
zero = new JButton( " 0 " );
container.add( zero );
zero.addActionListener(this);
//set up dec
dec = new JButton( " . " );
container.add( dec );
dec.addActionListener(this);
//set up eq
eq = new JButton( " = " );
container.add( eq );
eq.addActionListener(this);
//set up plus
plus = new JButton( " +" );
container.add( plus );
plus.addActionListener(this);
//Set size and make visible
setSize(220,250);
setResizable(false);
setVisible( true );
public void actionPerformed(ActionEvent ae)
JButton but = (JButton)ae.getSource();
output.setText(but.getText());
//execute application
public static void main( String args[] )
calcu application = new calcu();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} Noah -
Having probelm with JLabel and setText
I posted a message in Java Programming but I think it will be more appropriate here. I am trying to create a calculator so I want my JLabel(output) to display the number of the button that is clicked on. I used output.setText("7") but I get an error when compiling saying <identifier> expected. Any advice would be great. Also, is there a getText method in JLabel? I need to concatenate the current contents of JLabel and the value of the button pushed. For example:
output.setText( output.getText() + "7" );
Anyways, here is my code. I tried to make it indent so it is easier to read but it doesn't show up once I post it.
Thanks for you help.
* Write a description of class calculator here.
* @author (Jeremy Kruer)
* @version (11/19/02)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class calculator extends JFrame
private JButton one, two, three, four, five, six, seven, eight, nine, zero, dec, eq, plus, minus, mult, div;
private JLabel output;
private Container container;
//set up GUI
public calculator()
//Create Title
super("Calculator");
//Set size and make visible
setSize( 400, 400 );
setVisible( true );
container = getContentPane();
container.setLayout( new FlowLayout() );
//set up output
output = new JLabel();
container.add( output );
//set up seven and register its event handler
seven = new JButton( " 7 " );
seven.addActionListener(
//anonymouse inner class
new ActionListener()
//add a seven to the output diplay when clicked
output.setText( "7" );
}//end anonymouse inner class
); //end call to addActionListener
container.add( seven );
//set up eight
eight = new JButton( " 8 " );
container.add( eight );
//set up nine
nine = new JButton( " 9 " );
container.add( nine );
//set up div
div = new JButton( " / " );
container.add( div );
//set up four
four = new JButton( " 4 " );
container.add( four );
//set up five
five = new JButton( " 5 " );
container.add( five );
//set up six
six = new JButton( " 6 " );
container.add( six );
//set up mult
mult = new JButton( " * " );
container.add( mult );
//set up one
one = new JButton( " 1 " );
container.add( one );
//set up two
two = new JButton( " 2 " );
container.add( two );
//set up three
three = new JButton( " 3 " );
container.add( three );
//set up minus
minus = new JButton( " - " );
container.add( minus );
//set up zero
zero = new JButton( " 0 " );
container.add( zero );
//set up dec
dec = new JButton( " . " );
container.add( dec );
//set up eq
eq = new JButton( " = " );
container.add( eq );
//set up plus
plus = new JButton( " +" );
container.add( plus );
//Set size and make visible
setSize( 220, 250 );
setVisible( true );
//execute application
public static void main( String args[] )
calculator application = new calculator();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );// not tested but try it ...
1. put an empty string into the JLabel
declare
String labString = "";
(and declare the JLabel too)
2. initialise label - init() {
myLabel = new JLabel(labString)
3. activate
actionPerformed(ActionEvent evt) {
if (evt.getSource()==button#7) {
labString = getActionCommand();
myLabel.setText(labString);
validate();
Something like that anyway - it should work + if you 'play' with it, you can probably make it a bit more efficiently than the methods I've outlined here. -
HTML component with PDF disappears on rotate/scale
I have a PDF loading into an <mx:HTML> source. This works fine. However, in my multi-touch application, I need to drag/rotate/scale its wrapping container. Drag works fine. However, when it rotates/scales, the PDF disappears.
From livedocs:
"If certain visual properties of an HTMLLoader object that contains a PDF document are changed, the PDF document will become invisible. These properties include the filters, alpha, rotation, and scaling
properties. Changing these properties renders the PDF content invisible until the properties are reset. The PDF content is also invisible if you change these properties of display object containers that contain the HTMLLoader object."
Is this still a limitation on Air 2/Hero? Is there a workaround so the container/HTML/PDF can support rotating/scaling?
I want the multi-touch wall users to be able to make the PDF bigger, rotate the container/pdf, and drag it around the wall. My drag/rotate/scale work very well on any other component, just not pdf.
Please explain why it disappears and if there is a workaround.
Thanks,
DonI never did find a solution for this. The Reader just doesn't support it. What I ended up doing back then was to use ColdFusion's CFPDF tag to automatically convert each page in the PDF to an png, then do the touch gestures on the pngs.
Don Kerr -
Hi - I'm having trouble with JLabels "underlapping" when I want them to overlap in a swing JFrame. I believe this is because of the order in which they are instantiated. Is there a way to overlap a JLabel (containing an ImageIcon) on a JLabel that has been previously instantiated?
thanks, AdamI believe in JDK6 (maybe JDK5) you can set the z-order.
Otherwise you could try using the OverlayLayout, (see the API) or use LayeredPane (read the Swing tutorial);
http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html -
Ad rotator - add supporting gif for flash file
Hi there, I am using the ad rotator to host 3rd party advertising. I have been supplied with a flash file (swf) and also a gif version of the ad. I want to be able to point to the gif file if the swf file is not able to be played by the browser/device. Is this possible within the ad rotator to have a fall-back gif file?
thanksThis functionality isn't native to BC but I've done this before for a client. Just beware that using an .swf (flash) file embed for the ad won't let you track the BC Ad Rotator links. Typical, image-only ads in the AdRotator can be tracked in BC's reporting but using a .swf file doesn't work and you have to embed the link in the actual .swf file itself. Before we get you working with a flash fallback solution, if you have access to the .swf file or can tell your client what URL to use in the flash ad then you should use the AdRotator trackign URL if you can. Do do that, setup an image-only ad rotator item first in one of your ad rotators. Add that rotator to a demo page to get the URL of the ad rotator (it contains the unique id of your ad for tracking). Once you have that URL you can update your flash file to use that URL to take advantage of tracking on BC or give it to your customer to update the flash file themselves before sending you the flash file.
Once you've taken care of the link in the flash ad or if you don't care about not tracking flash ad clicks in BC's reporting system, let's move on to building a flash fallback ad solution. We'll be using SWFObject which is the correct way to embed flash with fallback content. The hardest part of this whole scenario is we have to get the ID of the ad rotator item (not the ad rotator ID) below.
The javascript I came up with requires jQuery and it's usually already loaded on many sites. Make sure jQuery is loaded in the HEAD of your page or page template where you'll be serving the ads in the ad rotator.
Download the SWFObject project and unzip it locally.
Upload the whole "swfobject" folder to the root of your website.
In your page template or page that you will be serving your ads on, add this script reference to the HEAD of your HTML doc:<script src="/swfobject/swfobject.js"></script>
Download my custom javascript function and upload it somewhere on your website. For this example we'll assume you are placing it in the "js" folder in the root of your site.
In your page or page template where you'll be serving ads, reference the script you just downloaded. Make sure it goes after our swfobject.js and jquery references in the head of your HTML doc:<script src="/js/adRotatorFlashFallback.js"></script>
Now that our jQuery, SWFObject & adRotatorFlashFallback scripts are in place in the HEAD of our page or page template, let's move on to creating your ads with fallback content
Upload the backup image you want to use for non-flash devices to your website and remember the URL/path of that image. For our example we'll use "/images/demoad.gif".
Upload your .swf file to your site and rember the URL/path to that file. We'll need it later.
Once the image and flash file are uploaded we'll create our ad rotator item for that ad:
Create a new ad rotator item
Choose the Item Type as HTML
Add your Label (title) and Item Click-thru URL
In the Item HTML box manually insert your HTML markup for the image:
<img src="/images/demoad.gif" width="125" height="125" />
(I won't be covering styling the ad so you can wrap a div around that image if you want to use some CSS to target the ad:(Optional) <div class="ad-item"><img src="/images/demoad.gif" width="125" height="125" /></div>
Save the ad first before we add the flash option. We need to get that ad rotator item's ID first before we can hookup javascript to embed the flash over the backup image. If you have many ad rotator items already in place you might want to temporarily disable all the ads already setup except the one you are working on so you don't have to refresh the page a bunch of times to wait for your ad to randomly appear.
Goto a test page and use BC's module manager to insert your AdRotator.
Preview your test page with your ad rotator and once you see your ad you are creating, right-click the ad (this works in Chrome for sure) to copy the URL of the ad. You can also see what the URL is just by hovering over the ad in most browers. The goal here is to jot down or grab the ID of the web app item and that should be in the URL similar to this: "/BannerProcess.aspx?ID=32713&URL=%2ftest". I bolded the ID we'll be grabbing. This ID is unique to each ad rotator item and we need that so that we can embed a specific flash file for that specific ad rotator item.
Once you've got your ID of the item, head back to the Ad Rotator Item you just created in the BC Admin.
You'll want to add some javascript after your image markup in the "Item HTML" box
Before we had: <img src="/images/demoad.gif" width="125" height="125" />
and it becomes:<img src="/images/demoad.gif" width="125" height="125" />
<script>adRotatorFlashFallback('32711','/demoad.swf', '125', '125');</script>
Replace the bolded items above with the ID of your ad rotator item we pulled from the URL before and the URL to the flash file we uploaded to the site before. In our case, I uploaded "demoad.swf" to the root of the website. Also, the '125' and '125' above are the width and height, respectively for your flash file. For instance if your flash movie is 300 pixels wide and 100 pixels in height then calling our functions with those dimensions would look like:<script>adRotatorFlashFallback('32711','/demoad.swf', '300', '100');</script>
Make sure the ad rotator item is enabled and you're all set.
You can see a demo of it working at http://www.chrismatthias.com/demos/swf-fallback-ad-rotator
After your initial setup of downloading the javascripts and referencing them in your page or template, the hardest thing about creating new ad rotator items with fallback is getting the ID of the ad rotator item from the URL in steps 12-14, but it's the only way I know of to get the ID of the ad rotator item. I can't find it in the BC Admin anywhere. -
Trying to call a Java3D application from .jnlp file
Hi everybody,
I'm trying to execute a java3D simple program making use of a *.jnlp* file, but isn't working...
Can anybody help? Thanks in advance.
This is what I have:
simple.jnlp
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+"
codebase="file:///the_path/jnlp/">
<information>
<title>Hello JNLP</title>
<homepage href="http://whatever.com" />
<vendor>My self </vendor>
<offline/>
</information>
<resources>
<j2se version="1.2+" />
<jar href="bin/HelloJava3Da.jar" />
<jar href="bin/j3dcore.jar" />
<jar href="bin/j3dutils.jar" />
<jar href="bin/vecmath.jar" />
</resources>
<application-desc main-class="HelloJava3Da" />
</jnlp>First, I had to generate the HelloJava3Da.jar, which contains HelloJava3Da.class (my program compiled and working when using java command).
Generation of HelloJava3Da.jar :
$ jar cf HelloJava3Da.jar HelloJava3Da.class
$ jarsigner -keystore myKeys HelloJava3Da.jar jdcFinally, when I try to run simple.jnlp, making use of Firefox:
firefox simple.jnlpThe result is:
Error: Unexpected exception: java.lang.reflect.InvocationTargetException
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.javaws.Launcher.executeApplication(Launcher.java:1272)
at com.sun.javaws.Launcher.executeMainClass(Launcher.java:1218)
at com.sun.javaws.Launcher.doLaunchApp(Launcher.java:1065)
at com.sun.javaws.Launcher.run(Launcher.java:105)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.ExceptionInInitializerError
at javax.media.j3d.VirtualUniverse.<clinit>(VirtualUniverse.java:227)
at HelloJava3Da.<init>(HelloJava3Da.java:23)
at HelloJava3Da.main(HelloJava3Da.java:53)
... 9 more
Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
at java.security.AccessController.checkPermission(AccessController.java:546)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.SecurityManager.checkAccess(SecurityManager.java:712)
at java.lang.ThreadGroup.checkAccess(ThreadGroup.java:288)
at java.lang.ThreadGroup.getParent(ThreadGroup.java:139)
at javax.media.j3d.MasterControl$16.run(MasterControl.java:3680)
at java.security.AccessController.doPrivileged(Native Method)
at javax.media.j3d.MasterControl.<clinit>(MasterControl.java:3673)
... 12 moreI have already made the same procedure with a none Java3D program (*TheTime.class*) and everything run well... With my java3D program is not...
TheTime.java
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class TheTime {
public static void main(String args[]) {
JFrame frame = new JFrame("Time Check");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
Container content = frame.getContentPane();
content.add(label, BorderLayout.CENTER);
String message = "missing";
BufferedReader reader = null;
try {
Socket socket = new Socket("time.nist.gov", 13);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
reader = new BufferedReader(isr);
reader.readLine(); // skip blank line
message = reader.readLine();
} catch (MalformedURLException e) {
System.err.println("Malformed: " + e);
} catch (IOException e) {
System.err.println("I/O Exception: " + e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
label.setText(message);
frame.pack();
frame.show();
HelloJava3Da.java
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.*;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.ColorCube;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.*;
import javax.vecmath.*;
import java.awt.GraphicsConfiguration;
//import com.sun.j3d.utils.universe.SimpleUniverse;
// HelloJava3Da renders a single, rotating cube.
public class HelloJava3Da extends Applet {
public HelloJava3Da() {
setLayout(new BorderLayout());
GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
Canvas3D canvas3D = new Canvas3D(config);
add("Center", canvas3D);
BranchGroup scene = createSceneGraph();
// SimpleUniverse is a Convenience Utility class
SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
// This will move the ViewPlatform back a bit so the
// objects in the scene can be viewed.
simpleU.getViewingPlatform().setNominalViewingTransform();
simpleU.addBranchGraph(scene);
} // end of HelloJava3Da (constructor)
public BranchGroup createSceneGraph() {
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
objRoot.addChild(new ColorCube(0.4));
return objRoot;
} // end of CreateSceneGraph method of HelloJava3Da
// The following allows this to be run as an application
// as well as an applet
public static void main(String[] args) {
Frame frame = new MainFrame(new HelloJava3Da(), 256, 256);
} // end of main (method of HelloJava3Da)
} // end of class HelloJava3DaI have a collection of Java3d applets launched with Java3d:
http://astral.mobile-visuals.com/3d_visuals.php
You can compare your code for the page with mine, for instance this one:
<applet code="org.jdesktop.applet.util.JNLPAppletLauncher"
width=100%
height=98%
archive="astrals.jar,
http://download.java.net/media/applet-launcher/applet-launcher.jar,
http://download.java.net/media/java3d/webstart/release/j3d/latest/j3dcore.jar,
http://download.java.net/media/java3d/webstart/release/j3d/latest/j3dutils.jar,
http://download.java.net/media/jogl/builds/archive/jsr-231-webstart-current/jogl.jar,
http://download.java.net/media/gluegen/webstart/gluegen-rt.jar,
http://download.java.net/media/java3d/webstart/release/vecmath/latest/vecmath.jar">
<param name="codebase_lookup" value="false">
<param name="subapplet.classname" value="OrchideaOptM">
<param name="subapplet.displayname" value="Orchideic Morph">
<param name="jnlpNumExtensions" value="1">
<param name="jnlpExtension1" value="http://download.java.net/media/java3d/webstart/release/java3d-latest.jnlp">
<param name="progressbar" value="true">
<param name="noddraw.check" value="true">
</applet>
----------------- -
Hii there,
I'm having a JInternalFrame, and within that frame, I added a jlabel. the jlabel contains several images that is being added dynamically. I've added a horizontal scrollbar that is working. but my problem is with the vertical scrollbar. The thing is whenever an image added to jlabel, height of the label increases and the label exceeds to internalframe. The vertivcal scrollbar does not working to see the exceeded part of the jlabel,
My code is something like this:
dpane.setDesktopManager(new DefaultDesktopManager());
iframe=new JInternalFrame("Image Frame" ,true,true,true,true);
vScrollBar = new JScrollBar(JScrollBar.VERTICAL);
vScrollBar.setValue(jLabel.getHeight());
vScrollBar.setValueIsAdjusting(true);
iframe.getContentPane().add(vScrollBar,BorderLayout.EAST);
iframe.getContentPane().add(jLabel,BorderLayout.CENTER);
dpane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
dpane.add(iframe);
iframe.setVisible(true);
add(dpane);could you else please help me!
thanks in advance...
DevYou haven't written the code that links scroll bar and its target view component.
Use JScrollPane and a simple container JPanel.
Forget your scroll bar and the label.
Maybe you are looking for
-
A connection was abortively closed after one of the peers sent an rst packet
Hello, i have a dvr on netwoek that is wok fine. i tried to publish it over internet. i have tmg with two wan connections(load Balancing) and two internal networks. i create a server application rule and and but dvr protcols on it. when i try to open
-
How to start from a specific point on the timeline
I have a horizontal list of image thumbnails, there are 21 thumbnails and only 7 are visible at one time and scrolls back and forth. It works fine. However, when I choose an image that is not in the first seven, say the 8th image, the page loads and
-
How do I get my apps to save less data?
I have a iPhone 4S. Recently my apps are storing more data than usual. I have to delete the app, then re-download it. Also, there is memory missing, meaning when I add up the data my iPhone uses, it doesn't calculate to what my iPhone says I have ava
-
A Java internet plug-in?
Does anyone know a good plug-in for netbeans so that when i run my compiled project i can view the internet. example would be like opening up internet explore... ty
-
SRM MDM with Multiple Repositories and required S&A.
Hello everyone, We are in the planning process to migrate from CCM to MDM. Our current environment has two separate customers running on two separate SAP clients in SRM 5.0 using the internal CCM (one SAP SRM instance, 2 separate SAP clients). In MDM