Can't draw .jpeg on a JPanel - image

I'm working on a Game where I need to draw a board and pawns actively when I move them. I've searched for a few hours now, but I can't find a solution.
They're located in the same folder as the classes.
Thanks in advance for any help :)
code:
import java.awt.*;
import javax.swing.*;
public class MyPanel extends JPanel{
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
try {
Image board = new ImageIcon("images/ChackerBoard.jpeg").getImage();
Image black = new ImageIcon("images\\BlackPawn.jpeg").getImage();
Image white = new ImageIcon("images\\WhitePawn.jpeg").getImage();
this.setSize(320, 320);
g.drawImage(board, 0, 0, this);
for (int i = 0; i < Game.BlackList.size(); i++) {
g.drawImage(black, (Game.BlackList.get(i).GetX() * 40) - 36, (Game.BlackList.get(i).GetY() * 40) - 36, this);
}
for (int i = 0; i < Game.WhiteList.size(); i++) {
g.drawImage(white, (Game.WhiteList.get(i).GetX() * 40) - 36, (Game.WhiteList.get(i).GetY() * 40) - 36, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
images:
http://i.stack.imgur.com/bhuc2.jpg
http://imageshack.us/a/img7/8673/checkerboardo.jpg

#FailX in paintComponent, imageobserver object is null. Set the image observer as "this" and it works.
#Override
protected void paintComponent( Graphics g ){
super.paintComponent( g );
g.drawImage(img, 0, 0, this); //Image is also drawn
g.drawLine( 10, 10, 100, 50 ); //Line is drawn
g.draw3DRect(20,20,50,30,true); // Rectangle is drawn
}

Related

Problem with ActionListener to give a buttona value

I'm trying to give a functions to an array of jbuttons with ActionListener
but when I pass 'i' as variable it gives erorr :
App.java:45: error: local variables referenced from an inner class must be final or effectively final
the error is on line 45, 58, and 71.
Here's the code :
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class App extends JFrame {
App(){
JFrame calcFrame = new JFrame();
calcFrame.setSize(320, 420);
calcFrame.setVisible(true);
calcFrame.setTitle("Calculator");
calcFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
calcFrame.setResizable(false);
calcFrame.getContentPane().setBackground(new Color(0x123456));
//add panel
JTextField textField = new JTextField();
textField.setBounds(35, 20, 200, 100);
textField.setBackground(new Color(0x000000));
calcFrame.add(textField);
JButton cbtn = new JButton(String.valueOf('c')); // clear button
cbtn.setBounds(240, 140, 50, 50);
calcFrame.add(cbtn);
JButton pbtn = new JButton(String.valueOf('^')); // power button
pbtn.setBounds(240, 200, 50, 50);
calcFrame.add(pbtn);
/*Add array of buttuns from 0 ... 9 */
JButton nums[] = new JButton[10];
calcFrame.getContentPane().setLayout(null);
// organzie using if statment
for(int i = 0; i < 4; i++)
{
nums[i] = new JButton(String.valueOf(i)); // organzie first line 0 ... 3
nums[i].setBounds(i * 60, 140, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
for(int i = 4, j = 0; i < 8; i++, j++)//organzie second line 4 ... 7
{
nums[i] = new JButton(String.valueOf(i));
nums[i].setBounds(j * 60, 200, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
for(int i = 8, j = 0; i < 10; i++, j++)//last numbers line 8 ... 9
{
nums[i] = new JButton(String.valueOf(i));
nums[i].setBounds(j * 60, 260, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
//End of numbers 0 ... 9
JButton dotbtn = new JButton();
JButton eqlbtn = new JButton();
dotbtn = new JButton(String.valueOf('.'));// dot button for a value less than 1
dotbtn.setBounds(120, 260, 50, 50);
calcFrame.add(dotbtn);
eqlbtn = new JButton(String.valueOf('=')); //equal button
eqlbtn.setBounds(180, 260, 50, 50);;
calcFrame.add(eqlbtn);
String[] arthmetictools = {"+", "-", "x", "/"};
JButton[] artbtns = new JButton[4]; // array of arthmetic buttons
for (int i = 0; i <= 4; i++) {
artbtns[i] = new JButton(String.valueOf(arthmetictools[i]));
artbtns[i].setBounds( 60 * i, 320, 50, 50);
calcFrame.add(artbtns[i]);
}
}
public static void main(String[] args) {
System.out.println("Hello, World!");
/* make the frame call it calc frame */
App calc = new App();
}
}
Thank you.
Tried to set text field to string of i from for loop.

Position of JLabel in Graphics when double buffering

I am using a thread to draw some animations, so I need to repaint the label for every frame. To do this without flickering I am updating the label with my backbuffer graphics object (using the lbl.update(bufferedGraphics); method), but when I do this, the label gets repainted in the top left of the Graphics object, and not where setLocation has specified.
How do I specify the location of the label within the graphics, instead of within the panel that owns the label?
Here is an SSCCE:
import javax.swing.*;
import java.awt.*;
public class LabelSSCCE extends JApplet implements Runnable {
JPanel pnl;
JLabel lbl;
Image buffer;
Graphics bufferedGraphics;
Thread t;
public void init (){
pnl = new JPanel (null);
lbl = new JLabel ();
lbl.setText ("Text");
lbl.setOpaque(true);
add(pnl);
pnl.add (lbl);
lbl.setLocation(100, 100);
lbl.setBounds (100, 100, 200, 20);
buffer = createImage (500, 500);
bufferedGraphics = buffer.getGraphics ();
t = new Thread (this, "Label");
t.start ();
}// init method
public void paint (Graphics g){
if (g != null)
g.drawImage (buffer, 0, 0, this);
}//paint
public void update (Graphics g){
paint (g);
}//update
public void render (){
bufferedGraphics.setColor (Color.WHITE);
bufferedGraphics.fillRect (0, 0, 500, 500);
lbl.update (bufferedGraphics);
update(getGraphics());
}//render
public void run (){
while (true){
try{
render ();
t.sleep (20);
} catch (InterruptedException e){
e.printStackTrace ();
}//catch
}//while
}//run
}//LabelSSCCE
First, convert the JLabel to a BufferedImage:
public BufferedImage componentToImage(Component component)
{
BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
Graphics g = img.getGraphics();
g.setColor(component.getForeground());
g.setFont(component.getFont());
component.paintAll(g);
Rectangle region = new Rectangle(0, 0, img.getWidth(), img.getHeight());
return img.getSubimage(region.x, region.y, region.width, region.height);
}
Then, change the render method to something like this:
public void render() {
bufferedGraphics.setColor(Color.WHITE);
bufferedGraphics.fillRect(0, 0, 500, 500);
BufferedImage bi = componentToImage(lbl);
bufferedGraphics.drawImage(bi, lbl.getX(), lbl.getY(), null);
update(getGraphics());
}

GWT - Fading in/out a background image

I have a custom class as follows which works fine, the button grows/shrinks to accomodate the text and the bg image changes on a click.
Probem I want to solve is how to "fadeIN" one or other image when clicked/notClicked is called
Here is my code
public ExpandingOvalButton(String text) {
if (text.length() > 15) {
label.getElement().getStyle().setFontSize(20, Unit.PX);
} else {
label.getElement().getStyle().setFontSize(30, Unit.PX);
}
int width = 120;
initWidget(panel);
label.setText(text);
// width = width + (text.length() * 8);
String widthStr = width + "px";
image.setWidth(widthStr);
image.setHeight("100px");
button = new PushButton(image);
button.setWidth(widthStr);
button.setHeight("50px");
panel.add(button, 0, 0);
panel.add(label, 18, 14);
}
public void isClicked()
{
image.setUrl("images/rectangle_green.png");
}
public void unClicked()
{
image.setUrl("images/rectangle_blue.png");
}
#Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
return addDomHandler(handler, ClickEvent.getType());
}
public void setButtonEnabled(boolean enabled) {
// panel.setVisible(enabled);
// this.label.setVisible(enabled);
this.button.setVisible(enabled);
}
Here's a general utility class to fade any element:
public class ElementFader {
private int stepCount;
public ElementFader() {
this.stepCount = 0;
}
private void incrementStep() {
stepCount++;
}
private int getStepCount() {
return stepCount;
}
public void fade(final Element element, final float startOpacity, final float endOpacity, int totalTimeMillis) {
final int numberOfSteps = 30;
int stepLengthMillis = totalTimeMillis / numberOfSteps;
stepCount = 0;
final float deltaOpacity = (float) (endOpacity - startOpacity) / numberOfSteps;
Timer timer = new Timer() {
#Override
public void run() {
float opacity = startOpacity + (getStepCount() * deltaOpacity);
DOM.setStyleAttribute(element, "opacity", Float.toString(opacity));
incrementStep();
if (getStepCount() == numberOfSteps) {
DOM.setStyleAttribute(element, "opacity", Float.toString(endOpacity));
this.cancel();
}
}
};
timer.scheduleRepeating(stepLengthMillis);
}
}
Calling code for instance:
new ElementFader().fade(image.getElement(), 0, 1, 1000); // one-second fade-in
new ElementFader().fade(image.getElement(), 1, 0, 1000); // one-second fade-out
You could use GwtQuery. It provides fadeIn & fadeOut effects (and many other JQuery goodies), it is cross-browser compatible and seems to be pretty active.

blackberry: AbsoluteFieldManager dont show custom fields

I'm trying to make a menu with an absolute layout that contains custom items extending Field. This items show well in the HorizontalFieldManager for example, but with the AbsoluteFieldManager it just shows a blank screen.
This is my code so far:
/********************
* CustomField.java *
********************/
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Keypad;
public class CustomField extends Field {
Bitmap img;
String s1, s2;
Font font;
int textColorUnfocused, textColorFocused, bgColorUnfocused, bgColorFocused;
public CustomField(long style) {
super(style);
}
public CustomField(Bitmap img, String s1, String s2) {// , long style) {
// super(style);
this.img = img;
this.s1 = s1;
this.s2 = s2;
this.font = Font.getDefault();
textColorUnfocused = 0x000000;
textColorFocused = 0xffffff;
bgColorUnfocused = 0xffffff;
bgColorFocused = 0x3956F7;
}
protected void layout(int maxWidth, int maxHeight) {
Font font = getFont();
int width = img.getWidth() + 10;
int height = img.getHeight() + (font.getHeight() * 3);
setExtent(Math.min(width, maxWidth), Math.min(height, maxHeight));
}
protected void onFocus(int direction) {
super.onFocus(direction);
invalidate();
}
protected void onUnfocus() {
super.onUnfocus();
invalidate();
}
public boolean isFocusable() {
return true;
}
protected void paint(Graphics g) {
// Draw background
g.setColor(isFocus() ? bgColorFocused : bgColorUnfocused);
g.fillRect(0, 0, getWidth(), getHeight());
// draw image
g.drawBitmap(5, 5, img.getWidth(), img.getHeight(), img, 0, 0);
g.setColor(isFocus() ? textColorFocused : textColorUnfocused);
// draw text
g.drawText(s1, ((img.getWidth() + 10) / 2) - (font.getAdvance(s1) / 2),
img.getHeight() + font.getHeight());
g.drawText(s2, ((img.getWidth() + 10) / 2) - (font.getAdvance(s2) / 2),
img.getHeight() + (2 * font.getHeight()));
}
protected boolean keyChar(char character, int status, int time) {
if (character == Keypad.KEY_ENTER) {
fieldChangeNotify(0);
return true;
}
return super.keyChar(character, status, time);
}
public int getY() {
return img.getHeight() + (font.getHeight() * 3);
}
public int getX() {
return img.getWidth();
}
}
/**************
* MyApp.java *
**************/
import net.rim.device.api.ui.UiApplication;
public class MyApp extends UiApplication{
public static void main(String args[]){
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp()
{
// Push a screen onto the UI stack for rendering.
pushScreen(new MyScreen());
}
}
/*****************
* MyScreen.java *
*****************/
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.container.AbsoluteFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
public class MyScreen extends MainScreen {
public MyScreen() {
AbsoluteFieldManager manager = new AbsoluteFieldManager();
Bitmap img = Bitmap.getBitmapResource("1.png");
CustomField cf1 = new CustomField(img, "an", "Item");
CustomField cf2 = new CustomField(img, "another", "Item");
manager.add(cf1, 10, 10);
manager.add(cf2, 150, 150);
//HorizontalFieldManager hfm = new HorizontalFieldManager(
// Manager.HORIZONTAL_SCROLL);
//hfm.add(cf1); hfm.add(cf2);
//add(hfm);
add(manager);
}
}
And the image (1.png) http://www7.pic-upload.de/14.05.11/rhr4jcfuy9f8.png
How can I get the absolute manager to show my custom field?
My guess is that maybe AbsoluteFieldManager is passing 0, 0 to the layout method of your custom field. So your logic in there is calling setExtent(0, 0).

BlackBerry - Custom menu toolbar

I'm a beginner in BlackBerry programming, I need to replace in my application the default menu (when you press the menu button) by a custom menu, horizontal. The best to describe is I want the same result as the WeatherEye application for BlackBerry...
alt text http://www.blackberrybing.com/resource/pics/201002/WeatherEye-OS-45.jpg
I know how to create the default menu, but this one I have no idea!
Thank you,
What you will need to do is:
create SizebleVFManager (contentManager) as an extension of VerticalFieldManager
set display width and height = (display height - menu height) size to contentManager
add contentManager to screen
create HorizontalFieldManager (menuManager)
create BitmapButtonField (menuButton) as an extension of ButtonField
set FieldChangeListeners to menuButtons
add menuButtons to menuManager
add menuManager to screen
Sample of SizebleVFManager :
class SizebleVFManager extends VerticalFieldManager
{
int mWidth = 0;
int mHeight = 0;
public SizebleVFM(int width, int height, long style) {
super(style);
mWidth = width;
mHeight = height;
}
public SizebleVFM(int width, int height) {
mWidth = width;
mHeight = height;
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void sublayout(int width, int height) {
width = getPreferredWidth();
height = getPreferredHeight();
super.sublayout(width, height);
setExtent(width, height);
}
}
...
SizebleVFManager contentManager =
new SizebleVFManager(Display.getWidth(), Display.getHeight(),
VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
See also
sample of BitmapButtonField and Toolbar
PS though its better to use standard menu...
UPDATE
If you want to disable default menu functionality, cancel MENU keydown:
protected boolean keyDown(int keycode, int time) {
if(Keypad.KEY_MENU == Keypad.key(keycode))
{
return true;
}
else
return super.keyDown(keycode, time);
}
UPDATE
I've installed that wonderful weather application and understood this sample may be more alike with several improvements:
use CyclicHFManager as an extension of HorizontalFieldManager
show/hide menuManager on Menu button click
CyclicHFManager is a manager which will keep focus on the same place visually and run all fields over, in cycle. Like in BlackBerry - Custom centered cyclic HorizontalFieldManager
class CyclicHFManager extends HorizontalFieldManager {
int mFocusedFieldIndex = 0;
boolean mCyclicTurnedOn = false;
public void focusChangeNotify(int arg0) {
super.focusChangeNotify(arg0);
if (mCyclicTurnedOn) {
int focusedFieldIndexNew = getFieldWithFocusIndex();
if (focusedFieldIndexNew != mFocusedFieldIndex) {
if (focusedFieldIndexNew - mFocusedFieldIndex > 0)
switchField(0, getFieldCount() - 1);
else
switchField(getFieldCount() - 1, 0);
}
}
else
{
mFocusedFieldIndex = getFieldWithFocusIndex();
}
}
private void switchField(int prevIndex, int newIndex) {
Field field = getField(prevIndex);
delete(field);
insert(field, newIndex);
}
}
alt text http://img109.imageshack.us/img109/6176/toolbarj.jpg
And whole code sample:
abstract class AScreen extends MainScreen {
boolean mMenuEnabled = false;
SizebleVFManager mContentManager = null;
CyclicHFManager mMenuManager = null;
public AScreen() {
mContentManager = new SizebleVFManager(Display.getWidth(), Display
.getHeight(), VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
add(mContentManager);
// mMenuManager = new CyclicHFManager(Display.getWidth(), 60);
mMenuManager = new CyclicHFManager();
mMenuManager.setBorder(BorderFactory.createBevelBorder(new XYEdges(4,
0, 0, 0), new XYEdges(Color.DARKBLUE, 0, 0, 0), new XYEdges(
Color.WHITE, 0, 0, 0)));
mMenuManager.setBackground(BackgroundFactory
.createLinearGradientBackground(Color.DARKBLUE, Color.DARKBLUE,
Color.LIGHTBLUE, Color.LIGHTBLUE));
for (int i = 0; i < 10; i++) {
Bitmap nBitmap = new Bitmap(60, 60);
Graphics g = new Graphics(nBitmap);
g.setColor(Color.DARKBLUE);
g.fillRect(0, 0, 60, 60);
g.setColor(Color.WHITE);
g.drawRect(0, 0, 60, 60);
Font f = g.getFont().derive(Font.BOLD, 40);
g.setFont(f);
String text = String.valueOf(i);
g.drawText(text, (60 - f.getAdvance(text)) >> 1, (60 - f
.getHeight()) >> 1);
Bitmap fBitmap = new Bitmap(60, 60);
g = new Graphics(fBitmap);
g.setColor(Color.DARKBLUE);
g.fillRect(0, 0, 60, 60);
g.setColor(Color.GOLD);
g.drawRect(0, 0, 60, 60);
g.setFont(f);
g.drawText(text, (60 - f.getAdvance(text)) >> 1, (60 - f
.getHeight()) >> 1);
BitmapButtonField button = new BitmapButtonField(nBitmap, fBitmap,
fBitmap);
button.setCookie(String.valueOf(i));
button.setPadding(new XYEdges(0, 18, 0, 18));
button.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
Dialog.inform("Button # " + (String) field.getCookie());
}
});
mMenuManager.add(button);
}
}
protected boolean keyDown(int keycode, int time) {
if (Keypad.KEY_MENU == Keypad.key(keycode)) {
if (mMenuManager.getManager() != null) {
delete(mMenuManager);
mMenuManager.mCyclicTurnedOn = false;
mContentManager.updateSize(Display.getWidth(), Display
.getHeight());
} else {
add(mMenuManager);
mMenuManager.getField(2).setFocus();
mMenuManager.mCyclicTurnedOn = true;
mContentManager.updateSize(Display.getWidth(), Display
.getHeight()
- mMenuManager.getHeight());
}
return true;
} else
return super.keyDown(keycode, time);
}
}
class FirstScreen extends AScreen {
public FirstScreen() {
mContentManager.add(new LabelField("This is a first screen"));
}
}
public class ToolbarMenuApp extends UiApplication {
public ToolbarMenuApp() {
pushScreen(new FirstScreen());
}
public static void main(String[] args) {
(new ToolbarMenuApp()).enterEventDispatcher();
}
}

Resources