Java SWT GC not drawing text on Canvas - java

I have the following code:
final Canvas canvas = new Canvas(mainshell, SWT.NO_REDRAW_RESIZE);
canvas.setBounds(0, 0, mainshell.getSize().x, mainshell.getSize().y);
canvas.setBackgroundImage( new Image(display, "BlueBack.jpg" ));
canvas.setFont(font);
GC gc = new GC(canvas);
gc.drawText("Test", 0, 0, true);
gc.dispose();
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
e.gc.drawText("String", 170, 30, true);
e.gc.drawText("Another Unimportant String", 80, 90, true);
int I = 140;
int i = 1;
String[] strings = Stuff.getUnimportantStringArray();
if(strings != null)
for(String string : strings){
e.gc.drawText( i + " " + string , 120, I, true);
I += 50;
i++;
}
}
});
The code that I am having the problem with is this:
GC gc = new GC(canvas);
gc.drawText("Test", 0, 0, true);
gc.dispose();
The gc.drawText(); is not drawing the String "Test" on the canvas as I expected it would.
Here is my Question:
Why is the gc.drawText("Test", 0, 0, true"); not working, but the e.gc.drawText("String", 170, 30, true); inside the PaintListeneris working ?

The paintControl() method is called whenever the canvas needs to be redrawn which could happen any number of times. For example, the PaintListener is used when the canvas is resized (try putting a breakpoint on paintControl(), resize the window, and see for yourself). All drawing you need to do should be in the PaintListener.
Also, you shouldn't use setBounds() here. Use a layout instead:
mainShell.setLayout(new FillLayout());

Related

how do I detect key presses with just one method in java?

I'm trying to paint 6 colors, 10 shapes, a jpeg image, and 3 things that change when a key is pressed in java.
However I'm trying to program all of this in one method. I've done everything else except detecting a key press. I've looked at a lot of examples, but all of them use different methods or classes that work together to detect a key press. But how to do I detect key presses and at the same time change pictures/images in JPanel all in just one method.
I tried to write some code but it doesn't work (nothing shows up on the JPanel/screen) Here's my code so far:
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, 1000, 1000);
BufferedImage photo = null;
try
{
File file = new File("holiday.jfif");
photo = ImageIO.read(file);
}
catch (IOException e)
{
g.drawString("Problem reading the file", 100, 100);
}
g.drawImage(photo,0,0,800,800,null);
g.setColor(Color.BLACK);
g.fillRect(120,300,100,100 );
g.setColor(Color.GREEN);
g.fillOval(270,130,50,100 );
g.setColor(Color.BLUE );
g.fillRect(350,200,100,150 );
g.setColor(Color.PINK);
g.fillOval(460, 270, 50, 50);
g.setColor(Color.GRAY);
g.fillArc(500, 300, 110, 100, 5, 150);
g.setColor(Color.YELLOW);
g.fillRect(500,450,100,100);
g.setColor(Color.YELLOW);
g.fillOval(550,500,100,100);
int[] xpoints = {50,150,20,180};
int[] ypoints = {500,500,550,550};
g.setColor(Color.BLACK);
g.drawPolygon(xpoints,ypoints,4);
int[] xpoint = {250,220,380,350};
int[] ypoint = {500,550,550,500};
g.drawPolygon(xpoint,ypoint,4);
int[] x = {600,500,700};
int[] y = {20,100,100};
g.drawPolygon(x,y,3);
g.setColor(Color.ORANGE);
g.fillRect(10,50,220,30);
g.fillRect(115,80,20,100);
Scanner input = new Scanner(System.in);
String press;
boolean stop = false;
while(!stop)
{
//Scanner input = new Scanner(System.in);
press = input.next();
if (press != null)
{
g.clearRect(115,80,20,100);
g.clearRect(500,450,100,100);
stop = true;
}
}
}

Entity not spawning after being summoned Java

