My sprite dont show the background - java

Im having a problem where my sprite isnt showing the background image but its showing the background Color from the frame.
Here is my code:
MAIN(edited so i only show the part where i load the sprite)
private JFrame principal;
private JButton bt_inicio_iniciar;
private JButton bt_menu_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run()
{
try
{
// UIManager.setLookAndFeel(new SyntheticaBlackEyeLookAndFeel());
new Thread (new ClientMain()).start();
}
catch( Exception e )
{
e.printStackTrace();
}
}
});
}
public ClientMain() throws IOException {
img = ImageIO.read(new File("Resources\\images\\background\\background.png"));
loadGUI();
}
private void loadGUI()
{
int principal_width = 1200;
int principal_heigth = 500;
principal = new JFrame();
// principal.setBackground(new Color(0,0,0,0));
JLabel contentPane = new JLabel();
contentPane.setIcon( new ImageIcon("Resources\\images\\background\\background.png") );
contentPane.setLayout( new BorderLayout() );
principal.pack();
principal.setContentPane( contentPane );
principal.setResizable(false);
principal.setLocationRelativeTo(null);
principal.setTitle("Cliente ");
principal.setSize(principal_width, principal_heigth);
//principal.setContentPane(new JLabel(new ImageIcon("Resources\\images\\background\\background.png")));
principal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
principal.getContentPane().setLayout(null);
//inicio
bt_inicio_iniciar = new JButton();
bt_inicio_iniciar.setBounds(500,200,200,50);
bt_inicio_iniciar.setText("Iniciar");
bt_inicio_iniciar.setEnabled(false);
tx_inicio_estado = new JLabel();
tx_inicio_estado.setText("Esperando al servidor");
tx_inicio_estado.setForeground(Color.WHITE);
tx_inicio_estado.setSize(200,20);
tx_inicio_estado.setLocation(500,175);
//menu
bt_menu_1 = new JButton();
bt_menu_1.setBounds(10,350,150,50);
bt_menu_1.setText("Attack");
bt_menu_1.setBackground(Color.LIGHT_GRAY);
bt_menu_1.setEnabled(true);
bt_menu_2 = new JButton();
bt_menu_2.setBounds(170,350,150,50);
bt_menu_2.setText("Spells");
bt_menu_2.setBackground(Color.LIGHT_GRAY);
bt_menu_2.setEnabled(true);
bt_menu_3 = new JButton();
bt_menu_3.setBounds(10,410,150,50);
bt_menu_3.setText("Items");
bt_menu_3.setBackground(Color.LIGHT_GRAY);
bt_menu_3.setEnabled(true);
bt_menu_4 = new JButton();
bt_menu_4.setBounds(170,410,150,50);
bt_menu_4.setText("Defend");
bt_menu_4.setBackground(Color.LIGHT_GRAY);
bt_menu_4.setEnabled(true);
//battleLog
tx_log = new JLabel();
tx_log.setText("Battle Log");
tx_log.setBounds(330,350,150,15);
log = new TextArea();
log.setBounds(330,370,400,89);
log.setBackground(Color.lightGray);
log.setForeground(Color.white);
//Hp
tx_hp_player1 = new JLabel();
tx_hp_player1.setBounds(740,350,150,15);
tx_hp_player1.setText("Player1");
pb_hp_player1 = new JProgressBar();
pb_hp_player1.setBounds(740,365,445,15);
pb_hp_player1.setMaximum(100);
pb_hp_player1.setMinimum(0);
pb_hp_player1.setValue(100);
pb_hp_player1.setIndeterminate(false);
pb_hp_player1.setStringPainted(true);
pb_hp_player1.setForeground(Color.red);
pb_hp_player1.setString(pb_hp_player1.getValue()+"/"+pb_hp_player1.getMaximum());
tx_hp_player2 = new JLabel();
tx_hp_player2.setBounds(740,385,150,15);
tx_hp_player2.setText("Player2");
pb_hp_player2 = new JProgressBar();
pb_hp_player2.setBounds(740,400,445,15);
pb_hp_player2.setMaximum(100);
pb_hp_player2.setMinimum(0);
pb_hp_player2.setValue(100);
pb_hp_player2.setIndeterminate(false);
pb_hp_player2.setStringPainted(true);
pb_hp_player2.setForeground(Color.red);
pb_hp_player2.setString(pb_hp_player2.getValue()+"/"+pb_hp_player2.getMaximum());
tx_hp_boss = new JLabel();
tx_hp_boss.setBounds(740,420,150,15);
tx_hp_boss.setText("Boss");
pb_hp_boss = new JProgressBar();
pb_hp_boss.setBounds(740,435,445,15);
pb_hp_boss.setMaximum(200);
pb_hp_boss.setMinimum(0);
pb_hp_boss.setValue(200);
pb_hp_boss.setIndeterminate(false);
pb_hp_boss.setStringPainted(true);
pb_hp_boss.setForeground(Color.red);
pb_hp_boss.setString(pb_hp_boss.getValue()+"/"+pb_hp_boss.getMaximum());
p = new Player();
//p.setBounds(100,100,30,35);
//p.setOpaque(true);
principal.add(bt_inicio_iniciar);
principal.add(bt_menu_1);
principal.add(bt_menu_2);
principal.add(bt_menu_3);
principal.add(bt_menu_4);
principal.add(tx_log);
principal.add(log);
principal.add(tx_hp_player1);
principal.add(pb_hp_player1);
principal.add(tx_hp_player2);
principal.add(pb_hp_player2);
principal.add(tx_hp_boss);
principal.add(pb_hp_boss);
principal.add(tx_inicio_estado);
principal.add(p);
principal.setVisible(true);
}
}
Player
public class Player extends JPanel {
// Screen Dimensions
int
GWIDTH = 30,
GHEIGHT = 30;
Dimension screenSize = new Dimension(GWIDTH, GHEIGHT);
// Double Buffer Varabiles
Image dbImage;
Graphics dbg;
// buffered spritesheet
Image firstBall;
SpriteLoader ball = new SpriteLoader("Resources\\images\\sprites\\sprite1.png");
// Animator
Animation ballAnimation;
ArrayList animationArray;
public Player() {
this.setSize(screenSize);
init();
}
private void init(){
animationArray = new ArrayList<BufferedImage>();
animationArray.add(0,ball.getImage(0,64,32,32));
animationArray.add(1,ball.getImage(32,64,32,32));
animationArray.add(2,ball.getImage(64,64,32,32));
ballAnimation = new Animation(animationArray);
ballAnimation.setSpeed(100);
ballAnimation.start();
}
#Override
public void paint(Graphics g){
super.paint(g);
dbImage = createImage(getWidth(),getHeight());
dbg = dbImage.getGraphics();
draw(dbg);
g.drawImage(dbImage, 0, 0, this);
g.dispose();
}
public void draw(Graphics g){
if(ballAnimation != null){
g.drawImage(ballAnimation.sprites, 0, 0, this);
ballAnimation.update(System.currentTimeMillis());
repaint();
}
g.dispose();
}
public static void main(String[] args) {
Player m = new Player();
}
}
Animation
public class Animation {
// initalize values
private ArrayList<BufferedImage> frames;
public BufferedImage sprites;
// Animation Varabales
private volatile boolean running = false;
private long previousTime, speed;
private int frameAtPause, currentFrame;
public Animation(ArrayList<BufferedImage> frames){
this.frames = frames;
}
public void setSpeed(long speed){
this.speed = speed;
}
public void update(long time){
if(running){
if(time - previousTime >= speed){
//Update the animation
currentFrame++;
try{
sprites = frames.get(currentFrame);
} catch(IndexOutOfBoundsException e){
currentFrame = 0;
sprites = frames.get(currentFrame);
}
previousTime = time;
}
}
}// end update
public void start (){
running = true;
previousTime = 0;
frameAtPause = 0;
currentFrame = 0;
}
public void stop (){
running = false;
running = true;
previousTime = 0;
frameAtPause = 0;
currentFrame = 0;
}
public void pause (){
frameAtPause = currentFrame;
running = false;
}
public void restart (){
currentFrame = frameAtPause;
running = true;
}
}
SpriteLoader
public class SpriteLoader {
//Initialize values
private BufferedImage bImage = null,bImage2 = null;
public SpriteLoader(String location){
try{
bImage = ImageIO.read(new File(location));
}catch(IOException e){
}
}
public BufferedImage getImage (int x, int y, int w, int h){
bImage2 = bImage.getSubimage(x, y , w, h);
return bImage2;
}
}
Here is the sprite I'm using
And the background
till now i tried to do everything that i could find on stackoverflow but i couldn't find anything that helped to solve the problem :S
EDIT1: Edited the main class to have only the GUI part but i don't know if i could clean the other classes since i dont knwo where the bug can be :S
EDIT2: Cleared unused methods

