Swing formatting issues - graphics

In an attempt to create a checkerboard type grid, I found myself frustrated. Coding it was easy enough, but the outcome isn't quite right. I know my code is right because I even had someone else whose a much better programmer than I check it out. The problem is that the first two rows, though alternating, start on the same color. I even tried ignoring it, and hardcoding over it, but whenever I used Color.white for those two rows, it came out black. I'm looking for suggestions as how to fix this problem. Or in case I did make a logical error and neither me or my friend caught it, I'm hoping one of you can.
public class Checkers1 extends JFrame {
public void paint(Graphics g){
//checker-board
for(int x=0, t=0; x<8 && t>=0; x++,t++){
for(int y=0; y<8; y++, t++){
if(t%2==0|| t==0){
g.fillRect(x*80, y*80, 80, 80);
g.setColor(Color.black);
}
else{
g.fillRect(x*80, y*80, 80, 80);
g.setColor(Color.white);
}
}
}
}
public Checkers1(){
setSize(640,640);
setVisible(true);
setResizable(false);
}
public static void main(String[] args) {
Checkers1 b=new Checkers1();
}
}

Related

Type Writer Effect in JTextPane

i'm pretty new to coding (about 5 months) and i've been trying to make a custom terminal for a text based RPG. so far i have the terminal working the way it should but i'm looking for ways to rewrite the code to come up with a typewriter effect. here's the code i have for writing the text onto a JTextPane but the code i'm trying to merge doesn't work all too well since i do feel like i am missing something. i've tried searching for what but couldn't find too many answers.
public void print(String s, boolean trace) {
print(s, trace, new Color(255,255,255), startFont);
}
public void print(String s, boolean trace, Color c, boolean startFont) {
Style style = console.addStyle("Style", null);
StyleConstants.setForeground(style, c);
if (trace) {
Throwable t = new Throwable();
StackTraceElement[] elements = t.getStackTrace();
String caller = elements[0].getClassName();
s = caller + " -> " + s;
}
if (startFont) {
console.setFont(new Font("Bookman Old Style", Font.ITALIC, 87));
}
try {
document.insertString(document.getLength(), s, style);
} catch(Exception ex) {}
}
public void println(String s, boolean trace) {
println(s, trace, new Color(255, 255, 255));
}
public void println(String s, boolean trace, Color c) {
print(s + "\n", trace, c, startFont);
}
here's the code that i'm trying to implement: Java typewriter effect
when i do use the "g.drawString" method i ususally get an error saying that "g" is null which makes me think that i am missing something and that "g.drawString" would work but i'm very unsure.
i have some ideas on what i should do like maybe try to make the main string public without anything to it/making it into an array or trying to make a whole new render itself for the JTextPane to get the effect but i've had no luck so far. anyone's got any ideas if it's even possible?

Why does my RotateTransition throw errors after it runs for the first time?

Warning: This is my first time using threads and my first time trying out an animation. Please bear with me.
I want to rotate an ImageView. I set up a thread for it:
public class ThreadAnimation extends Thread
{
private ImageView iv;
private RotateTransition rt;
public ThreadAnimation(ImageView iv)
{
this.iv = iv;
}
#Override
public void run()
{
while (true)
{
RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);
r.play();
try
{
sleep(100);
} catch (InterruptedException e)
{
return;
}
}
}
}
I call this inside my controller class, upon pressing a Button.
animation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle (ActionEvent abschicken)
{
ThreadAnimation thread = null; //ANIMATION PIZZA
if (thread == null)
{
thread = new ThreadAnimation(olivenview);
thread.start();
}
}
});
My ImageView olivenview will rotate just like I wanted it to. However it takes quite a long time until it seems to stop (I can see it because the button triggering it still looks triggered for a while) and when I go ahead to press it a second time afterwards, I get a nonstop error stream with a lot of null pointer exceptions. I am very clueless, can anyone help me out? Is this due to my Thread Setup or does the problem lie somewhere else (in code that I didn't post here)?
I believe you do not need threads for this. Notice the .play() method returns immediately and the animation will run in the background.
That being said, try this.
...
//Create your rotation
final RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);
//When the button is pressed play the rotation. Try experimenting with .playFromStart() instead of .play()
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent action) {
r.play();
}
});
...
On an other note I recommend switching to java 8 so that you can use lambda expressions instead of the anonymous class!

Blackberry Thread Image from JSON

