FNAKLNFDKA.java
import java.awt.*;
import javax.swing.*;
public class GraphApplet extends JApplet{
private static final long serialVersionUID = 1L;
public static Graphics p;
public void init(){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
});
}
}
FANKJ.java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
class FASKHF extends JPanel {
public static Graphics p;
private static final long serialVersionUID = 1L;
public Graph(){
this.setBackground(Color.yellow);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(560,560));
}
public static void updateGraph() {
repaint();
}
public void paint(Graphics F) {
//line co-ordinates
//the numbers represent the number of boxes on the graph
//1st line on the l/h side
int xstart1 = 2;
int ystart1 = 3;
int xfinish1 = 1;
int yfinish1 = 9;
//2nd line on the r/h side
int xstart2 = 8;
int ystart2 = 3;
int xfinish2 = 9;
int yfinish2 = 9;
//drawing upper arc
int arcX = 2;
int arcY = 1;
int imagRectWid = 6;
int imagRectHei = 4;
int startAngle = 0;
int arcAngle = 180;
//other
f = xaxis22;
g = xaxis11;
//to be assigned later.
//the values of xaxis and yaxis need to be separated
//yaxis3 = 5;
//yaxis4 = -5;
//change -ve num to +ve
int g3 = Math.abs(g);
int a1 = g3 + f;
int b1 = a1;
int d = (appletWidth / a1);
int e = (Height / b1);
/**
to determine the
ammount of pixles there
is in each box of the
graph, both y-axis and
x-axis
*/
int xbox = x1 / 10;
int ybox = y1 / 10;
//line variables
//the xstart, ystart, etc represent the number of boxes
//top point of the line on the graph
px1 = xbox * xstart1;//start x
py1 = ybox * ystart1;//start y
//lowwer point of the line on the graph
px = xbox * xfinish1;//finish x
py = ybox * yfinish1;//finish y
//other line on the right hand side
p2x = xbox * xstart2;
p2y = ybox * ystart2;
p2x2 = xbox * xfinish2;
p2y2 = ybox * yfinish2;
//drawing arc
int arcBoxX = arcX * xbox;
int arcBoxY = arcY * ybox;
int arcBoxWidth = imagRectWid * xbox;
int arcBoxHeight = imagRectHei * ybox;
//draw y-axis numbers
//(+ve)
while(f != 0){
String s = String.valueOf(f);
p.drawString(s,(x + 5),m + 13);
m = m + b;
f = f - 1;
}
//(-ve)
m2 = y;
while(f2 != g-1){
String u = String.valueOf(f2);
p.drawString(u,(x + 5),m2 - 3);
m2 = m2 + b;
f2 = f2 - 1;
}
//draw x-axis numbers.
//(-ve)
while(g != 0){
String t = String.valueOf(g);
p.drawString(t,n,y - 5);
n = n + a;
g = g + 1;
}
//(+ve)
n2 = x + a;
while(g2 != g3+1){
String vw = String.valueOf(g2);
p.drawString(vw,n2 -10,y - 5);
n2 = n2 + a;
g2 = g2 + 1;
}
BasicStroke aLine2 = new BasicStroke(1.0F,
BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
graph.setStroke(aLine2);
//notch on numbers and grid lines
//left to right, top to bottom notches
int v2 = -5;
int v5 = 0;
while(i <= a1-1){
p.drawLine(Da,0,Ea,y1);
a = a + d;
b = b + e;
i = i + 1;
}
//notches
while(i2 <= a1){
p.setColor(Color.blue);//notch color
p.drawString("x",v2+2,y+3);//xaxis
p.drawString("x",x-4,v5+4);//yaxis
v5 = v5 + e;
v2 = v2 + d;
i2 = i2 + 1;
}
}
}
}
import java.awt.*;
import javax.swing.*;
}
}
/*
* this code is to accept a user input in order for him to
* change the ranges of the xaxis and yaxis to his needs
*/
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ControlsB extends JPanel{
private static final long serialVersionUID = 1L;
public static int xaxis1,xaxis2,yaxis3,yaxis4;
//public int xaxis11,xaxis22,yaxis33,yaxis44;
//public Object ControlsB;
//private Graph graph;
//public static Graphics p;
public String s;
public ControlsB(Box box2) {
JButton btn1 = new JButton("Resize");
final Box b = Box.createHorizontalBox();
b.add(new JLabel("Please enter range: "));
Box b0 = Box.createVerticalBox();//create a vertical box to stack the controls
Box b1 = Box.createHorizontalBox(); // create a horizontal box for the x-axis
//x-axis
b1.add(new JLabel("x-axis "));
b1.add(new JLabel("from"));
final JTextField f1 = new JTextField(" 0");
f1.setMaximumSize(new Dimension(100,30));
b.add(btn1);
}
protected Object Integer(int xaxis12) {
return null;
}
}
Now the problem with this program is; in ControlsB I have a method that places the controls at the bottom side (Under the yellow box / graph), now these controls are supposed to accept the range of the graph on the x-axis line (x-axis only at the moment because the code for the y-axis is not ready yet). When the user presses the "resize" button the graph should come up with the changes.
However this is not happening and the button is being pressed for nothing... and I cannot figure out what I have wrong.
In ControlsB file I have an action listener for the btn1 that is the "resize" button and a soon as the bottom is pressed it changes the text fields inputs (f1 and f2) into integers and assigned to x-axis1,x-axis 2,etc...
Now I am making a reference from theses variables (found in the action listener method) to the class Graph.java with this line: public static int xaxis11 = ControlsB.xaxis1;
Can anyone please let me know what is the best solution for this problem I have..??..
NOTE: all these files compile. but the graph does not come up.
The way that it is currently coded, you are assigning the xaxis11, xaxis22, yaxis33, and yaxis44 only one time. The variables are not updated dynamically when they change in ControlsB. This means that you simply have to update them each time the values change. To do this, add a method to your Graph class:
public static void updateGraph() {
xaxis11 = ControlsB.xaxis1;
xaxis22 = ControlsB.xaxis2;
yaxis33 = ControlsB.yaxis3;
yaxis44 = ControlsB.yaxis4;
}
Then, when the user changes the values in ControlsB, call Graph.update(). Make sure you are also calling repaint when this happens.
Also note that making all of these things static is not your only option. You can also simply have a reference to an object as a field of another class, set it in the constructor, and call methods on it when necessary. You may run into some problems with your implementation due to this problem, as making everything static may affect your ability to call repaint() on an object, which you need to do in order to update it.
A workaround to that problem would be to add repaint() to the bottom of the updateGraph method I outlined above.
When you set the static variables in Graph, you are making a copy of the variables in ControlB, so when you are chaning them in ControlB, the changes do not reflect in Graph. Instead access the variables through ControlB (preferably via a public method in ControlB)
Update
to enable calling repaint, remove all static modifies from Graph and ControlsB; add a variable holding the graph instance to ControlsB and pass that instance to its constructor
public class ControlsB extends JPanel
{
Graph my_graph;
//...
public ControlsB(Box box2, Graph graph)
{
my_graph = graph;
// ...
}
}
then change the updateGraph() method in Graph to
public void updateGraph(int xaxis1, xaxis2, yaxis3, yaxis4)
{
xaxis11 = xaxis1;
xaxis22 = xaxis2;
yaxis33 = yaxis3;
yaxis44 = yaxis4;
repaint();
}
and call it like this in the button's actionperformed() method:
graph.updateGraph(xaxis1, xaxis2, yaxis3, yaxis4);
Note: you don't seem to be using box2 in the ControlsB constructor, so you can remove that parameter.
Related
I posted this question a bit earlier and was told to make it SSCCE so here goes (if I can make any improvements feel free to let me know):
I'm wondering why when my button "confirm" is clicked the old squares disappear and the redrawn squares do not appear on my GUI (made with swing). The Squares class draws 200 spaced out squares with an ID (0, 1, 2, or 3 as String) inside obtained from a different class (for the purpose of this question, let's assume it is always 0 and not include that class). For clarification: Squares draws everything perfectly the first time (also retrieves the correct IDs), but I want it to redraw everything once the button is clicked with new IDs.
Code for Squares:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
public class Squares extends JPanel{
private ArrayList<Rectangle> squares = new ArrayList<Rectangle>();
private String stringID = "0";
public void addSquare(int x, int y, int width, int height, int ID) {
Rectangle rect = new Rectangle(x, y, width, height);
squares.add(rect);
stringID = Integer.toString(ID);
if(ID == 0){
stringID = "";
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
FontMetrics fm = g2.getFontMetrics();
int fontAscent = fm.getAscent();
g2.setClip(new Rectangle(0,0,Integer.MAX_VALUE,Integer.MAX_VALUE));
for (Rectangle rect : squares) {
g2.drawString(stringID, rect.x + 7, rect.y + 2 + fontAscent);
g2.draw(rect);
}
}
}
Code for GUI:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIReserver extends JFrame implements Runnable{
private int myID;
private JButton confirm = new JButton("Check Availability and Confirm Reservation");
private JFrame GUI = new JFrame();
private Squares square;
public GUIReserver(int i) {
this.myID = i;
}
#Override
public void run() {
int rows = 50;
int seatsInRow = 4;
confirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
GUI.getContentPane().remove(square);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this does not show up at all (could be that it wasn't drawn, could be that it is out of view etc...)
GUI.repaint(); //the line in question
}
});
GUI.setLayout(new FlowLayout());
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setLocation(0,0);
GUI.setExtendedState(JFrame.MAXIMIZED_BOTH);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this shows up the way I wish
GUI.add(confirm);
GUI.pack();
GUI.setVisible(true);
}
}
Code for main:
public class AircraftSeatReservation {
static AircraftSeatReservation me = new AircraftSeatReservation();
private final int rows = 50;
private final int seatsInRow = 4;
private int seatsAvailable = rows * seatsInRow;
private Thread t3;
public static void main(String[] args) {
GUIReserver GR1 = new GUIReserver(3);
me.t3 = new Thread(GR1);
me.t3.start();
}
}
One major problem: Your Squares JPanels preferred size is only 20 by 20, and will likely actually be that size since it seems to be added to a FlowLayout-using container. Next you seem to be drawing at locations that are well beyond the bounds of this component, and so the drawings likely will never be seen. Consider allowing your Squares objects to be larger, and make sure to only draw within the bounds of this component.
Note also there is code that doesn't make sense, including:
private int myID;
private JTextField row, column, instru draft saved // ???
package question2;ction1, instruction2, seatLabel, rowLabel; // ???
I'm guessing that it's
private int myID;
private JTextField row, column, instruction1, instruction2, seatLabel, rowLabel;
And this won't compile for us:
int rows = AircraftSeatReservation.getRows();
int seatsInRow = AircraftSeatReservation.getSeatsInRow(); // and shouldn't this take an int row parameter?
since we don't have your AircraftSeatReservation class (hopefully you don't really have static methods in that class).
And we can't compile or run your current code. We don't want to see your whole program, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem. So as Andrew Thompson recommends, for better help, please create and post your Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
I would try to OOP-ify your problem as much as possible, to allow you to divide and conquer. This could involve:
Creating a SeatClass enum, one with possibly two elements, FIRST and COACH.
Creating a non-GUI Seat class, one with several fields including possibly: int row, char seat ( such as A, B, C, D, E, F), a SeatClass field to see if it is a first class seat or coach, and a boolean reserved field that is only true if the seat is reserved.
This class would also have a getId() method that returns a String concatenation of the row number and the seat char.
Creating a non-GUI Airplane class, one that holds two arrays of Seats, one for SeatClass.FIRST or first-class seats, and one for SeatClass.COACH.
It would also have a row count field and a seat count (column count) field.
After creating all these, then work on your GUI classes.
I'd create a GUI class for Seats, perhaps GuiSeat, have it contain a Seat object, perhaps have it extend JPanel, allow it to display its own id String that it gets from its contained Seat object, have it override getBackground(...) so that it's color will depend on whether the seat is reserved or not.
etc.....
There is something in the following code that I am unable to understand. After digging through google for a while, I decided it would be better to ask someone.
I am following a game programming tutorial on youtube, and I feel I understand (to some degree) everything I have written, except for some lines which concern the rendering part of the program.
package com.thomas.game;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import com.thomas.game.graphics.Screen;
import com.thomas.game.input.Keyboard;
public class Game extends Canvas implements Runnable {
private static final int WIDTH = 300;
private static final int HEIGHT = (WIDTH / 16) * 9;
private static final int SCALE = 3;
private static final String TITLE = "Game";
private JFrame frame;
private Thread thread;
private Screen screen;
private BufferedImage image;
private Keyboard key;
private int[] pixels;
private boolean running = false;
private int x = 0, y = 0;
public Game() {
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
screen = new Screen(WIDTH, HEIGHT);
frame = new JFrame();
initializeFrame();
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
this is what I don't understand. I get the image raster, from which I get the databuffer. I typecast that databuffer into a (DatabufferInt), which allows me to retrieve an int[] through the getData() method. After this is done, pixel.length has a value of 48600, and every index contains the int value 0. Operating with this int[] makes the program render like it is supposed to. However, if I don't typecast and retrieve the int[] in the above manner, and instead say pixels = new int[48600], i end up with a black screen.
I guess what I want to know is: what is the difference between these two int[], or rather, what makes the first one work? How does it work?
key = new Keyboard();
addKeyListener(key);
setFocusable(true);
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1E9/60;
double delta = 0;
long now;
int ticks = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while(running) {
now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
while(delta >= 1) {
tick();
ticks++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer >= 1000) {
timer += 1000;
frame.setTitle(TITLE + " | ups: " + ticks + " fps: " + frames);
ticks = 0;
frames = 0;
}
}
}
private void render() {
BufferStrategy bs = getBufferStrategy(); // retrieves the bufferstrategy from the current component (the instance of Game that calls this method)
if(bs == null) {
createBufferStrategy(3);
return;
}
screen.clear();
screen.render(x, y);
getPixels();
Graphics g = bs.getDrawGraphics(); // retrieves a graphics object from the next in line buffer in the bufferstrategy, this graphics object draws to that buffer
g.drawImage(image, 0, 0, getWidth(), getHeight(), null); // draws the bufferedimage to the available buffer
g.dispose();
bs.show(); // orders the next in line buffer (which the graphics object g is tied to) to show its contents on the canvas
}
private void tick() {
key.update();
if(key.up)
y--;
if(key.down)
y++;
if(key.left)
x--;
if(key.right)
x++;
}
public void initializeFrame() {
frame.setTitle(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(this);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public synchronized void start() {
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Game game = new Game();
game.start();
}
public void getPixels() {
for(int i = 0; i < pixels.length; i++)
pixels[i] = screen.pixels[i];
}
}
It seems like the bufferedimage gets values from the pixels array. But I don't understand how these two communicate, or how they are connected. I haven't explicitly told the bufferedimage to get its pixels from the pixels array, so how does it know?
I will also attach the Screen class, which is responsible for updating the pixels array.
package com.thomas.game.graphics;
import java.util.Random;
public class Screen {
private int width, height;
public int[] pixels;
private final int MAP_SIZE = 64;
private final int MAP_SIZE_MASK = MAP_SIZE - 1;
private int[] tiles;
private int tileIndex;
private int xx, yy;
private Random r;
public Screen(int w, int h) {
width = w;
height = h;
pixels = new int[width * height];
tiles = new int[MAP_SIZE * MAP_SIZE];
r = new Random(0xffffff);
for(int i = 0; i < tiles.length; i++) {
tiles[i] = r.nextInt();
}
tiles[0] = 0;
}
public void clear() {
for(int i = 0; i < pixels.length; i++)
pixels[i] = 0;
}
public void render(int xOffset, int yOffset) {
for(int y = 0; y < height; y++) {
yy = y + yOffset;
for(int x = 0; x < width; x++) {
xx = x + xOffset;
tileIndex = (yy >> 4 & MAP_SIZE_MASK) * MAP_SIZE + (xx >> 4 & MAP_SIZE_MASK);
pixels[y * width + x] = tiles[tileIndex];
}
}
}
}
I really hope someone can explain this to me, it would be greatly appreciated. The program is working like it is supposed to, but I don't feel comfortable continuing on the tutorial until I grasp this.
Basic types like short, int, long etc are not Objects.
However, int[] is an array. Arrays are objects in java. Java manipulates objects by reference, not value.
In this line you are not creating a new object. You are storing a reference to the object int[] in your variable pixels. Anything you change in pixels, gets changed inside of the int[] object in image:
pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
I've created an example, try running this code:
public class Data {
private int[] values = {25,14};
public int[] getValues() {
return values;
}
public static void main(String[] args) {
Data d = new Data();
System.out.println(d.getValues()[0]);
int[] values = d.getValues();
values[0] = 15;
System.out.println(d.getValues()[0]);
}
}
Output:
25
15
Note that you have this code...
pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
while it should be like this...
pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
Change image to img.
Hope it works!
I have the following code which does (the first part of) what I want drawing a chessboard with some pieces on it.
Image pieceImage = getImage(currentPiece);
int pieceHeight = pieceImage.getHeight(null);
double scale = (double)side/(double)pieceHeight;
AffineTransform transform = new AffineTransform();
transform.setToTranslation(xPos, yPos);
transform.scale(scale, scale);
realGraphics.drawImage(pieceImage, transform, this);
that is, it gets a chess piece's image and the image's height, it translates the drawing of that image to the square the piece is on and scales the image to the size of the square.
Llet's say I want to rotate the black pieces 180 degrees. Somewhere I expect to have something like:
transform.rotate(Math.toRadians(180) /* ?, ? */);
But I can't figure out what to put in as X and Y. If I put nothing, the image is nicely rotated around the 0,0 point of its chessboard square, putting the piece upside down in the square to the northeast of where it is supposed to be. I've guessed at various other combinations of x,y, with no luck yet.
I am already using translation to put the piece in the right square, the rotation transform wants another x,y around which to rotate things, but I don't know how to tell the transform to rotate the piece around one x,y and write the image to a different x,y. Can someone help me with the rotation parameters, or point me to something that explains how these things work? I've found examples of things that don't explain how they work, and so far I haven't figured out how to alter them to my situation...
Major edit: addition of working code. Sorry, I don't know how to post images, please substitute your own.
When I run the following I get a 2x2 chess board with a rook at the top left and a knight at the bottom right.
If I go into SmallChessboardComponent and take the comment delims off the first rotation transform statement, I get the rook in its original place upside down and the knight does not appear. If I instead take the comment delims off the second transform statement, neither piece appears at all.
I am looking for a way to turn the pieces upside down on the square on which they would appear anyway. I want to draw each piece onto the board; I don't want code that flips the board.
main program:
package main;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import directredraw.SmallChessboardComponent;
public class SmallChessboardMain
{
private static void dbg (String message) { System.out.println(message); }
public static void main(String[] args)
{
//Create the top-level container and add contents to it.
final JFrame frame = new JFrame("Small Chessboard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the chessboard itself and set it in the component
SmallChessboard chessboard = new SmallChessboard();
// create the GUI component that will contain the chessboard
SmallChessboardComponent chessboardComponent = new SmallChessboardComponent();
chessboardComponent.setBoard (chessboard);
frame.getContentPane().add(chessboardComponent, BorderLayout.CENTER);
// pack and display all this
frame.pack();
frame.setVisible(true);
}
}
chessboard class:
package main;
public class SmallChessboard
{
Piece [][] squares = new Piece[2][2];
public SmallChessboard()
{
squares[0][0] = new Piece(Piece.WHITECOLOR, Piece.ROOK);
squares[1][1] = new Piece(Piece.WHITECOLOR, Piece.KNIGHT);
}
/**
* get the piece at the given rank and file; null if
* no piece exists there.
*/
public Piece getPiece(int rank, int file)
{
if (0 > rank || rank > 2 || 0 > file || file > 2) { return null; }
else { return squares[rank][file]; }
}
}
chessboard component class:
package directredraw;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
import main.Piece;
import main.PieceImages;
import main.SmallChessboard;
public class SmallChessboardComponent extends JPanel
{
private static final long serialVersionUID = 1L;
Color whiteSquareColor = Color.yellow;
Color blackSquareColor = Color.blue;
private static void dbg (String msg) { System.out.println(msg); }
private SmallChessboard chessboard = null;
// currently playing with rotating images; this affine transform
// should help
AffineTransform rotationTransform = null;
private final int DEFAULT_PREFERRED_SIDE = 400;
int wholeSide = DEFAULT_PREFERRED_SIDE;
int side = DEFAULT_PREFERRED_SIDE / 8;
public void setBoard (SmallChessboard givenBoard)
{ chessboard = givenBoard;
}
/**
* set either or both colors for this chessboard; if either of
* the arguments are null, they do not change the existing color
* setting.
*/
public void setColors (Color darkSquare, Color lightSquare)
{
if (darkSquare != null) { blackSquareColor = darkSquare; }
if (lightSquare != null) { whiteSquareColor = lightSquare; }
}
/**
* return the preferred size for this component.s
*/
public Dimension getPreferredSize()
{ return new Dimension(wholeSide, wholeSide);
}
/*
* return the image object for the given piece
*/
private Image getImage(Piece piece)
{ return PieceImages.getPieceImage(this, piece);
}
public void paintComponent (Graphics graphics)
{
Graphics2D realGraphics = (Graphics2D) graphics;
// the image container might have been stretched.
// calculate the largest square held by the current container,
// and then 1/2 of that size for an individual square.
int wholeWidth = this.getWidth();
int wholeHeight = this.getHeight();
wholeSide = (wholeWidth / 2) * 2;
if (wholeHeight < wholeWidth) { wholeSide = (wholeHeight / 2) * 2; }
side = wholeSide / 2;
Rectangle clip = realGraphics.getClipBounds();
boolean firstColumnWhite = false;
// for each file on the board:
// set whether top square is white
// set background color according to white/black square
//
for (int fileIndex=0; fileIndex<8; fileIndex++)
{ boolean currentColorWhite = firstColumnWhite;
firstColumnWhite = !firstColumnWhite;
// draw the board and all the pieces
int rankIndex = 2;
for (rankIndex=2; rankIndex>=0; rankIndex--)
{
currentColorWhite = !currentColorWhite;
// x and y position of the top left corner of the square we're drawing,
// and rect becomes the dimensions and position of the square itself.
int xPos = fileIndex * side;
int yPos = rankIndex * side;
Rectangle rect = new Rectangle(xPos, yPos, side, side);
// if this square intersects the clipping rectangle we're drawing,
// then we'll draw the square and the piece on the square.
if (rect.intersects(clip))
{
// this puts down the correct color of square
if (currentColorWhite) { realGraphics.setColor(whiteSquareColor); }
else { realGraphics.setColor(blackSquareColor); }
realGraphics.fillRect(xPos, yPos, side, side);
// if there is a piece on this square and it isn't selected at the
// moment, then draw it.
Piece currentPiece = chessboard.getPiece(rankIndex, fileIndex);
if (currentPiece != null)
{
Image pieceImage = getImage(currentPiece);
int pieceHeight = pieceImage.getHeight(null);
double scalePiece = (double)side/(double)pieceHeight;
AffineTransform transform = new AffineTransform();
// transform.setToRotation(Math.toRadians(180));
transform.setToRotation(Math.toRadians(180), side/2, side/2);
transform.scale(scalePiece, scalePiece);
transform.translate(xPos/scalePiece, yPos/scalePiece);
// if (currentPiece.isBlack())
// {
// transform.translate(xPos + (side+2), yPos + (side+2));
// transform.rotate(Math.toRadians(180) /*, ,*/ );
// }
// else
// {
// transform.translate(xPos, yPos);
// }
realGraphics.drawImage(pieceImage, transform, this);
}
}
}
}
}
}
Piece.java
package main;
public class Piece
{
// piece types; the sum of the piece type and the
// color gives a number unique to both type and color,
// which is used for things like image indices.
public static final int PAWN = 0;
public static final int KNIGHT = 1;
public static final int BISHOP = 2;
public static final int ROOK = 3;
public static final int QUEEN = 4;
public static final int KING = 5;
// one of these is the color of the current piece
public static final int NOCOLOR = -1;
// the sum of the piece type and the
// color gives a number unique to both type and color,
// which is used for things like image indices.
public static final int BLACKCOLOR = 0;
public static final int WHITECOLOR = 6;
int color = NOCOLOR;
int imageIndex;
public Piece(int color, int pieceType)
{
// dbg -- all pieces are white rooks for now...
this.color = color;
imageIndex = color + pieceType;
}
/**
* return the integer associated with this piece's color;
*/
int getPieceColor()
{ return color;
}
/**
* return true if the piece is black
*/
public boolean isBlack()
{
return (color == BLACKCOLOR);
}
/**
* set the color associated with this piece; constants
* found in this class.
*/
public void setPieceColor(int givenColor)
{ color = givenColor;
}
/**
* return the integer designated for the image used for this piece.
*/
int getImageIndex()
{ return imageIndex;
}
}
and PieceImages.java
package main;
import java.awt.Component;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.net.URL;
public class PieceImages
{ static Image images[] = null;
private static void dbg (String msg) { System.out.println(msg); }
public static Image getPieceImage (Component target, Piece piece)
{
if (images == null)
try
{
MediaTracker tracker = new MediaTracker(target);
images = new Image[12];
images[Piece.BLACKCOLOR + Piece.PAWN] = getImage(tracker, "bPawn.gif");
images[Piece.BLACKCOLOR + Piece.KNIGHT] = getImage(tracker, "bKnight.gif");
images[Piece.BLACKCOLOR + Piece.BISHOP] = getImage(tracker, "bBishop.gif");
images[Piece.BLACKCOLOR + Piece.ROOK] = getImage(tracker, "bRook.gif");
images[Piece.BLACKCOLOR + Piece.QUEEN] = getImage(tracker, "bQueen.gif");
images[Piece.BLACKCOLOR + Piece.KING] = getImage(tracker, "bKing.gif");
images[Piece.WHITECOLOR + Piece.PAWN] = getImage(tracker, "wPawn.gif");
images[Piece.WHITECOLOR + Piece.KNIGHT] = getImage(tracker, "wKnight.gif");
images[Piece.WHITECOLOR + Piece.BISHOP] = getImage(tracker, "wBishop.gif");
images[Piece.WHITECOLOR + Piece.ROOK] = getImage(tracker, "wRook.gif");
images[Piece.WHITECOLOR + Piece.QUEEN] = getImage(tracker, "wQueen.gif");
images[Piece.WHITECOLOR + Piece.KING] = getImage(tracker, "wKing.gif");
if (!tracker.waitForAll(10000))
{ System.out.println("ERROR: not all piece main.images loaded");
}
dbg("piece images loaded");
}
catch (Exception xcp)
{ System.out.println("Error loading images");
xcp.printStackTrace();
}
return images[piece.getImageIndex()];
}
private static Image getImage(MediaTracker tracker, String file)
{
URL url = PieceImages.class.getResource("images/" + file);
Image image = Toolkit.getDefaultToolkit().getImage(url);
tracker.addImage(image, 1);
return image;
}
}
Okay, this is a little slight of hand. The example code will only work for 90 degree increments (it was only designed this way), to do smaller increments you to use some trig to calculate the image width and height (there's a answer somewhere for that to ;))
public class ImagePane extends JPanel {
private BufferedImage masterImage;
private BufferedImage renderedImage;
public ImagePane(BufferedImage image) {
masterImage = image;
applyRotation(0);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(renderedImage.getWidth(), renderedImage.getHeight());
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
protected int getVirtualAngle(int angle) {
float fRotations = (float) angle / 360f;
int rotations = (int) (fRotations - (fRotations / 1000));
int virtual = angle - (rotations * 360);
if (virtual < 0) {
virtual = 360 + virtual;
}
return virtual;
}
public void applyRotation(int angle) {
// This will only work for angles of 90 degrees...
// Normalize the angle to make sure it's only between 0-360 degrees
int virtualAngle = getVirtualAngle(angle);
Dimension size = new Dimension(masterImage.getWidth(), masterImage.getHeight());
int masterWidth = masterImage.getWidth();
int masterHeight = masterImage.getHeight();
double x = 0; //masterWidth / 2.0;
double y = 0; //masterHeight / 2.0;
switch (virtualAngle) {
case 0:
break;
case 180:
break;
case 90:
case 270:
size = new Dimension(masterImage.getHeight(), masterImage.getWidth());
x = (masterHeight - masterWidth) / 2.0;
y = (masterWidth - masterHeight) / 2.0;
break;
}
renderedImage = new BufferedImage(size.width, size.height, masterImage.getTransparency());
Graphics2D g2d = renderedImage.createGraphics();
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.rotate(Math.toRadians(virtualAngle), masterWidth / 2.0, masterHeight / 2.0);
g2d.drawImage(masterImage, at, null);
g2d.dispose();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int width = getWidth() - 1;
int height = getHeight() - 1;
int x = (width - renderedImage.getWidth()) / 2;
int y = (height - renderedImage.getHeight()) / 2;
g2d.drawImage(renderedImage, x, y, this);
}
}
Now, you could simply "flip" the image vertically, if that works better for you
public class FlipPane extends JPanel {
private BufferedImage masterImage;
private BufferedImage renderedImage;
public FlipPane(BufferedImage image) {
masterImage = image;
flipMaster();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(renderedImage.getWidth(), renderedImage.getHeight());
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
protected void flipMaster() {
renderedImage = new BufferedImage(masterImage.getWidth(), masterImage.getHeight(), masterImage.getTransparency());
Graphics2D g2d = renderedImage.createGraphics();
g2d.setTransform(AffineTransform.getScaleInstance(1, -1));
g2d.drawImage(masterImage, 0, -masterImage.getHeight(), this);
g2d.dispose();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int width = getWidth() - 1;
int height = getHeight() - 1;
int x = (width - renderedImage.getWidth()) / 2;
int y = (height - renderedImage.getHeight()) / 2;
g2d.drawImage(renderedImage, x, y, this);
}
}
This basically results in:
Original | 180 degree rotation | Vertical inversion...
Now, if you change the flipMaster method to read:
g2d.setTransform(AffineTransform.getScaleInstance(-1, -1));
g2d.drawImage(masterImage, -masterImage.getWidth(), -masterImage.getHeight(), this);
You'll get the same effect as the 180 rotation ;)
Try performing the rotation before translating it into the correct position. Simply reorder the transformations so that first you scale, then you rotate (around the center point of the image), and then you translate:
transform.scale(scale, scale);
transform.rotate(Math.PI, pieceWidth / 2, pieceHeight /2);
transform.translation(xPos, yPos);
By the way, the black pieces on a chess board usually aren't rotated. :)
Update
In what way does it not work? The solution I provided also also differs from your code in that scaling is performed before translating. You can try the rotating, translating, and then scaling.
I strongly suggest that you modify your code so that you can perform the translation last. If you do this, everything will become a lot less complicated. Once you have done so, you only have to scale once to automatically take care of the rotation.
transform.scale(scale, scale); // or transform.scale(scale, -scale); to rotate
transform.translate(xPos, yPos);
I stumbled upon a problem which i would like to solve it using Java. User inputs Larger Rectangle dimension (i.e L_width and L_height) and smaller rectangle dimension (i.e S_width and S_height). I would like to place as many smaller rectangle inside the larger rectangle and show it graphically.
for example: When the Larger Rectangle size is 4 x 5 and smaller rectangle size is 2 x 2, then the maximum number of smaller rectangle that i would be able to place it inside the larger rectangle is 4. I would like to show them graphically.
As im new to java, i wanted to know how i can approach this problem from programmatic point of view and what concept i have to use to achieve the same.
Initial code for calculating the maximum number of rectangles. Can any1 help me to show this result graphically using java
// Code Starts
import java.awt.Graphics;
import java.util.Scanner;
import javax.swing.JComponent;
import javax.swing.JFrame;
//Class to store the output of layout
class layout{
private int Cnt_BW_CW=0; // BoardWidth and CardWidth are arranged together
private int Cnt_BW_CH=0;
private int option=0; // Option 1: width-width Option 2: width-height
public int getCnt_BW_CW (){
return Cnt_BW_CW;
}
public int getCnt_BW_CH (){
return Cnt_BW_CH;
}
public int getoption (){
return option;
}
public void setCnt_BW_CW (int newValue){
Cnt_BW_CW = newValue;
}
public void setCnt_BW_CH (int newValue){
Cnt_BW_CH = newValue;
}
public void setoption (int newValue){
option = newValue;
}
}
// Stores the Dimension
class Dimension{
private float w,h;
Scanner input = new Scanner( System.in );
public Dimension(){
System.out.print( "Enter Width: " );
w = input.nextInt();
System.out.print( "Enter Height: " );
h = input.nextInt();
}
public Dimension(float width, float height){
w = width;
h = height;
}
public float getWidth (){
return w;
}
public float getHeight (){
return h;
}
public void setWidth (float newWidth){
w = newWidth;
}
public void setHeight (float newHeight){
h = newHeight;
}
}
class MyCanvas extends JComponent {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
g.drawRect (10, 10, 200, 200);
}
}
public class boundedRect {
#SuppressWarnings("unused")
public static void main(String[] a) {
Dimension Board = new Dimension();
Dimension Card = new Dimension();
int Cnt =0;
Cnt = NumOfRect(Board, Card);
System.out.printf( "Number of Cards:%d",Cnt );
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300,300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
public static int NumOfRect(Dimension b,Dimension c){
float bw,bh,cw,ch;
int bw_cw,bh_ch,bw_ch,bh_cw;
int SameDimensionCnt,DiffDimensionCnt;
int count;
layout Result = new layout();
bw =b.getWidth(); bh = b.getHeight();
cw =c.getWidth(); ch = c.getHeight();
if (bw < cw || bh < ch){
System.out.println( "Board and Card Dimension mismatch" );
System.exit(0);
}
bw_cw = (int)Math.floor(bw/cw);
bh_ch = (int)Math.floor(bh/ch);
SameDimensionCnt = bw_cw * bh_ch;
Result.setCnt_BW_CW(SameDimensionCnt);
bw_ch = (int)Math.floor(bw/ch);
bh_cw = (int)Math.floor(bh/cw);
DiffDimensionCnt = bw_ch * bh_cw;
Result.setCnt_BW_CH(DiffDimensionCnt);
System.out.printf( "Matching BW x CW: %d\n",SameDimensionCnt );
System.out.printf( "Matching BW x CH: %d\n",DiffDimensionCnt );
if (SameDimensionCnt < DiffDimensionCnt ){
count = DiffDimensionCnt;
System.out.println( "Align Board Width and Card Height" );
Result.setoption(2);
}else {
count = SameDimensionCnt;
System.out.println( "Align Board Width and Card Width" );
Result.setoption(1);
}
return count;
}
}
So you want to tile a large rectangle with a number of smaller rectangles. First define a class to represent the small rectangles, and create a data structure (probably an ArrayList) to hold them. Use a nested for loop to walk over the area of the large rectangle in S_width/S_height steps, and create as many small rectangles as will fit. Add them to the ArrayList as they are created. Search for ArrayList on Google to find the Java docs if you need them.
Then you need to write the code to draw them on the screen. For that, look up the official Java Tutorial on Google and read the section on graphics.
Try writing the code first and if you have problems, post your code here (you can edit the question).
I have an assignment in which I have to allow a user to plot a graph using a quadratic equation.
I managed to draw the skeleton of the graph, and now I am trying to display the "control panel" for the user to input the values.
I have 4 files:
graph.java
panel.java
panelB.java
panelC.java
My problem is when I run the code it is displaying only the panel.java even in the container where it should display the other two panels.
panel.java
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.JPanel;
public class panel extends JPanel {
public panel(){
this.setBackground(Color.yellow);
}
}
Can anyone please advise what changes I should do to fix this problem?
I have done some changes to the graph.java file:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.*;
public class GraphApplet extends JApplet{
public GraphApplet(){
raph p = new Graph();//graph
p.setPreferredSize(new Dimension(760,500));
conn.add(p,BorderLayout.CENTER);
}
And now all that is being displayed is the graph.
Regarding the other code, I also made some changes to the class names:
gnjk;.java
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.JPanel;
public class Graph extends JPanel {
public Graph(){
this.setBackground(Color.yellow);
}
public void paintComponent(Graphics p) {
super.paintComponent(p);
Graphics2D graph = (Graphics2D)p;
this.setBackground(Color.yellow);//set background color.
int x,y,y1,x1,a,b,p1x,p1y,p2x,p2y;
int xstart = 7;
int ystart = 1;
int xfinish = 3;
.......
bhfvhn.java
import javax.swing.*;
import java.awt.*;
import javax.swing.JPanel;
public class ControlsA extends JPanel{
public void init (Box g) {
a = Box.createVerticalBox();
a.add(new JLabel("Please enter the values below:"));
a.add(new JLabel("h"));
}
}
jknmk.java
import javax.swing.*;
import java.awt.Component;
import java.awt.Dimension;
public class ControlsB extends JPanel{
public void init (Box b) {
b = Box.createHorizontalBox();
b.add(new JLabel("a"));
JTextField f1 = new JTextField("0.0");
f1.setMaximumSize(new Dimension(100,30));
b.add(f1);
}
}
Here is an updated to my project:
jkl.java
import java.awt.BorderLayout;
import java.awt.Container;
public class GraphApplet extends JApplet{
public GraphApplet() {
public void init(){
SwingUtilities.invokeLater(new Runnable() {
public void run(){
Container conn = getContentPane();
conn.setLayout(new BorderLayout());
Graph z = new Graph();
conn.add(p,BorderLayout.CENTER);
fasfae a = new ControlsA(box1);
conn.add(a,BorderLayout.LINE_START);
adsfawef b = new ControlsB(box2);
conn.add(b,BorderLayout.PAGE_END);
}
});
}
}
/*Container conn = getContentPane();
conn.setLayout(new BorderLayout());
Graph p = new Graph();//graph
p.setPreferredSize(new Dimension(460,560));
conn.add(p,BorderLayout.CENTER);
Box a = new Box(BoxLayout.Y_AXIS);
a.setPreferredSize(new Dimension(50,50));
conn.add(a,BorderLayout.EAST);
Box b = new Box(BoxLayout.X_AXIS);
b.setPreferredSize(new Dimension(201,50));
conn.add(b,BorderLayout.SOUTH);*/
//this code is commented not to loose it
vtk.java
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.JPanel;
class Graph extends JPanel {
public Graph(){
this.setBackground(Color.yellow);
}
#Override
public Dimension getPreferredSize(){return (new Dimension(460,560)); }
public void paint(Graphics z) {
Graphics graph = (Graphics2D)z;
this.setBackground(Color.yellow).
int x,y,y1,x1,a,b,p1x,p1y,p2x,p2y;
//line co-ordinates
//the numbers represent the number of boxes on the graph
int xstart = 7;
int ystart = 1;
int x = 3;
int y = 9;
//other variables
int i = 0;
int i2 = 0;
int m = 0;
int n = 0;
int m2 = 0;
int n2 = 0;
int f2 = 0;
int g2 = 1;
//ranges
int f = 5;
int g = -5;
//change -ve num to +ve
int g3 = Math.abs(g);
int a1 = g3 + f;
int b1 = a1;
a = (Height);
f = (Width);
}
}
}
// 6 variables the user has to input
}
#Override
public Dimension getPreferredSize() {return (new Dimension(200,100));}
}
nllkl.java
#Override
public Dimension getPreferredSize(){return (new Dimension(201,50));}
}
Still no improvement. I cannot understand what is going on.
The main problems in that code are:
The applet is adding 3 instances of panel as opposed to one each of panel, panelB & panelC.
Neither panelB & panelC ever adds the Box to the panel, so it will not appear.
You intimate in the code that panelB should be vertically aligned, which means it would better fit in the LINE_START (WEST) of the BorderLayout, as opposed to the NORTH.
public void paint(Graphics p) {.. is wrong for panel. Since panel is a Swing JPanel it should be public void paintComponent(Graphics p) {..
Once those things are attended to, this is how it might appear.
Other problems.
The only code that needs to extend a class is for the applet itself and panel. In fact, even the panel could be changed to show a BufferedImage (the graph) inside a JLabel
The panelB and panelC are entirely redundant, just add a Box directly to the layout area of the parent component needed.
The nomenclature is wrong.
Java class names should be EachWordUpperCase
Use meaningful class names - the applet might be GraphApplet, the graphing area Graph, ..I am not sure what to call the last 2 panels, since they carry identical components. If there were but one, I might call it Controls as a class (which is overkill for this), or controls if it were an instance of a plain JPanel or Box.
None of the calls to set maximum or preferred size are recommended in this situation. The only case that can be made for it is in the preferred size of the graph itself, but since this appears in the CENTER of applet, a size will be suggested by the applet width/height specified in HTML, minus the natural size of the other components (the CENTER component will get 'the rest of the space').
Update
..how am I going to change the code in my applet so that the applet adds one of each panel(?)
Change:
panel a = new panel();//vertical
To:
panelB a = new panelB(new Box(BoxLayout.Y_AXIS));//vertical
Is the simplest way. Note that it changes if you decide to add the Box directly.
Box a = new Box(BoxLayout.Y_AXIS);//vertical
Please try to run this code now, tell me is this closer to what you wanted ? if so do let me know, so that I can delete my answer. Do watch the changes I had done :
in your PanelC class, where instead of using init() method, I
made the constructor.
Inside your Graph class< i had removed all setPreferredSizes(...)
calls, and instead I had overridden getPreferredSize() for each
Class extending JPanel. For this visit each Class Panel, PanelB and
PanelC.
Lastly I had changed the Dimension values supplied to the JPanel,
which is to go to the LEFT/LINE_START side, to something that can
be seen
BEST CHANGE is the use of EDT - Event Dispatch Thread, seems like you
really not aware of Concurrency in Swing
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class Graph extends JApplet{
public void init(){
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
Container conn = getContentPane();
conn.setLayout(new BorderLayout());
Panel p = new Panel();//graph
conn.add(p,BorderLayout.CENTER);
Box box1 = new Box(BoxLayout.Y_AXIS);
PanelB a = new PanelB(box1);//vertical
conn.add(a,BorderLayout.LINE_START);
Box box2 = new Box(BoxLayout.X_AXIS);
PanelC b = new PanelC(box2);//horizontal
conn.add(b,BorderLayout.PAGE_END);
}
});
}
}
class Panel extends JPanel {
public Panel(){
this.setBackground(Color.yellow);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(460,560));
}
public void paintComponent(Graphics p) {
super.paintComponent(p);
Graphics2D graph = (Graphics2D)p;
Dimension appletSize = this.getSize();
int appletHeight = (int)(appletSize.height);
int appletWidth = appletSize.width;
this.setBackground(Color.yellow);//set background color.
int x,y,y1,x1,a,b,p1x,p1y,p2x,p2y;
//line co-ordinates
//the numbers represent the number of boxes on the graph
int xstart = 7;
int ystart = 1;
int xfinish = 3;
int yfinish = 9;
//other variables
int i = 0;
int i2 = 0;
int m = 0;
int n = 0;
int m2 = 0;
int n2 = 0;
int f2 = 0;
int g2 = 1;
//ranges
int f = 5;
int g = -5;
//change -ve num to +ve
int g3 = Math.abs(g);
int a1 = g3 + f;
int b1 = a1;
y1 = (appletHeight);
x1 = (appletWidth);
y = (appletHeight / 2);
x = (appletWidth / 2);
a = (appletWidth / a1);
b = (appletHeight / b1);
int d = (appletWidth / a1);
int e = (appletHeight / b1);
/**
to determine the
ammount of pixles there
is in each box of the
graph, both y-axis and
x-axis
*/
int xbox = x1 / 10;
int ybox = y1 / 10;
//line variables
//the xstart, ystart, etc represent the number of boxes
//top point of the line on the graph
p1x = xbox * xstart;//start x
p1y = ybox * ystart;//start y
//lowwer point of the line on the graph
p2x = xbox * xfinish;//finish x
p2y = ybox * yfinish;//finish y
//draw y-axis numbers
//(+ve)
while(f != 0){
String s = String.valueOf(f);
p.drawString(s,(x + 5),m + 13);
m = m + b;
f = f - 1;
}
//(-ve)
m2 = y;
while(f2 != g-1){
String u = String.valueOf(f2);
p.drawString(u,(x + 5),m2 - 3);
m2 = m2 + b;
f2 = f2 - 1;
}
//draw x-axis numbers.
//(-ve)
while(g != 0){
String t = String.valueOf(g);
p.drawString(t,n,y - 5);
n = n + a;
g = g + 1;
}
//(+ve)
n2 = x + a;
while(g2 != g3+1){
String vw = String.valueOf(g2);
p.drawString(vw,n2 -10,y - 5);
n2 = n2 + a;
g2 = g2 + 1;
}
BasicStroke aLine2 = new BasicStroke(1.0F,
BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
graph.setStroke(aLine2);
//notch on numbers and grid lines
//left to right, top to bottom notches
int v2 = -5;
int v5 = 0;
while(i <= a1-1){
p.setColor(Color.lightGray);//lightgray line
p.drawLine(a,0,a,y1);//vertical lightgray
p.drawLine(0,b,x1,b);//horizontal lightgray
a = a + d;
b = b + e;
i = i + 1;
}
//notches
while(i2 <= a1){
p.setColor(Color.blue);//notch color
p.drawString("x",v2+2,y+3);//xaxis
p.drawString("x",x-4,v5+4);//yaxis
v5 = v5 + e;
v2 = v2 + d;
i2 = i2 + 1;
}
//draws the border of the graph
p.setColor(Color.black);
Rectangle2D.Float rect = new Rectangle2D.Float(0,0,x1,y1);
BasicStroke aLine = new BasicStroke(2.5F,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
graph.setStroke(aLine);
graph.draw(rect);
//draw cross
BasicStroke aLine3 = new BasicStroke(2.5F,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
graph.setStroke(aLine3);
p.drawLine(x,0,x,y1); //vertical line
p.drawLine(0,y,x1,y); //horizontal line
//display the value of graph width and graph height
String aw = String.valueOf(x1);
p.drawString("Graph Width = ", 50,90);
p.drawString(aw,150,90);
p.drawString("Graph Height = ", 50,110);
String ah = String.valueOf(y1);
p.drawString(ah,156,110);
//draw line on graph
BasicStroke aLine4 = new BasicStroke(1.5F,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
graph.setStroke(aLine4);
p.setColor(Color.red);
if(p1x <= x1 && p2x <= x1 && p1y <= y1 && p2y <= y1){
p.drawLine(p1x,p1y,p2x,p2y);
Color c = new Color(0,0,0);
p.setColor(c);
p.drawString("X", p1x-4,p1y+4);
p.drawString("X", p2x-4,p2y+4);
}
else{
p.setColor(Color.black);
p.drawRect(48,34,223,35);
p.setColor(Color.white);
p.fillRect(49,35,222,34);
p.setColor(Color.red);
p.drawString("Wrong co-ordinates!!!", 50,50);
p.drawString("Values exceede applet dimensions.", 50,65);
}
}
}
class PanelB extends JPanel{
public PanelB (Box a) {
a = Box.createVerticalBox();
a.add(new JLabel("Please enter the values below:"));
a.add(new JLabel("a"));
JTextField g1 = new JTextField("0.0");
g1.setMaximumSize(new Dimension(100,30));
a.add(g1);
a.add(new JLabel("b"));
JTextField g2 = new JTextField("0.0");
g2.setMaximumSize(new Dimension(100,30));
a.add(g2);
a.add(new JLabel("c"));
JTextField g3 = new JTextField("0.0");
g3.setMaximumSize(new Dimension(100,30));
a.add(g3);
a.add(new JLabel("d"));
JTextField g4 = new JTextField("0.0");
g4.setMaximumSize(new Dimension(100,30));
a.add(g4);
a.add(new JButton("Plot"));
a.add(new JButton("Refine"));
add(a);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(200,100));
}
}
class PanelC extends JPanel{
public PanelC (Box b) {
b = Box.createHorizontalBox();
b.add(new JLabel("a"));
JTextField f1 = new JTextField("0.0");
f1.setMaximumSize(new Dimension(100,30));
b.add(f1);
b.add(new JLabel("b"));
JTextField f2 = new JTextField("0.0");
f2.setMaximumSize(new Dimension(100,30));
b.add(f2);
b.add(new JLabel("c"));
JTextField f3 = new JTextField("0.0");
f3.setMaximumSize(new Dimension(100,30));
b.add(f3);
b.add(new JLabel("d"));
JTextField f4 = new JTextField("0.0");
f4.setMaximumSize(new Dimension(100,30));
b.add(f4);
b.add(new JButton("Plot"));
b.add(new JButton("Refine"));
add(b);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(201,50));
}
}
Here is the HTML file I used :
<html>
<p> This file launches the 'Graph' applet: Graph.class! </p>
<applet code= "Graph.class" height = 550 width = 1000>
No Java?!
</applet>
</html>
Here is the output I am getting :