Related

How to input values or phrases on a window?

I'm trying to write a program that solves an equation for a school project, but I can't figure out how to create a space for writing in the screen instead of eclipse's console. Like, creating a space in the bottom of the window so the user can input the requested values and the program can read that and make the equation, finally showing the user the final result.
public class Main extends Canvas implements Runnable{
public static JFrame frame;
private Thread thread;
private boolean isRunning = true;
private final int WIDTH = 160;
private final int HEIGHT = 120;
private final int SCALE = 4;
private BufferedImage image;
public Main() {
setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
initFrame();
image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
}
public void initFrame() {
frame = new JFrame("Tempo de Queda (FĂ­sica)");
frame.add(this);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public synchronized void start() {
thread = new Thread(this);
isRunning = true;
thread.start();
}
public synchronized void stop() {
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Main main = new Main();
main.start();}
public void tick() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs==null) {
createBufferStrategy(3);
return;
}
Graphics g = image.getGraphics();
//Back Ground---------------------------------------
g.setColor(new Color(19,19,19));
g.fillRect(0,0,WIDTH,HEIGHT);
g = bs.getDrawGraphics();
g.drawImage(image,0,0,WIDTH*SCALE,HEIGHT*SCALE,null);
//Back Ground---------------------------------------
g.setFont(new Font("Arial",Font.PLAIN,20));
g.setColor(Color.green);
g.drawString("Write Here: ", 5,20);
bs.show();
}
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int frames = 0;
double timer = System.currentTimeMillis();
while(isRunning) {
long now = System.nanoTime();
delta+= (now-lastTime) / ns;
lastTime = now;
if(delta >= 1) {
tick();
render();
frames++;
delta--;
}
if(System.currentTimeMillis() - timer >= 1000) {
System.out.println("FPS: "+frames);
frames = 0;
timer+=1000;
}
}
}
}
So in your case, I'd make some additions to the initFrame method. Specifically, you'll want to add a JPanel to it.
JPanel panel = new JPanel();
frame.add(panel);
Then, define your JTextFields, a JButton and any JLabels to go with them. Java will want you to define any that you're messing with the text value as "final." The other components are ok to set as "final" if you don't plan on reinitializing them:
final JLabel labelX = new JLabel();
final JLabel labelY = new JLabel();
final JLabel output = new JLabel();
final JTextField inputX = new JTextField(5);
final JTextField inputY = new JTextField(5);
final JButton button = new JButton("multiply");
Setting the text of any labels is a good idea:
labelX.setText("X");
labelY.setText("Y");
output.setText("NaN");
Then add them all to the panel:
panel.add(labelX);
panel.add(inputX);
panel.add(labelY);
panel.add(inputY);
panel.add(button);
panel.add(output);
Finally, you'll need to add a listener for the button action. This is where you'll process your inputs and display the output.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
float valueX = 0;
float valueY = 0;
boolean validInputs = true;
try {
valueX = Float.parseFloat(inputX.getText());
valueY = Float.parseFloat(inputY.getText());
} catch (NumberFormatException ex) {
output.setText("Invalid input value(s)");
validInputs = false;
}
if (validInputs) {
//multiply
float result = valueX * valueY;
output.setText(Float.toString(result));
}
}
});
Running that should give you something like this:
Link to Github: FloatMathGUI