So I am trying to call an entity called Mothership with a texture. What should be happening is that the image appears where the player is (temporary place till it appears). Instead, no matter where I move it, it does not appear.
This dropbox link is to the whole game because it all links together.
https://www.dropbox.com/sh/kuvoxzjf00wa8jf/AAD-MaXXcnHMn4PtW-X_vHcUa?dl=0
I thought maybe it's because of Controller.java, not initialising it but I was getting errors. In the end, I want the mothership to be stationary and appear on the side that the player spawns on. The mothership will lose health from enemy bullets which I am working on at the moment.
But here are the bits that I have been focussing my attention to:
public void render(Graphics g) {
g.drawImage(tex.nmothership, (int) x, (int) y, null);
}
^This is in Mothership.java
public void init(){
requestFocus();
BufferedImageLoader loader = new BufferedImageLoader();
try {
spriteSheet = loader.loadImage("/spriteSheet.png");
background = loader.loadImage("/background.png");
}catch(IOException e) {
e.printStackTrace();
}
tex = new Textures(this);
c = new Controller(tex, this);
p = new Player(200, 200, tex, this, c);
menu = new Menu();
mothership = new Mothership(200, 200, tex);
ea = c.getEntityA();
eb = c.getEntityB();
this.addKeyListener(new KeyInput(this));
this.addMouseListener(new MouseInput());
c.createEnemy(enemy_count);
//e = error
}
^In Game.java (the main engine of the game)
private void getTextures() {
player = ss.grabImage(1, 1, 32, 32);
missile = ss.grabImage(2, 1, 32, 32);
enemy = ss.grabImage(3, 1, 32, 32);
emissile = ss.grabImage(4, 1, 32, 32);
nmothership = ss.grabImage(1, 1, 128, 128);
^In Textures.java - the grabImage is from Spritesheet.java
After some playing around I managed to get the "mothership" to spawn however it has come at the price of commenting out the mothership's physics mechanic. I will make another post about it if I am still having trouble.

Generating a pdf using IText library in java doesnt work as expected

I have this piece of code that make me somehow a latex formula in a image and display to a pdf.The first thing is i have a error when i open the pdf file 109. and the first page with the formulas is not displayed at all.
the next ones is ok.
Any ideas? Thanks
document.open();
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
preface.add(new Paragraph("Test Generat", catFont));
addEmptyLine(preface, 1);
document.add(preface);
// Start a new page
// document.newPage();
for (int i = 0; i < intrebari.size(); i++) {
TeXFormula formula = new TeXFormula("x=\\frac{-b \\pm \\sqrt {b^2-4ac}}{2a}");
TeXIcon icon = formula
.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
// insert a border
icon.setInsets(new Insets(5, 5, 5, 5));
// now create an actual image of the rendered equation
BufferedImage image = new BufferedImage(icon.getIconWidth(),
icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.setColor(Color.white);
g2.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
JLabel jl = new JLabel();
jl.setForeground(new Color(0, 0, 0));
icon.paintIcon(jl, g2, 0, 0);
document.setPageSize(PageSize.A4);
PdfContentByte pdfCB = new PdfContentByte(writer);
try {
Image image1 = Image.getInstance(pdfCB, image, 1);
document.newPage();
Phrase p = new Phrase("quick brown fox jumps over the lazy dog.");
p.add(new Chunk(image1, 0, 0, true));
p.add(" ");
p.add(new Chunk(image1, 0, 0, true));
ColumnText ct = new ColumnText(writer.getDirectContent());
ct.setSimpleColumn(new Rectangle(20, document.getPageSize().getWidth(), 400, 800));
ct.addText(p);
ct.go();
document.newPage();
} catch (BadElementException | IOException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
}
document.newPage();
}

Refresh text in Applet

I am doing this small race between two cars, in a java applet.
Just two pictures moving at random speed. I am calculating the distance between current position and the finish line, and you are suppose to be able to see the distance in the upper corner.
The thing is I am not able to refresh the text field, instead it just applies a new layer on top of the old number so it is almost impossible to read.
Here are pictures to demonstrate my problem.
I thought I would be able to solve it by creating the blue rectangle at the start of each loop but that does not seem to solve it.
public void action(){
Random rand = new Random();
boolean race = true;
int x1 =500, y1 = 233;
int x2 = 500, y2 = 333;
int speed1 = rand.nextInt(15) + -16;
int speed2 = rand.nextInt(15) + -16;
int finishline = 30;
Text winnerBlue = new Text("Winner: BLUE",new Font("SansSerif",Font.BOLD,20), Color.blue,Color.white);
Text winnerRed = new Text("Winner: RED",new Font("SansSerif",Font.BOLD,20), Color.red,Color.white);
//background
Text text =null;
Text text2 = null;
window.fillRect(0, 0, 600, 400, Color.GREEN);
//track 1
window.fillRect(20, 330, 550, 39, Color.gray);
//track2
window.fillRect(20, 230, 550, 39, Color.gray);
//Finish line
window.fillRect(40, 210, 10, 180, Color.BLACK);
while(race){
text = new Text(Integer.toString(x1),new Font("Courier",Font.BOLD,20), Color.WHITE);
text2 = new Text(Integer.toString(x2),new Font("SansSerif",Font.BOLD,20), Color.WHITE);
window.fillRect(0, 0, 70, 50, Color.blue);
window.fillRect(70, 0, 70, 50, Color.red);
window.showImage(text, 0, 0);
window.showImage(text2, 70, 0);
window.showImage(car1.getImage(), x1, y1);
window.showImage(car2.getImage(), x2, y2);
car1.moveTo(x1 += speed1, y1);
car2.moveTo(x2 += speed2, y2);
window.pause(50);
if(x1 <= (finishline ) ){
speed1 = 0;
speed2 = 0;
window.showImage(winnerBlue, 200, 200);
race = false;
}
if(x2 <= (finishline)){
speed2 = 0;
speed1 = 0;
window.showImage(winnerRed, 200, 200);
race = false;
}
}
}
}
For the two screen shots and supplied code snippt, it's clear that you don't understand how painting works in Swing/AWT.
Do NOT ever, maintain any kind of refernce to the Graphics context out side of the paintXxx methods.
The paint methods perform a number of very important steps to prepare the Graphics context for painting
Start by taking a look through Performing Custom Painting

Removing bitmaps in android

How do you remove a Bitmap in android? I have created a bitmap that is called"sun" but as soon as I have finished a guy walking across the screen I want to add a new bit map called "moon" but it just gets created over top of the sun, how can I remove the sun bitmap? here is my code for the walking guy.
switch (counter)
{
case 0:
skyRect.set(0, 0, canvas.getWidth(), 400);
canvas.drawRect(skyRect, sky);
canvas.drawBitmap(AndroidDude, changingX, (canvas.getHeight()/2 - (AndroidDude.getHeight()/2)), null);
if (changingX < canvas.getWidth())
{
changingX += 10;
}
else
{
changingX = 0;
sunChangingX = 0;
counter++;
}
grassRect.set(0, 400, canvas.getWidth(), canvas.getHeight());
canvas.drawRect(grassRect, grass);
canvas.drawBitmap(cloud, 100, 50, null);
canvas.drawBitmap(cloud, 700, 100, null);
canvas.drawBitmap(sun, (canvas.getWidth() - sun.getWidth()), 0, null);
invalidate();
break;
case 1:
//Remove sun and clouds here?
canvas.drawBitmap(moon, (canvas.getWidth() - moon.getWidth()), 0, null);
canvas.drawBitmap(AndroidDude, changingX, (canvas.getHeight()/2 - (AndroidDude.getHeight()/2)), null);
if (changingX < canvas.getWidth())
{
changingX += 10;
}
else
{
changingX = 0;
counter++;
}
grassRect.set(0, 400, canvas.getWidth(), canvas.getHeight());
canvas.drawRect(grassRect, grass);
canvas.drawBitmap(cloud, 100, 50, null);
canvas.drawBitmap(cloud, 700, 100, null);
canvas.drawBitmap(sun, sunChangingX, 0, null);
invalidate();
break;
}
Redraw your background (sky and grass) over the bitmap you want removed. Make a refresh function.
You just draw new things over the old ones. If you need to "erase" something, you just redraw the background.
Canvas.drawColor(Color.WHITE);
or
You can have to clean canvas so
you can draw rectangle with WHITE color.
// or whatever your canvas color
It will looks like canvas is blank.
and again draw what ever you want.
your output will display on white color.

Categories

Resources