Related
How can I implement Marquee effect in Java Swing
Here's an example using javax.swing.Timer.
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
/** #see http://stackoverflow.com/questions/3617326 */
public class MarqueeTest {
private void display() {
JFrame f = new JFrame("MarqueeTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String s = "Tomorrow, and tomorrow, and tomorrow, "
+ "creeps in this petty pace from day to day, "
+ "to the last syllable of recorded time; ... "
+ "It is a tale told by an idiot, full of "
+ "sound and fury signifying nothing.";
MarqueePanel mp = new MarqueePanel(s, 32);
f.add(mp);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
mp.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MarqueeTest().display();
}
});
}
}
/** Side-scroll n characters of s. */
class MarqueePanel extends JPanel implements ActionListener {
private static final int RATE = 12;
private final Timer timer = new Timer(1000 / RATE, this);
private final JLabel label = new JLabel();
private final String s;
private final int n;
private int index;
public MarqueePanel(String s, int n) {
if (s == null || n < 1) {
throw new IllegalArgumentException("Null string or n < 1");
}
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++) {
sb.append(' ');
}
this.s = sb + s + sb;
this.n = n;
label.setFont(new Font("Serif", Font.ITALIC, 36));
label.setText(sb.toString());
this.add(label);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
#Override
public void actionPerformed(ActionEvent e) {
index++;
if (index > s.length() - n) {
index = 0;
}
label.setText(s.substring(index, index + n));
}
}
I know this is a late answer, but I just saw another question about a marquee that was closed because it was considered a duplicate of this answer.
So I thought I'd add my suggestion which takes a approach different from the other answers suggested here.
The MarqueePanel scrolls components on a panel not just text. So this allows you to take full advantage of any Swing component. A simple marquee can be used by adding a JLabel with text. A fancier marquee might use a JLabel with HTML so you can use different fonts and color for the text. You can even add a second component with an image.
Basic answer is you draw your text / graphic into a bitmap and then implement a component that paints the bitmap offset by some amount. Usually marquees / tickers scroll left so the offset increases which means the bitmap is painted at -offset. Your component runs a timer that fires periodically, incrementing the offset and invalidating itself so it repaints.
Things like wrapping are a little more complex to deal with but fairly straightforward. If the offset exceeds the bitmap width you reset it back to 0. If the offset + component width > bitmap width you paint the remainder of the component starting from the beginning of the bitmap.
The key to a decent ticker is to make the scrolling as smooth and as flicker free as possible. Therefore it may be necessary to consider double buffering the result, first painting the scrolling bit into a bitmap and then rendering that in one go rather than painting straight into the screen.
Here is some code that I threw together to get you started. I normally would take the ActionListener code and put that in some sort of MarqueeController class to keep this logic separate from the panel, but that's a different question about organizing the MVC architecture, and in a simple enough class like this it may not be so important.
There are also various animation libraries that would help you do this, but I don't normally like to include libraries into projects only to solve one problem like this.
public class MarqueePanel extends JPanel {
private JLabel textLabel;
private int panelLocation;
private ActionListener taskPerformer;
private boolean isRunning = false;
public static final int FRAMES_PER_SECOND = 24;
public static final int MOVEMENT_PER_FRAME = 5;
/**
* Class constructor creates a marquee panel.
*/
public MarqueePanel() {
this.setLayout(null);
this.textLabel = new JLabel("Scrolling Text Here");
this.panelLocation = 0;
this.taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
MarqueePanel.this.tickAnimation();
}
}
}
/**
* Starts the animation.
*/
public void start() {
this.isRunning = true;
this.tickAnimation();
}
/**
* Stops the animation.
*/
public void stop() {
this.isRunning = false;
}
/**
* Moves the label one frame to the left. If it's out of display range, move it back
* to the right, out of display range.
*/
private void tickAnimation() {
this.panelLocation -= MarqueePanel.MOVEMENT_PER_FRAME;
if (this.panelLocation < this.textLabel.getWidth())
this.panelLocaton = this.getWidth();
this.textLabel.setLocation(this.panelLocation, 0);
this.repaint();
if (this.isRunning) {
Timer t = new Timer(1000 / MarqueePanel.FRAMES_PER_SECOND, this.taskPerformer);
t.setRepeats(false);
t.start();
}
}
}
Add a JLabel to your frame or panel.
ScrollText s= new ScrollText("ello Everyone.");
jLabel3.add(s);
public class ScrollText extends JComponent {
private BufferedImage image;
private Dimension imageSize;
private volatile int currOffset;
private Thread internalThread;
private volatile boolean noStopRequested;
public ScrollText(String text) {
currOffset = 0;
buildImage(text);
setMinimumSize(imageSize);
setPreferredSize(imageSize);
setMaximumSize(imageSize);
setSize(imageSize);
noStopRequested = true;
Runnable r = new Runnable() {
public void run() {
try {
runWork();
} catch (Exception x) {
x.printStackTrace();
}
}
};
internalThread = new Thread(r, "ScrollText");
internalThread.start();
}
private void buildImage(String text) {
RenderingHints renderHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
BufferedImage scratchImage = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_RGB);
Graphics2D scratchG2 = scratchImage.createGraphics();
scratchG2.setRenderingHints(renderHints);
Font font = new Font("Serif", Font.BOLD | Font.ITALIC, 24);
FontRenderContext frc = scratchG2.getFontRenderContext();
TextLayout tl = new TextLayout(text, font, frc);
Rectangle2D textBounds = tl.getBounds();
int textWidth = (int) Math.ceil(textBounds.getWidth());
int textHeight = (int) Math.ceil(textBounds.getHeight());
int horizontalPad = 600;
int verticalPad = 10;
imageSize = new Dimension(textWidth + horizontalPad, textHeight
+ verticalPad);
image = new BufferedImage(imageSize.width, imageSize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHints(renderHints);
int baselineOffset = (verticalPad / 2) - ((int) textBounds.getY());
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, imageSize.width, imageSize.height);
g2.setColor(Color.GREEN);
tl.draw(g2, 0, baselineOffset);
// Free-up resources right away, but keep "image" for
// animation.
scratchG2.dispose();
scratchImage.flush();
g2.dispose();
}
public void paint(Graphics g) {
// Make sure to clip the edges, regardless of curr size
g.setClip(0, 0, imageSize.width, imageSize.height);
int localOffset = currOffset; // in case it changes
g.drawImage(image, -localOffset, 0, this);
g.drawImage(image, imageSize.width - localOffset, 0, this);
// draw outline
g.setColor(Color.black);
g.drawRect(0, 0, imageSize.width - 1, imageSize.height - 1);
}
private void runWork() {
while (noStopRequested) {
try {
Thread.sleep(10); // 10 frames per second
// adjust the scroll position
currOffset = (currOffset + 1) % imageSize.width;
// signal the event thread to call paint()
repaint();
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
}
}
public void stopRequest() {
noStopRequested = false;
internalThread.interrupt();
}
public boolean isAlive() {
return internalThread.isAlive();
}
}
This is supposed to be an improvement of #camickr MarqueePanel. Please see above.
To map mouse events to the specific components added to MarqueePanel
Override add(Component comp) of MarqueePanel in order to direct all mouse events of the components
An issue here is what do do with the MouseEvents fired from the individual components.
My approach is to remove the mouse listeners form the components added and let the MarqueePanel redirect the event to the correct component.
In my case these components are supposed to be links.
#Override
public Component add(Component comp) {
comp = super.add(comp);
if(comp instanceof MouseListener)
comp.removeMouseListener((MouseListener)comp);
comp.addMouseListener(this);
return comp;
}
Then map the component x to a MarqueePanel x and finally the correct component
#Override
public void mouseClicked(MouseEvent e)
{
Component source = (Component)e.getSource();
int x = source.getX() + e.getX();
int y = source.getY();
MarqueePanel2 marqueePanel = (MarqueePanel2) ((JComponent)e.getSource()).getParent();
double x2 = marqueePanel.getWidth();
double x1 = Math.abs(marqueePanel.scrollOffset);
if(x >= x1 && x <= x2)
{
System.out.println("Bang " + x1);
Component componentAt = getComponentAt(x+marqueePanel.scrollOffset, y);
if(comp instanceof MouseListener)
((MouseListener) componentAt).mouseClicked(e);
System.out.println(componentAt.getName());
}
else
{
return;
}
//System.out.println(x);
}
How can I quickly and efficiently set all pixels of a BufferedImage to transparent so that I can simply redraw what sprite graphics I want for each frame?
I am designing a simple game engine in java that updates a background and foreground BufferedImage and draws them to a composite VolatileImage for efficient scaling, to be drawn to a JPanel. This scalable model allows me to add more layers and iterate over each drawing layer.
I simplified my application into one class given below that demonstrates my issue. Use the arrow keys to move a red square over the image. The challenge is I want to decouple updating the game graphics from drawing the composite graphics to the game engine. I have studied seemingly thorough answers to this question but cannot figure out how to apply them to my application:
Java: Filling a BufferedImage with transparent pixels
Here is the critical section that does not clear the pixels correctly. The commented out section is from stack-overflow answers I have read already, but they either draw the background as a non-transparent black or white. I know the foregroundImage begins with transparent pixels in my implementation as you can see the random pixel noise of the backgroundImage behind the red sprite when the application begins. Right now, the image is not cleared, so the previous drawn images remain.
/** Update the foregroundGraphics. */
private void updateGraphics(){
Graphics2D fgGraphics = (Graphics2D) foregroundImage.getGraphics();
// set image pixels to transparent
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
//fgGraphics.setColor(new Color(0,0,0,0));
//fgGraphics.clearRect(0, 0, width, height);
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw again.
fgGraphics.setColor(Color.RED);
fgGraphics.fillRect(sx, sy, spriteSize, spriteSize);
fgGraphics.dispose();
}
Here is my entire example code:
/**
* The goal is to draw two BufferedImages quickly onto a scalable JPanel, using
* a VolatileImage as a composite.
*/
public class Example extends JPanel implements Runnable, KeyListener
{
private static final long serialVersionUID = 1L;
private int width;
private int height;
private Object imageLock;
private Random random;
private JFrame frame;
private Container contentPane;
private BufferedImage backgroundImage;
private BufferedImage foregroundImage;
private VolatileImage compositeImage;
private Graphics2D compositeGraphics;
private int[] backgroundPixels;
private int[] foregroundPixels;
// throttle the framerate.
private long prevUpdate;
private int frameRate;
private int maximumWait;
// movement values.
private int speed;
private int sx;
private int sy;
private int dx;
private int dy;
private int spriteSize;
/** Setup required fields. */
public Example(){
width = 512;
height = 288;
super.setPreferredSize(new Dimension(width, height));
imageLock = new Object();
random = new Random();
frame = new JFrame("BufferedImage Example");
frame.addKeyListener(this);
contentPane = frame.getContentPane();
contentPane.add(this, BorderLayout.CENTER);
// used to create hardware-accelerated images.
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
backgroundImage = gc.createCompatibleImage(width, height,Transparency.TRANSLUCENT);
foregroundImage = gc.createCompatibleImage(width, height,Transparency.TRANSLUCENT);
compositeImage = gc.createCompatibleVolatileImage(width, height,Transparency.TRANSLUCENT);
compositeGraphics = compositeImage.createGraphics();
compositeGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
compositeGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
backgroundPixels = ((DataBufferInt) backgroundImage.getRaster().getDataBuffer()).getData();
foregroundPixels = ((DataBufferInt) foregroundImage.getRaster().getDataBuffer()).getData();
//initialize the background image.
for(int i = 0; i < backgroundPixels.length; i++){
backgroundPixels[i] = random.nextInt();
}
// used to throttle frames per second
frameRate = 180;
maximumWait = 1000 / frameRate;
prevUpdate = System.currentTimeMillis();
// used to update sprite state.
speed = 1;
dx = 0;
dy = 0;
sx = 0;
sy = 0;
spriteSize = 32;
}
/** Renders the compositeImage to the Example, scaling to fit. */
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// draw the composite, scaled to the JPanel.
synchronized (imageLock) {
((Graphics2D) g).drawImage(compositeImage, 0, 0, super.getWidth(), super.getHeight(), 0, 0, width, height, null);
}
// force repaint.
repaint();
}
/** Update the BufferedImage states. */
#Override
public void run() {
while(true){
updateSprite();
updateGraphics();
updateComposite();
throttleUpdateSpeed();
}
}
/** Update the Sprite's position. */
private void updateSprite(){
// update the sprite state from the inputs.
dx = 0;
dy = 0;
if (Command.UP.isPressed()) dy -= speed;
if (Command.DOWN.isPressed()) dy += speed;
if (Command.LEFT.isPressed()) dx -= speed;
if (Command.RIGHT.isPressed()) dx += speed;
sx += dx;
sy += dy;
// adjust to keep in bounds.
sx = sx < 0 ? 0 : sx + spriteSize >= width ? width - spriteSize : sx;
sy = sy < 0 ? 0 : sy + spriteSize >= height ? height - spriteSize : sy;
}
/** Update the foregroundGraphics. */
private void updateGraphics(){
Graphics2D fgGraphics = (Graphics2D) foregroundImage.getGraphics();
// set image pixels to transparent
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
//fgGraphics.setColor(new Color(255, 255, 255, 255));
//fgGraphics.clearRect(0, 0, width, height);
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw again.
fgGraphics.setColor(Color.RED);
fgGraphics.fillRect(sx, sy, spriteSize, spriteSize);
fgGraphics.dispose();
}
/** Draw the background and foreground images to the volatile composite. */
private void updateComposite(){
synchronized (imageLock) {
compositeGraphics.drawImage(backgroundImage, 0, 0, null);
compositeGraphics.drawImage(foregroundImage, 0, 0, null);
}
}
/** Keep the update rate around 60 FPS. */
public void throttleUpdateSpeed(){
try {
Thread.sleep(Math.max(0, maximumWait - (System.currentTimeMillis() - prevUpdate)));
prevUpdate = System.currentTimeMillis();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
/** Ignore key typed events. */
#Override
public void keyTyped(KeyEvent e) {}
/** Handle key presses. */
#Override
public void keyPressed(KeyEvent e) {
setCommandPressedFrom(e.getKeyCode(), true);
}
/** Handle key releases. */
#Override
public void keyReleased(KeyEvent e) {
setCommandPressedFrom(e.getKeyCode(), false);
}
/** Switch over key codes and set the associated Command's pressed value. */
private void setCommandPressedFrom(int keycode, boolean pressed){
switch (keycode) {
case KeyEvent.VK_UP:
Command.UP.setPressed(pressed);
break;
case KeyEvent.VK_DOWN:
Command.DOWN.setPressed(pressed);
break;
case KeyEvent.VK_LEFT:
Command.LEFT.setPressed(pressed);
break;
case KeyEvent.VK_RIGHT:
Command.RIGHT.setPressed(pressed);
break;
}
}
/** Commands are used to interface with key press values. */
public enum Command{
UP, DOWN, LEFT, RIGHT;
private boolean pressed;
/** Press the Command. */
public void press() {
if (!pressed) pressed = true;
}
/** Release the Command. */
public void release() {
if (pressed) pressed = false;
}
/** Check if the Command is pressed. */
public boolean isPressed() {
return pressed;
}
/** Set if the Command is pressed. */
public void setPressed(boolean pressed) {
if (pressed) press();
else release();
}
}
/** Begin the Example. */
public void start(){
try {
// create and display the frame.
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
Example e = new Example();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
// start updating from key inputs.
Thread t = new Thread(this);
t.start();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
/** Start the application. */
public static void main(String[] args){
Example e = new Example();
e.start();
}
}
Edits:
- Fixed a typo in the for-loop initializing the backgroundPixels to random.
Turns out I goofed in my method selection. I noticed I was clearing a one-pixel wide box that was the outline of my graphics. This is because I accidentally used drawRect() instead of fillRect(). Upon changing my code it works now. Here are examples I was able to get to work.
Example using AlphaComposite.CLEAR (draw with any opaque color):
// clear pixels
fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
fgGraphics.setColor(new Color(255,255,255,255));
fgGraphics.fillRect(0, 0, width, height);
fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw new graphics
Example using AlphaComposite.SRC_OUT (draw with any color with alpha zero):
// clear pixels
fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OUT));
fgGraphics.setColor(new Color(255,255,255,0));
fgGraphics.fillRect(0, 0, width, height);
fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw new graphics
I'm not sure if this is the right place to ask, but I'm wondering if there is something like 9 patch images on android, but for Java, like Oracle, PC java. All my google searches only show me android because people call that Java, but it's not really the same.
I've found LibGdx but it's quite hefty for the single nine-patch ability that I'm looking for.
A nine patch image is one that has '9' areas, with the corners being 'not scaled' typically while the side walls and the center area stretched to fit the screen.
An example from Android: http://developer.android.com/tools/help/draw9patch.html
Does anyone know anything that can scale like this? I need something that can support PNG.
If you are searching a way to use a 9-patch image on a Java component I asked the same question here: How use a 9-patch image as background on a JPanel? and the short answer is no, you can not.
The long one is: You can if you split the image in the 9 images (borders, corners and center) and create a component that when is repainted moves and resizes the images.
The example that follows is adapted for my case where:
The component is a JPanel.
The center of the panel has to be transparent, so I need one image less.
The component is not going to be smaller than the given images.
Images have transparences, this explains the setOpaque(false) calls in the code.
The code is a rough draft.
Here the code:
public class NinePatchLikePanel extends JPanel{
private JPanel corner_top_l;
private JPanel corner_top_r;
private JPanel corner_bot_l;
private JPanel corner_bot_r;
private JPanel border_ver_l;
private JPanel border_ver_r;
private JPanel border_hoz_t;
private JPanel border_hoz_b;
private int min_width, min_height;
private int corners_width;
private int corners_height;
private int borders_width;
private int borders_height;
public NinePatchLikePanel (String[] urls) {
if(urls.length != 8) {
throw new UnsupportedOperationException("Exception to be managed!");
} else {
corner_top_l = new JPanelWithBackground (urls [0]);
corner_top_r = new JPanelWithBackground (urls [1]);
corner_bot_r = new JPanelWithBackground (urls [2]);
corner_bot_l = new JPanelWithBackground (urls [3]);
border_hoz_t = new JPanelWithBackground (urls [4]);
border_ver_r = new JPanelWithBackground (urls [5]);
border_hoz_b = new JPanelWithBackground (urls [6]);
border_ver_l = new JPanelWithBackground (urls [7]);
corners_width = corner_top_l.getWidth();
corners_height = corner_top_l.getHeight();
borders_width = border_hoz_t.getWidth();
borders_height = border_ver_l.getHeight();
min_width = 2 * corners_width + borders_width;
min_height = 2 * corners_height + borders_height;
this.setSize (min_width, min_height );
this.setMinimumSize ( new Dimension (min_width, min_height) );
this.setOpaque(false);
this.setLayout(null);
this.add(corner_top_l);
this.add(corner_top_r);
this.add(corner_bot_l);
this.add(corner_bot_r);
this.add(border_hoz_t);
this.add(border_ver_r);
this.add(border_hoz_b);
this.add(border_ver_l);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int actual_width = this.getWidth();
int actual_height = this.getHeight();
int _x = actual_width - corners_width;
int _y = actual_height - corners_height;
corner_top_l.setLocation(0, 0);
corner_top_r.setLocation(_x, 0);
corner_bot_l.setLocation(0, _y);
corner_bot_r.setLocation(_x, _y);
int new_borders_width = _x - corners_width;
int new_borders_height = _y - corners_height;
border_hoz_t.setLocation(corners_width, 0);
border_hoz_t.setSize(new_borders_width, border_hoz_t.getHeight());
border_ver_r.setLocation(_x, corners_height);
border_ver_r.setSize(border_ver_r.getWidth(), new_borders_height);
border_hoz_b.setLocation(corners_width, _y);
border_hoz_b.setSize(new_borders_width, border_hoz_b.getHeight());
border_ver_l.setLocation(0, corners_height);
border_ver_l.setSize(border_ver_l.getWidth(), new_borders_height);
}
}
Here the code for the JPanelWithBackground class:
public class JPanelWithBackground extends JPanel {
Image bg = null;
public JPanelWithBackground(String url) {
try{
bg = ImageIO.read(getClass().getResourceAsStream(url));
int height = bg.getHeight(null);
int width = bg.getWidth(null);
Dimension d = new Dimension(width,height);
this.setSize (width, height);
this.setMinimumSize ( d );
this.setOpaque(false);
} catch (IOException ex) {
//TODO: Manage this exception in a better way
System.err.println(ex);
System.exit(1);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null)
g.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
I am developing one app in which I want to create two buttons. These buttons should be center aligned custom buttons with bitmap fill backgrounds. Each should also contain text that is centered in that button.
The problem is that those two buttons are not set properly. The second button is gone behind the first and its bitmap height is also decreased compared to the first button.
For both custom buttons I have the same CustomButton class.
Here is code:
CustomButtonField aboutM1 = new CustomButtonField(0,"About G1",registerbg,registerbg,Field.FOCUSABLE,0x324F85);
add(new RichTextField(Field.NON_FOCUSABLE));
// CustomButtonField2 ForgotPass = new CustomButtonField2("Forgot Password?",0x324F85);
CustomButtonField ForgotPass = new CustomButtonField(0,"Forgot Password?",registerbg,registerbg,Field.FOCUSABLE,0x324F85);
add(new RichTextField(Field.NON_FOCUSABLE));
VerticalFieldManager bottomVFM = new VerticalFieldManager(USE_ALL_WIDTH);
HorizontalFieldManager bottomHFM = new HorizontalFieldManager(FIELD_HCENTER);
bottomHFM.add(aboutM1);
bottomHFM.add(ForgotPass);
bottomVFM.add(bottomHFM);
add(bottomVFM);
Custom Button:
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;
public class CustomButtonField extends Field
{
Bitmap Unfocus_img, Focus_img, current_pic;
int width;
String text;
Font font;
int custColor;
CustomButtonField(int width, String text, Bitmap onFocus, Bitmap onUnfocus, long style,int custColor)
{
super(style);
Unfocus_img = onUnfocus;
Focus_img = onFocus;
current_pic = onFocus;
this.text = text;
this.width = width;
this.custColor = custColor;
}
protected void layout(int width, int height)
{
setExtent(current_pic.getWidth(), current_pic.getHeight());
}
protected void paint(Graphics graphics)
{
try
{
FontFamily fntFamily = FontFamily.forName("BBAlpha Sans");
font = fntFamily.getFont(Font.BOLD,20);
}
catch(Exception e)
{
font = Font.getDefault();
}
graphics.setFont(font);
graphics.setColor(custColor);
int xText = (getWidth() - font.getAdvance(text)) / 2;
int yText = (getHeight() - font.getHeight()) / 2;
graphics.drawBitmap(0, 0, current_pic.getWidth(), current_pic.getHeight(), current_pic , 0 , 0);
graphics.drawText(text, xText, yText);
/* graphics.drawBitmap(0, 0, current_pic.getWidth(), current_pic.getHeight(), current_pic , 0 , 0);
graphics.drawText(text, width , 7);*/
graphics.setDrawingStyle(Graphics.HCENTER | Graphics.VCENTER, true);
}
protected void onFocus(int direction)
{
super.onFocus(direction);
current_pic = Unfocus_img;
this.invalidate();
}
protected void drawFocus(Graphics graphics, boolean on)
{
}
protected void onUnfocus()
{
super.onUnfocus();
current_pic = Focus_img;
invalidate();
}
public boolean isFocusable() {
return true;
}
protected boolean navigationClick(int status, int time) {
fieldChangeNotify(0);
return true;
}
}
The code you used is correct , the only drawback is that you are centering your text according to your bitmap width & text length is more than bitmap width .
You may need to change your approach .
Have a look on Blackberry UI samples in this below URL & check for EmbossedButtonField Demo
https://github.com/blackberry/Samples-for-Java
Its a good approach to create a custom button , once we are not sure by the button label length.
Sorry guys, I deleted my APPLES and CATS example :) Here's the updated version of my question!
I'm losing my sanity here. I need someone who can enlighten me. I've tried a couple of times explaining my problem here. Hopefully, this time, my question will be easier to understand.
Basically I have this frame, and there's an image displayed. There is a JList on the right, and there is another panel for JLabels at the bottom. Here's a screencap of my frame.
When I click on the image, a JOptionPane pops out, like so. And I enter my input. My JList is an ArrayList, so everything I input is added to the JList and the JPanel at the bottom.
Now, when I hover on the the part where I clicked, you noticed that the square disappeared). It only appears when I click the image, and when I hover the label at the bottom. My labels, as of now are LOLZ NOSE and INPUT HERE.
What I want to do is when I hover on the label, for example INPUT HERE, it shows the square again, featuring the part where I clicked. My problem now is when I click on NOSE, which is supposed to be showing a square on the nose part and a the name NOSE with black bg, IT IS NOT SHOWING. Also, only the last label's square is shown, disregarding the other labels' position clicked.
How do I get a label to remember the position of the click I make? People said I should use ArrayLists or HashCodes however I have no idea how to implement them. Thank you to anyone who can help.
Edit: I've already done the rectangle, btw. It's showing only for the last label inputted. Here are some of the code snippets requested!
How I'm setting the text on JLabel and updating the JList:
public void updateLabel(){
StringBuilder text = new StringBuilder(); //creates empty builder, capacity 16
for(Object s: tagModel.toArray()) //returns an array containing the elements of the tagModel
text.append(" " + s);
repaint();
hoverLabel.setText(text.toString()); //returns a String
hoverLabel.addMouseMotionListener(this);
hoverPanel.add(hoverLabel);
}
My mouseListener upon click:
#Override
public void mouseClicked(MouseEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
isRectPresent = true;
repaint();
input = JOptionPane.showInputDialog("Enter tag name:");
if((input != null) && !input.isEmpty()){
tagModel.addElement(input);
}
}
My mouseMotionListener upon hovering:
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
xpos = e.getX(); //gets where the mouse moved
ypos = e.getY();
//checks if the mouse is inside the bounds of the rectangle
if (xpos > x && xpos < x + 100 && ypos > y && ypos < y + 100)
isRectPresent = false;
if(e.getSource() == hoverLabel){
isRectPresent = true;
repaint();
}
repaint();
}
How I'm painting:
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, 0, 0, null);
if(image != null && isRectPresent){
Stroke stroke = g2.getStroke();
g2.setStroke(new BasicStroke(4));
g2.setColor(Color.WHITE);
g2.drawRect(x-50, y-50, 100, 100);
g2.setStroke(stroke);
}else{
if(xpos > x && xpos < x + 100 && ypos > y && ypos < y + 100){
g.setColor(Color.BLACK);
g.fillRect(x-50, y-50, 100, 25);
g.setColor(Color.WHITE);
g.setFont(new Font("Tahoma", Font.BOLD, 12));
g.drawString(input, x-30, y-30);
}
}
}
If you want me to add some more snippets, just tell me! :)
You should create a HashMap, say something like:
Map linkSet = new HashMap();
And whenever you click on the drawing and create a label, add the JLabel and the point on the image to the set using the put method with the JLabel as the key and the Point as the value. Then in the JLabel's MouseMotionListener, use your label as a key and obtain the corresponding point from the set using the map's get(...) method.
edit:
Corrected as per alicedimarco's comment. Again, thanks!
edit 2
I think you want again to use a Map. If you have a Map, you can have it retrieve the Point of interest from the JLabel's or the JList's String, and then pass this Point to the class that's drawing the image and let it use the Point to draw a rectangle. For instance you could give the image drawing class a Point field called displayPoint, and a method called setDisplayPoint(Point p). It can be as simple as this:
public void setDisplayPoint(Point p) {
this.displayPoint = p;
repaint();
}
and assuming that the object of interest is centered at that point, use the displayPoint in the paintComponent method:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// draw image
if (img != null) {
g.drawImage(img, X_SHIFT, Y_SHIFT, null);
}
// if displayPoint not null, draw the surrounding rectangle
if (displayPoint != null) {
g.setColor(RECT_COLOR);
int x = displayPoint.x - RECT_WIDTH / 2;
int y = displayPoint.y - RECT_WIDTH / 2;
int width = RECT_WIDTH;
int height = RECT_WIDTH;
g.drawRect(x, y, width, height);
}
}
edit 3:
To get mouse clicks, it's quite easy, simply add a MouseListener to the component that holds the image:
// !! added
imgRect.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
imgMousePressed(e);
}
});
And in your code that is called from this mouse listener, use a JOptionPane to get the user's choice of tag name, and add the resulting String to both the listDataModel so that it is seen in the JList and also in the stringPointMap together with the Point obtained from the MouseEvent so that you can map the String to the Point and be able to retrieve it:
// !! added
private void imgMousePressed(MouseEvent e) {
String result = JOptionPane.showInputDialog(this,
"Please enter name for this point on image:");
if (result != null) {
stringPointMap.put(result, e.getPoint());
listDataModel.addElement(result);
}
}
That's it.
Then putting it all together:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ImageRectMain extends JPanel {
private ImageRect imgRect;
private DefaultListModel listDataModel = new DefaultListModel();
private JList list = new JList(listDataModel);
private Map<String, Point> stringPointMap = new HashMap<String, Point>();
public ImageRectMain() {
String nose = "Nose";
String ear = "Ear";
String rightEye = "Right Eye";
String leftEye = "Left Eye";
listDataModel.addElement(ear);
listDataModel.addElement(nose);
listDataModel.addElement(rightEye);
listDataModel.addElement(leftEye);
stringPointMap.put(nose, new Point(480, 500));
stringPointMap.put(ear, new Point(270, 230));
stringPointMap.put(rightEye, new Point(380, 390));
stringPointMap.put(leftEye, new Point(662, 440));
MouseAdapter listMouseAdapter = new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
listMouseMoved(e);
}
#Override
public void mouseExited(MouseEvent e) {
listMouseExited(e);
}
};
list.addMouseMotionListener(listMouseAdapter);
list.addMouseListener(listMouseAdapter);
try {
imgRect = new ImageRect();
// !! added
imgRect.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
imgMousePressed(e);
}
});
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.PAGE_AXIS));
eastPanel.add(new JLabel("You have tagged the following:"));
eastPanel.add(new JScrollPane(list));
eastPanel.add(Box.createVerticalGlue());
eastPanel.add(Box.createVerticalGlue());
eastPanel.add(Box.createVerticalGlue());
eastPanel.add(Box.createVerticalGlue());
setLayout(new BorderLayout());
add(imgRect, BorderLayout.CENTER);
add(eastPanel, BorderLayout.EAST);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// !! added
private void imgMousePressed(MouseEvent e) {
String result = JOptionPane.showInputDialog(this,
"Please enter name for this point on image:");
if (result != null) {
stringPointMap.put(result, e.getPoint());
listDataModel.addElement(result);
}
}
private void listMouseExited(MouseEvent e) {
imgRect.setDisplayPoint(null);
}
private void listMouseMoved(MouseEvent e) {
int index = list.locationToIndex(e.getPoint());
Object value = listDataModel.get(index);
if (value != null) {
Point point = stringPointMap.get(value.toString());
if (point != null) {
imgRect.setDisplayPoint(point);
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ImageRectMain");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ImageRectMain());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ImageRect extends JPanel {
public static final String IMAGE_PATH = "http://i.stack.imgur.com/7oNzg.jpg";
private static final int DEFAULT_W = 687;
private static final int DEFAULT_H = 636;
private static final int X_SHIFT = -6;
private static final int Y_SHIFT = -26;
private static final Color RECT_COLOR = Color.pink;
private static final int RECT_WIDTH = 40;
private BufferedImage img;
private Point displayPoint = null;
public ImageRect() throws MalformedURLException, IOException {
img = ImageIO.read(new URL(IMAGE_PATH));
}
public void setDisplayPoint(Point p) {
this.displayPoint = p;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, X_SHIFT, Y_SHIFT, null);
}
if (displayPoint != null) {
g.setColor(RECT_COLOR);
int x = displayPoint.x - RECT_WIDTH / 2;
int y = displayPoint.y - RECT_WIDTH / 2;
int width = RECT_WIDTH;
int height = RECT_WIDTH;
g.drawRect(x, y, width, height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(DEFAULT_W, DEFAULT_H);
}
}
One nice feature of a JList is that you can story any object in it. You're not limited to strings. When objects are stored in JLists, swing will call the object's toString() method, and display it in the list.
Knowing this, you can now write your own class that stores the name of your selection label and the coordinates of the box. This object's toString() method will return the name of the label, which will make the right thing appear in the JList.
Then, in the selection event handler for the JList, you can get your custom object out, and retrieve the box coordinates stored in it, and draw them on the screen. No need to fuss with other containers (although knowing how to use them is a good thing to).
Ok, Create a class like this...
public class MyLabel {
private int x;
private int y;
private String text;
public MyLabel (String text, int x, int y) {
this.text = text;
// assign x and y too...
}
#Override
public String toString() {
return label;
}
public int getX() {
return x;
}
// similar function to getY()
}
The class above overrides toString(), so when you put it in a JList, it will use the call to toString() to determine what to display, and since this toString implementation returns the label name you'll see that in the list.
And add those into your JList instead of Strings. Then at some point in your code you'll do something like this...
// this is pseudocode, method names may not be correct...
MyLabel ml = (MyLabel)jList.getSelectedItem();
int x = ml.getX();
int y = ml.getY();
// draw the box...
Hope that helps.