Try Again Button When Pressed Resets Everything But Everything Becomes Quicker

So, I had a problem concerning a Try Again button that would show on Game Over screen and when clicked on reset everything to initial value. Now that problem is partially solved but every time I click on it everything becomes crazy fast and with each click faster and faster.
Here is my code from class which does initialization:
public class game extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private Menu menu;
private GameOver gameover;
//variables
public static int cyclesToWait = 50;
public static int enemiesKilled = 0;
public static int life = 3;
int roundCount = 0;
Timer gamelooptimer;
//objects
Player p;
ControllerEnemy c;
ControllerRocket r;
ControllerExplosion e;
//is it new round or not --> for enemy control
public static enum ROUND{
INPROGRESS,
NEW
}
public static enum STATE{
MENU,
GAME,
OVER
};
public static STATE State = STATE.MENU;
public static ROUND Round = ROUND.INPROGRESS;
public game(){
setFocusable(true);
initGame();
}
public void resetGame(){
initGame();
}
private void initGame(){
enemiesKilled = 0;
life = 3;
roundCount = 0;
gamelooptimer = new Timer(10, this);
gamelooptimer.start();
p = new Player(MainClass.width / 2 - 60, 400);
c = new ControllerEnemy();
r = new ControllerRocket();
e = new ControllerExplosion();
menu = new Menu();
gameover = new GameOver();
addKeyListener(new KeyInput(p));
addMouseListener(new MouseInput());
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(getBackgroundImage(), 0, 0, null);
Font fnt = new Font("arial", Font.BOLD, 22);
g.setFont(fnt);
if(State == STATE.GAME){
p.draw(g2d);
c.draw(g2d);
r.draw(g2d);
e.draw(g2d);
g.drawString("Round: " + roundCount, MainClass.width - 125, 22);
g.drawString("Enemies Killed: " + enemiesKilled, MainClass.width/2 - 95, 22);
if(cyclesToWait < 50)
cyclesToWait++;
}
else if (State == STATE.OVER)
gameover.render(g);
else
menu.render(g);
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
if(State == STATE.GAME){
p.update();
c.update();
r.update();
}
if(Round == ROUND.NEW)
roundCount += 1;
}
private Image getBackgroundImage(){
ImageIcon i = new ImageIcon(getClass().getResource("/images/Background.png"));
return i.getImage();
}
resetGame() is called from another class.