I am looking for a way to display images on my ListField from a background thread. First in my drawListRow i try this
path = (String) imagePaths.elementAt(index);
bit = connectServerForImage(path);
g.drawBitmap(xText, y + yText, 80, 200, bit, 0, 0);
but can't scroll smoothly throughout the list, and they say do not do networking or other blocking operations on the UI. But i also try this
private class imgConnection extends Thread
{
public imgConnection() {
super();
}
public void run() {
try {
for (int i = 0; i < imagePaths.size(); i++)
{
final int index = i;
String path = imagePaths.elementAt(index).toString();
bit = connectServerForImage(path);
image.addElement(bit);
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_list.setSize(image.size());
subManager.add(_list);
screen.invalidate();
}
});
}
}
public void drawListRow(ListField list, Graphics g, int index, int y, int w) {
bit = (Bitmap) image.elementAt(index);
g.drawBitmap(xText, y + yText, 80, 200, bit, 0, 0);
}
but nothing happens. Any idea, comments.
You are right, i just started java development 2 weeks ago particularly BB development and i try this link. I want to add a background thread to download image after i got the path url from json return.
first thread:
_connectionthread = new Connection();
_connectionthread.start();
private class Connection extends Thread
{
public Connection()
{
super();
}
public void run() {
try {}
catch (Exception e) {}
}
}
second thread:
_imgConnectionThread = new ImgConnection();
_imgConnectionThread.start();
private class ImgConnection extends Thread
{
public ImgConnection() {
super();
}
public void run() {
try {
}
catch (Exception e)
{
}
}
}
how to update images on ListField?
Answer is based on code from - pastebin.com/90UKTHzP
Terrible code! It's really hard to read and undersand! It looks like you copy pasted several examples from different locations. Also you overriding default behavior with same behavior. Also MainScreen already has VerticalManagerField. Also you're adding list every iteration to manager which will cause IAE. And main one thread is depended on result of second one. They start at the same time, but getting json from server and it's processing could take longer time, so image thread most probably will finish his run without any result.
So main recommendation to fix it - read clean code book! Read more about java development - conventions, multithreading. Read about BB development - UI api, networking.
And finally - start only one thread to get and parse json. After you get it finished - start another thread to get images.
There some minor things that could save you more battery and processor time also - start loading images on demand - when it painted or going to be painted (user scrolls list).
By convention, Java class names start with a capital letter, so imgConnection should really be ImgConnection.
In your sample code, I don't see imgConnection being instantiated anywhere, and I don't see any call to Thread.start(), which is the way a thread i started. Without Thread.start() it is not surprising nothing is happening - the thread is never starting.

issue with lwuit right-to-left label ticker

I was trying to set ticker on a Label with lwuit 1.5, faced this issue:
if I set label.setRTL(true) and then call
label.startTicker(UIManager.getInstance().getLookAndFeel().getTickerSpeed(), true);
ticker just shows first 21 characters of the label's text and ignores the rest.
I've tried:
label.setRTL(false);
label.startTicker(UIManager.getInstance().getLookAndFeel().getTickerSpeed(), true);
it shows up OK, the text goes from left to right, but when I set this in a FocusListener (cause ticker should start when the label receive focus and stop after it loosed focus) it just change direction (goes from right to left).
here's what i do:
Label test = new Label();
Container c1 = new Container(new FlowLayout());
test.setText("1234567890ABCDEFGHIJ1234567890");
test.setFocusable(true);
test.setRTL(false);
test.addFocusListener(new FocusListener (){
public void focusGained(Component cmpnt) {
((Label)cmpnt).setRTL(false);
((Label)cmpnt).startTicker(UIManager.getInstance().getLookAndFeel().getTickerSpeed(), false);
}
public void focusLost(Component cmpnt) {
((Label)cmpnt).stopTicker();
}
});
c1.addComponent(test);
Look at setLabelFor, it will ticker the label for test when test gains focus. You should probably set RTL globally in the look and feel class.
I found the problem. wrong direction happens because I've implemented focusListener before adding the label to container (c1). so I just did this:
c1.addComponent(test);
test.addFocusListener(new FocusListener (){
public void focusGained(Component cmpnt) {
((Label)cmpnt).setRTL(false);
((Label)cmpnt).startTicker(UIManager.getInstance().getLookAndFeel().getTickerSpeed(), false);
}
public void focusLost(Component cmpnt) {
((Label)cmpnt).stopTicker();
}
});
and it simply worked.
in fact I got the idea from Label class source code (lines 149 ~ 153):
// solves the case of a user starting a ticker before adding the component
// into the container
if(isTickerEnabled() && isTickerRunning() && !isCellRenderer()) {
getComponentForm().registerAnimatedInternal(this);
}
this part does not work, but I don't know why. just hope someone fix this bug.

J2ME keyRepeated is not working

class ClassCanvas extends Canvas{
private int keyboard_key = 0;
protected void paint(Graphics g){
//Never mind the drawing, essence is that keyRepeated isn't working!
g.drawString(""+keyboard_key,0,0,Graphics.TOP|Graphics.LEFT);
}
protected void keyRepeated(int keyCode) {
keyboard_key = keyCode;
}
}
I compiled that, and paint always draws 0. Like that keyRepeated isn't even executed.
I tested "hasRepeatEvents()" and it says "true" so why keyRepeated doesn't work?
I'm out of ideas what could be happening.
keyPressed and keyReleased work, but keyRepeated not
Additional info:
CLDC-1.1,
MIDlet-2.0
IDE: Netbeans7.0.1 (or Java(TM) ME
Platform SDK 3.0)
Phone: CamshellCldc1, DefaultCldcPhone1 (I
tested both, both didn't work)

Resources