how to separate the logic from the form in java swing?

I have difficulties in separating the logic of the game from the view. The view should be dumb and simply render the current state of the model. But I can not figure out how to do that. Could you please help me in making the code simpler and separating the logic from the form? Because I want to extend the game and add new things but I can not because of the confusing form of the code. I am new in java.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.*;
public class ProjectileShooterTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 600);
final ProjectileShooter projectileShooter = new ProjectileShooter();
ProjectileShooterPanel projectileShooterPanel = new ProjectileShooterPanel(
projectileShooter);
projectileShooter.setPaintingComponent(projectileShooterPanel);
JPanel controlPanel = new JPanel(new GridLayout(1, 0));
controlPanel.add(new JLabel("Angle"));
final JSlider angleSlider = new JSlider(0, 90, 45);
controlPanel.add(angleSlider);
controlPanel.add(new JLabel("Power"));
final JSlider powerSlider = new JSlider(0, 100, 50);
controlPanel.add(powerSlider);
JButton shootButton = new JButton("Shoot");
shootButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int angleDeg = angleSlider.getValue();
int power = powerSlider.getValue();
projectileShooter.setAngle(Math.toRadians(angleDeg));
projectileShooter.setPower(power);
projectileShooter.shoot();
}
});
controlPanel.add(shootButton);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(controlPanel, BorderLayout.NORTH);
f.getContentPane().add(projectileShooterPanel, BorderLayout.CENTER);
f.setVisible(true);
}
}
class ProjectileShooter {
private double angleRad = Math.toRadians(45);
private double power = 50;
private Projectile projectile;
private JComponent paintingComponent;
void setPaintingComponent(JComponent paintingComponent) {
this.paintingComponent = paintingComponent;
}
void setAngle(double angleRad) {
this.angleRad = angleRad;
}
void setPower(double power) {
this.power = power;
}
void shoot() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
executeShot();
}
});
t.setDaemon(true);
t.start();
}
private void executeShot() {
if (projectile != null) {
return;
}
projectile = new Projectile();
Point2D velocity = AffineTransform.getRotateInstance(angleRad).transform(
new Point2D.Double(1, 0), null);
velocity.setLocation(velocity.getX() * power * 0.5, velocity.getY() * power * 0.5);
projectile.setVelocity(velocity);
long prevTime = System.nanoTime();
while (projectile.getPosition().getY() >= 0) {
long currentTime = System.nanoTime();
double dt = 3 * (currentTime - prevTime) / 1e8;
projectile.performTimeStep(dt);
prevTime = currentTime;
paintingComponent.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
projectile = null;
paintingComponent.repaint();
}
Projectile getProjectile() {
return projectile;
}
}
class Projectile {
private final Point2D ACCELERATION = new Point2D.Double(0, -9.81 * 0.1);
private final Point2D position = new Point2D.Double();
private final Point2D velocity = new Point2D.Double();
public Point2D getPosition() {
return new Point2D.Double(position.getX(), position.getY());
}
public void setPosition(Point2D point) {
position.setLocation(point);
}
public void setVelocity(Point2D point) {
velocity.setLocation(point);
}
void performTimeStep(double dt) {
scaleAddAssign(velocity, dt, ACCELERATION);
scaleAddAssign(position, dt, velocity);
}
private static void scaleAddAssign(Point2D result, double factor, Point2D addend) {
double x = result.getX() + factor * addend.getX();
double y = result.getY() + factor * addend.getY();
result.setLocation(x, y);
}
}
class ProjectileShooterPanel extends JPanel {
private final ProjectileShooter projectileShooter;
public ProjectileShooterPanel(ProjectileShooter projectileShooter) {
this.projectileShooter = projectileShooter;
}
#Override
protected void paintComponent(Graphics gr) {
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr;
Projectile projectile = projectileShooter.getProjectile();
if (projectile != null) {
g.setColor(Color.RED);
Point2D position = projectile.getPosition();
int x = (int) position.getX();
int y = getHeight() - (int) position.getY();
Ellipse2D.Double gerd = new Ellipse2D.Double(x - 01, y - 10, 20, 20);
g.draw(gerd);
// g.fillOval(x-01, y-10, 20, 20);
}
Rectangle hadaf1 = new Rectangle(450, 450, 50, 50);
Rectangle hadaf2 = new Rectangle(500, 450, 50, 50);
Rectangle hadaf3 = new Rectangle(475, 400, 50, 50);
g.draw(hadaf1);
g.draw(hadaf2);
g.draw(hadaf3);
}
}
I will be so thankful.

Area generation not liking straight lines

I'm using the area generation and drawing code from Smoothing a jagged path to create collision areas for tile sprites in a JRPG game I'm making in java - Its not a major full blown game, more just a proof-of-concept for me to learn from.
The area generation works fine except for straight lines:
http://puu.sh/7wJA2.png
http://puu.sh/7wJGF.png
These images are of the collision outline opened in photoshop (in the background) vs the area that the java code is generating based on the red color (in the foreground). As can be seen, the large red line in the first image won't be draw unless I have a red pixel under it every 2 pixels, as shown in the second image.
I have made no changes to the code (other than adding comments in an attempt to better understand it) except to remove
Graphics2D g = imageOutline.createGraphics();
//...
g.dispose();
from the areaOutline draw code, replacing it with reference to my own Graphics2D variable. I tested the code both with and without those two lines and I couldn't see any difference.
I'm a bit stuck on what could be causing the issue - its not a major game-breaking issue, as I can fix it a couple of ways, but it does mean I have to explain this issue to anyone when showing them how to use it with their own sprite textures.
I've created a SSCCE of the issue - This shows the areas generated have vertical lines generated fine, but that horizontal ones are not. It takes two images - both a square 30x30 pixels, but one has internal pixels every 2 second pixel in which causes a more accurate area to be generated.
When you press a key the program will switch between the two images (and their areas), allowing for direct comparison.
The following two images must be put in the root folder of the program.
You can start the program by running the "main" method.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import java.io.*;
import javax.imageio.*;
public class AreaOutlineCanvas extends JFrame implements KeyListener
{
private ImagePanel imagePanel;
/**
* Constructor for objects of class Skeleton
*/
public AreaOutlineCanvas()
{
// initialise instance variables
addKeyListener( this );
initUI();
}
public static void main( String[] args )
{
for( String s: args )
{
System.out.println( s );
}
SwingUtilities.invokeLater( new Runnable()
{
#Override
public void run()
{
AreaOutlineCanvas aOC = new AreaOutlineCanvas();
aOC.pack();
aOC.setVisible( true );
aOC.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} );
}
private void initUI()
{
imagePanel = new ImagePanel();
setPreferredSize( new Dimension( 100, 100 ) );
setLocationRelativeTo( null );
add( imagePanel );
imagePanel.setDoubleBuffered( true );
pack();
}
#Override
public void keyTyped( KeyEvent e )
{
}
#Override
public void keyPressed( KeyEvent e )
{
//#TODO: switch statment checking the menu Skeleton is in (currentMenu)
if( imagePanel != null )
{
imagePanel.bDrawingFirstArea = !imagePanel.bDrawingFirstArea;
imagePanel.repaint();
}
}
#Override
public void keyReleased(KeyEvent e)
{
//System.out.println( "Key released: " + e.getKeyChar() + " (" + e.getKeyCode() + ")" );
}
public class ImagePanel extends JPanel
{
/** Path for the location of this charactors sprite sheet */
private String firstPath = "square1.png";
private String secondPath = "square2.png";
private BufferedImage firstImage;
private BufferedImage secondImage;
private Area firstImageArea;
private Area secondImageArea;
public boolean bDrawingFirstArea = true;
/**
* Constructor for objects of class Character
*/
public ImagePanel()
{
loadImages();
generateAreas();
}
private void loadImages()
{
try
{
firstImage = ImageIO.read( new File( firstPath ) );
secondImage = ImageIO.read( new File( secondPath ) );
}
catch( IOException e )
{
e.printStackTrace();
}
}
private void generateAreas()
{
Color c = new Color( 255, 0, 0 );
firstImageArea = getOutline( c, firstImage );
secondImageArea = getOutline( c, secondImage );
}
public Area getOutline(Color target, BufferedImage bi) {
// construct the GeneralPath
GeneralPath gp = new GeneralPath();
boolean cont = false;
int targetRGB = target.getRGB();
for (int xx=0; xx<bi.getWidth(); xx++) {
for (int yy=0; yy<bi.getHeight(); yy++) {
if (bi.getRGB(xx,yy)==targetRGB) {
if (cont) {
gp.lineTo(xx,yy);
gp.lineTo(xx,yy+1);
gp.lineTo(xx+1,yy+1);
gp.lineTo(xx+1,yy);
gp.lineTo(xx,yy);
} else {
gp.moveTo(xx,yy);
}
cont = true;
} else {
cont = false;
}
}
cont = false;
}
gp.closePath();
// construct the Area from the GP & return it
return new Area(gp);
}
#Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
drawImages(g);
}
private void drawImages( Graphics g )
{
Graphics2D g2d = (Graphics2D) g;
if( bDrawingFirstArea )
{
g2d.drawImage( firstImage, 50, 0, this );
g2d.draw( firstImageArea );
}
else
{
g2d.drawImage( secondImage, 50, 0, this );
g2d.draw( secondImageArea );
}
Toolkit.getDefaultToolkit().sync();
}
}
}
For convenience I've posted the code from Smoothing a jagged path question here
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
/* Gain the outline of an image for further processing. */
class ImageOutline {
private BufferedImage image;
private TwoToneImageFilter twoToneFilter;
private BufferedImage imageTwoTone;
private JLabel labelTwoTone;
private BufferedImage imageOutline;
private Area areaOutline = null;
private JLabel labelOutline;
private JLabel targetColor;
private JSlider tolerance;
private JProgressBar progress;
private SwingWorker sw;
public ImageOutline(BufferedImage image) {
this.image = image;
imageTwoTone = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_RGB);
}
public void drawOutline() {
if (areaOutline!=null) {
Graphics2D g = imageOutline.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,imageOutline.getWidth(),imageOutline.getHeight());
g.setColor(Color.RED);
g.setClip(areaOutline);
g.fillRect(0,0,imageOutline.getWidth(),imageOutline.getHeight());
g.setColor(Color.BLACK);
g.setClip(null);
g.draw(areaOutline);
g.dispose();
}
}
public Area getOutline(Color target, BufferedImage bi) {
// construct the GeneralPath
GeneralPath gp = new GeneralPath();
boolean cont = false;
int targetRGB = target.getRGB();
for (int xx=0; xx<bi.getWidth(); xx++) {
for (int yy=0; yy<bi.getHeight(); yy++) {
if (bi.getRGB(xx,yy)==targetRGB) {
if (cont) {
gp.lineTo(xx,yy);
gp.lineTo(xx,yy+1);
gp.lineTo(xx+1,yy+1);
gp.lineTo(xx+1,yy);
gp.lineTo(xx,yy);
} else {
gp.moveTo(xx,yy);
}
cont = true;
} else {
cont = false;
}
}
cont = false;
}
gp.closePath();
// construct the Area from the GP & return it
return new Area(gp);
}
public JPanel getGui() {
JPanel images = new JPanel(new GridLayout(2,2,2,2));
JPanel gui = new JPanel(new BorderLayout(3,3));
JPanel originalImage = new JPanel(new BorderLayout(2,2));
final JLabel originalLabel = new JLabel(new ImageIcon(image));
targetColor = new JLabel("Target Color");
targetColor.setForeground(Color.RED);
targetColor.setBackground(Color.WHITE);
targetColor.setBorder(new LineBorder(Color.BLACK));
targetColor.setOpaque(true);
JPanel controls = new JPanel(new BorderLayout());
controls.add(targetColor, BorderLayout.WEST);
originalLabel.addMouseListener( new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent me) {
originalLabel.setCursor(
Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
#Override
public void mouseExited(MouseEvent me) {
originalLabel.setCursor(Cursor.getDefaultCursor());
}
#Override
public void mouseClicked(MouseEvent me) {
int x = me.getX();
int y = me.getY();
Color c = new Color( image.getRGB(x,y) );
targetColor.setBackground( c );
updateImages();
}
});
originalImage.add(originalLabel);
tolerance = new JSlider(
JSlider.HORIZONTAL,
0,
255,
104
);
tolerance.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
updateImages();
}
});
controls.add(tolerance, BorderLayout.CENTER);
gui.add(controls,BorderLayout.NORTH);
images.add(originalImage);
labelTwoTone = new JLabel(new ImageIcon(imageTwoTone));
images.add(labelTwoTone);
images.add(new JLabel("Smoothed Outline"));
imageOutline = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_RGB
);
labelOutline = new JLabel(new ImageIcon(imageOutline));
images.add(labelOutline);
updateImages();
progress = new JProgressBar();
gui.add(images, BorderLayout.CENTER);
gui.add(progress, BorderLayout.SOUTH);
return gui;
}
private void updateImages() {
if (sw!=null) {
sw.cancel(true);
}
sw = new SwingWorker() {
#Override
public String doInBackground() {
progress.setIndeterminate(true);
adjustTwoToneImage();
labelTwoTone.repaint();
areaOutline = getOutline(Color.BLACK, imageTwoTone);
drawOutline();
return "";
}
#Override
protected void done() {
labelOutline.repaint();
progress.setIndeterminate(false);
}
};
sw.execute();
}
public void adjustTwoToneImage() {
twoToneFilter = new TwoToneImageFilter(
targetColor.getBackground(),
tolerance.getValue());
Graphics2D g = imageTwoTone.createGraphics();
g.drawImage(image, twoToneFilter, 0, 0);
g.dispose();
}
public static void main(String[] args) throws Exception {
int size = 150;
final BufferedImage outline =
new BufferedImage(size,size,BufferedImage.TYPE_INT_RGB);
Graphics2D g = outline.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,size,size);
g.setRenderingHint(
RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Polygon p = new Polygon();
p.addPoint(size/2, size/10);
p.addPoint(size-10, size-10);
p.addPoint(10, size-10);
Area a = new Area(p);
Rectangle r = new Rectangle(size/4, 8*size/10, size/2, 2*size/10);
a.subtract(new Area(r));
int radius = size/10;
Ellipse2D.Double c = new Ellipse2D.Double(
(size/2)-radius,
(size/2)-radius,
2*radius,
2*radius
);
a.subtract(new Area(c));
g.setColor(Color.BLACK);
g.fill(a);
ImageOutline io = new ImageOutline(outline);
JFrame f = new JFrame("Image Outline");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(io.getGui());
f.pack();
f.setResizable(false);
f.setLocationByPlatform(true);
f.setVisible(true);
}
}
class TwoToneImageFilter implements BufferedImageOp {
Color target;
int tolerance;
TwoToneImageFilter(Color target, int tolerance) {
this.target = target;
this.tolerance = tolerance;
}
private boolean isIncluded(Color pixel) {
int rT = target.getRed();
int gT = target.getGreen();
int bT = target.getBlue();
int rP = pixel.getRed();
int gP = pixel.getGreen();
int bP = pixel.getBlue();
return(
(rP-tolerance<=rT) && (rT<=rP+tolerance) &&
(gP-tolerance<=gT) && (gT<=gP+tolerance) &&
(bP-tolerance<=bT) && (bT<=bP+tolerance) );
}
public BufferedImage createCompatibleDestImage(
BufferedImage src,
ColorModel destCM) {
BufferedImage bi = new BufferedImage(
src.getWidth(),
src.getHeight(),
BufferedImage.TYPE_INT_RGB);
return bi;
}
public BufferedImage filter(
BufferedImage src,
BufferedImage dest) {
if (dest==null) {
dest = createCompatibleDestImage(src, null);
}
for (int x=0; x<src.getWidth(); x++) {
for (int y=0; y<src.getHeight(); y++) {
Color pixel = new Color(src.getRGB(x,y));
Color write = Color.BLACK;
if (isIncluded(pixel)) {
write = Color.WHITE;
}
dest.setRGB(x,y,write.getRGB());
}
}
return dest;
}
public Rectangle2D getBounds2D(BufferedImage src) {
return new Rectangle2D.Double(0, 0, src.getWidth(), src.getHeight());
}
public Point2D getPoint2D(
Point2D srcPt,
Point2D dstPt) {
// no co-ord translation
return srcPt;
}
public RenderingHints getRenderingHints() {
return null;
}
}

java Gap between jframe and ImagePanel

I have a JLayeredPane that adds three objects, the problem is the backgroundImage when the app runs there is a gap between the jframe and the background image from the top which i set to (0,0) no matter what i change the gap is still there (I want to rid of the gap). If i copy the backgroundImage class and put it in another file/class the gap is not there. can anyone help?
public class NavigationMenu extends JPanel {
private ArrayList<String> Menu = new ArrayList();
private int MenuSize;
private int MenuChannel = 0;
private Font realFont;
private static Dimension screenSize = new Dimension(new ScreenDimensions().getScreenWidth(), new ScreenDimensions().getScreenHeight());
private static final int MENU_HEIGHT = (int)(new ScreenDimensions().getScreenHeight()*0.1);
private static final int MENU_WIDTH = new ScreenDimensions().getScreenWidth();
private static final int MENU_CENTER = (new ScreenDimensions().getScreenHeight() / 2) - (MENU_HEIGHT / 2);
public NavigationMenu() {
//Add Menu Channels
setPreferredSize(screenSize);
setBounds(0,0,MENU_WIDTH,screenSize.height);
this.Menu.add("MOVIES");
this.Menu.add("MUSIC");
this.Menu.add("PICTURES");
this.Menu.add("VIDEOS");
this.Menu.add("TV SHOWS");
this.Menu.add("WEATHER");
this.Menu.add("RADIO");
this.Menu.add("SETTINGS");
this.MenuSize = Menu.size() - 1;
JLayeredPane pfinal = new JLayeredPane();
JPanel _menuText = new menuText();
JPanel _backgroundImage = new backgroundImage("Backgrounds/curtains.png");
JPanel _bar = new bar();
pfinal.setPreferredSize(screenSize);
pfinal.setBounds(0,0,MENU_WIDTH,screenSize.height);
pfinal.add(_backgroundImage, new Integer(1));
pfinal.add(_bar, new Integer(2));
pfinal.add(_menuText, new Integer(3));
add(pfinal);
}
public class bar extends JPanel {
public bar() {
setBounds(0,MENU_CENTER,MENU_WIDTH, MENU_HEIGHT);
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,screenSize.width,MENU_HEIGHT);
}
}
public class menuText extends JPanel {
public menuText() {
setBounds(0,MENU_CENTER,MENU_WIDTH,MENU_HEIGHT);
setOpaque(false);
setFocusable(true);
requestFocusInWindow();
try {
realFont = new RealFont(((int)(MENU_HEIGHT * 0.80))).getRealFont();
} catch (Exception e) {
System.out.println(e.toString());
}
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
//JOptionPane.showMessageDialog(null, "OK");
int keyCode = e.getKeyCode();
switch (KeyEvent.getKeyText(keyCode)) {
case "Up":
//JOptionPane.showMessageDialog(null, "Up");
if(MenuChannel < MenuSize) {
MenuChannel++;
repaint();
} else {
MenuChannel = 0; //reset
repaint();
}
break;
case "Down":
if(MenuChannel == 0) {
MenuChannel = MenuSize + 1;
MenuChannel--;
repaint();
} else {
MenuChannel--;
repaint();
}
break;
}
}
});
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
String MenuString = Menu.get(MenuChannel);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//g2d.setBackground(Color.PINK);
//g2d.fillRect(0,0,getWidth(),getHeight());
g2d.setColor(Color.WHITE);
g2d.setFont(realFont);
FontRenderContext context = g2d.getFontRenderContext();
java.awt.geom.Rectangle2D rect = realFont.getStringBounds(MenuString, context);
int textHeight = (int)rect.getHeight();
int textWidth = (int)rect.getWidth();
int panelHeight = getHeight();
int panelWidth = getWidth();
int x = (panelWidth - textWidth) / 2;
int y = (panelHeight - textHeight) / 2;
//System.out.println("f:"+ fontMetrics.gettH:" + textHeight + "\ntW:" + textWidth + "\npH:" + panelHeight + "\npW:" + panelWidth);
g2d.drawString(MenuString,x,(float)-rect.getY()+2);
}
}
public class backgroundImage extends JPanel {
private Image icon;
private int screenWidth = new ScreenDimensions().getScreenWidth();
private int screenHeight = new ScreenDimensions().getScreenHeight();
public backgroundImage(String background) {
icon = new ImageIcon(background).getImage();
Dimension size = new Dimension(screenWidth,screenHeight);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(icon,0,0,screenSize.width,screenSize.height,null);
}
}
}
Change the NavigationMenu's layout to a BorderLayout

Categories

Resources