DrawImage() on JPanel help...
Hello folks,
Im a student, working on a project involving drawing pictures on JPanels. (Specifically, its a board game that has 50 spaces and a player piece, which is a JPEG, must be drawn on the panel and moved around to different spaces with the mouse.)
I have a big JPanel as the board, and then 50 smaller JPanels as the spaces on the board. As far as the mouse movement detection, Im sure I can use a mouseMotionListener on the board panel, and compare where the player clicked with the coordinates of the spaces on the board. However, I am having trouble figuring out how to draw an image on the board panel. It would probably be easier to make my own custom panel that extends JPanel, but Im too far into it to go back and redo all of that. My question is, how would I draw a JPEG on a regular JPanel? I know I need to use an imageIcon and drawImage(), specifying the picture I want drawn and the coordinates of where I would like it to go - however, Im not sure where I should put these method calls. I've tried for quite a while without any luck... so any help would be appreciated.
Eric
Maybe this thread will give you an idea:
http://forum.java.sun.com/thread.jsp?forum=57&thread=492100
Similar Messages
-
DrawImage into JPanel creates an imaginary panel??
Hi there,
I'm new (to here and to Java) but I'm having this problem. I'm trying to get 26 image files all layered on top of one another in a JPanel, and I've managed to get them to show up, but they come up in only a small part of my JPanel? If I change the alignment it just changes their alignment within this small rectangle? I've looked over and over my code, but can't find anything obviously wrong, can anyone else?!
This is the class MyImages which loads and displays the images:
package mmv2;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
@author bryonywalker
public class MyImages2 extends JPanel{
private MyClip mc1;
private String[] imageFiles = {
"mmv2/classical1.png",
"mmv2/classical2.png",
"mmv2/classical3.png",
"mmv2/dance1.png",
"mmv2/dance2.png",
"mmv2/dance3.png",
"mmv2/dance4.png",
"mmv2/jazz1.png",
"mmv2/jazz2.png",
"mmv2/jazz3.png",
"mmv2/jazz4.png",
"mmv2/latin1.png",
"mmv2/latin2.png",
"mmv2/latin3.png",
"mmv2/pop1.png",
"mmv2/pop2.png",
"mmv2/pop3.png",
"mmv2/pop4.png",
"mmv2/reggae1.png",
"mmv2/reggae2.png",
"mmv2/reggae3.png",
"mmv2/reggae4.png",
"mmv2/rock1.png",
"mmv2/rock2.png",
"mmv2/rock3.png",
"mmv2/rock4.png"
private BufferedImage[] img = new BufferedImage[imageFiles.length];
private static ClassLoader cL;
public MyImages2(){
initComponents();
readImages();
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 270, Short.MAX_VALUE)
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 300, Short.MAX_VALUE)
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
public void readImages() {
URL url;
try {
cL = this.getClass().getClassLoader();
for (int i = 0; i < imageFiles.length; i++) {
url = cL.getResource(imageFiles);
img[i] = ImageIO.read(url);
} catch (IOException e) {
System.out.println("IO Exception");
mc1.tidyUpAndExit(1);
@Override
protected void paintComponent(Graphics g) {
System.out.println ("beginning of PC");
super.paintComponent(g);
if(img != null)
for (int i = 0; i < imageFiles.length; i++) {
System.out.println("before" +img[i]);+
+ g.drawImage(img[i], 0, 0, this);+
+ System.out.println("after"+ img[i]);
else{
System.out.println("img=null!!");
}And the part of my frame class which calls it:public class MainFrame extends javax.swing.JFrame {
private MyClip mc;
private MyImages2 mi;
public MainFrame() {
initComponents();
mi = new MyImages2();
jPanel3.add(mi);
mc = new MyClip();
}Very grateful for any help/hints. It is currently looking like this: [Current GUI|http://i46.tinypic.com/m9ob9g.jpg] where the orange panel on the right is "jPanel3" - and those photos should be filling up this panel!This line g.drawImage(img, 0, 0, this);will draw the images at their true pixel size. If you want the images to be scaled to fit the panel, you will need to use a form of drawImage that takes a width and height as a parameter, probably drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
db
edit Unless many of the images have considerable transparent areas, it doesn't seem to make sense to draw them all at the same point though. What exactly are you trying to achieve?
Edited by: DarrylBurke -
hey,
I'm making a calculator program with a function graphing part using JFrame and JPanel. But these two have been causing problems because when I run the GraphMain class, only a portion of the graph shows up. I have tested the Main and Graph classes and they work but the problem is the GraphMain class. Could somebody please help. here are the three classes:
import java.util.Scanner;
import java.util.ArrayList;
//"Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction"
//NEED TO HANDLE NEGATIVE NUMBERS AND DIFFERENCE BETWEEN MINUS
//RECURSIVE SOLVE DOESN'T WORK FOR INPUT WITH TWO SET PARENTHESIS EX. (1+56)(3/8)
public class Main
public static ArrayList<Character> symbols;
public static double lastAnswer;
public static boolean radians;
public static void main(String[] args)
//initialize recognized symbols
symbols = new ArrayList<Character>();
symbols.add('+');
symbols.add('~');
symbols.add('*');
symbols.add('/');
symbols.add('%');
symbols.add('^');
symbols.add('s');
symbols.add('c');
symbols.add('t');
symbols.add('l');
radians = true;
Scanner in = new Scanner(System.in);
System.out.println("CALCULATOR (h for help)");
System.out.println("NOTE: ~ represents minus, - represents negative");
String input = "";
input = clearWhitespace(in.nextLine());
while (!input.equalsIgnoreCase("q"))
if (input.equalsIgnoreCase("graph"))
System.out.println("Opening function graphing window...");
if (input.equalsIgnoreCase("h"))
System.out.println("\nVARIABLES");
System.out.println("ans = last answer");
System.out.println("@ = pi = 3.14...");
System.out.println("# = e = 2.718...");
System.out.println("\nKEYS");
System.out.println("h = help");
System.out.println("q = quit");
System.out.println("* = multiply");
System.out.println("~ = subtract");
System.out.println("+ = add");
System.out.println("/ = divide");
System.out.println("% = modulus");
System.out.println("sin = sine");
System.out.println("cos = cosine");
System.out.println("tan = tangent");
System.out.println("csc = cosecant");
System.out.println("sec = cosecant");
System.out.println("cot = cotangent");
System.out.println("asin = sine inverse");
System.out.println("acos = cosine inverse");
System.out.println("atan = tangent inverse");
System.out.println("acsc = cosecant inverse");
System.out.println("asec = cosecant inverse");
System.out.println("acot = cotangent inverse");
System.out.println("log = logarithm");
System.out.println("ln = natural logarithm");
System.out.println("() = solve first");
System.out.println("ENTER = solve");
System.out.println("\nFUNCTIONS");
System.out.println("checkDiagnostics");
System.out.println("enableRadians");
System.out.println("enableDegrees\n");
else if (diagnostics(input) != null)
System.out.println(diagnostics(input));
else if (!input.equals(""))
try
System.out.println("= " + solve(replaceVariables(input)));
catch (IllegalArgumentException ex)
System.out.println(ex.getMessage());
input = clearWhitespace(in.nextLine());
/*String blah = "(415(645(2762+4)2524)4256465)";
String la = blah.substring(findParenthesis(blah)[0], findParenthesis(blah)[1]);
System.out.println(la);*/
/*String gah = "2+7*356*7+6+23*34";
gah = multiplyDivide(gah);
gah = addSubtract(gah);
System.out.println(gah);*/
/*int i = 1;
System.out.println(findNums(gah, i)[0]);
System.out.println(findNums(gah, i)[1]);
System.out.println(gah.substring(findNums(gah, i)[0], i));
System.out.println(gah.substring(i + 1, findNums(gah, i)[1]));*/
/*String foo = "2^2";
foo = exponents(foo);
System.out.println(foo);*/
/*String boo = "2sin~";
boo = replaceVariables(boo);
boo = trigonometry(boo);
System.out.println(boo);*/
/*String lala = "2546(23(4)2)24562";
System.out.println(lala.substring(findParenthesis(lala)[0] + 1, findParenthesis(lala)[1]));
System.out.println(lala.substring(0, findParenthesis(lala)[0]));*/
/*int q = 1000000;
double[] ys = new double[q];
for (int i = 1; i < q; i++)
ys[i] = Double.parseDouble(solve("sin(" + i + ")^(cos" + i + ")"));
System.out.println("DONE");*/
//about 41 seconds
//System.out.println(solveFunctionOfX("x^2", 3));
public static String solve(String theInput) throws IllegalArgumentException
String input = theInput;
int first = 0, last = 0;
try
first = findParenthesis(input)[0];
last = findParenthesis(input)[1];
catch (IllegalArgumentException ex)
throw ex;
String replace = "";
String temp = "";
while (first != -1 && last != -1)
replace = solve(input.substring(first + 1, last));
temp = "";
if (first != 0)
temp += input.substring(0, first);
if (first - 1 >= 0 && Character.isDigit(input.charAt(first - 1)))
temp += "*";
temp += replace;
if (last + 1 < input.length() && (Character.isDigit(input.charAt(last + 1)) || input.charAt(last + 1) == '-'))
temp += "*";
if (last != input.length() - 1)
temp += input.substring(last + 1, input.length());
input = temp;
first = findParenthesis(input)[0];
last = findParenthesis(input)[1];
try
input = fourLetterFunctions(input);
input = threeLetterFunctions(input);
input = twoLetterFunctions(input);
input = exponents(input);
input = multiplyDivide(input);
input = addSubtract(input);
lastAnswer = Double.parseDouble(input);
catch (IllegalArgumentException ex)
throw ex;
return input;
public static double solveFunctionOfX(String input, double x)
String solveFunction = "", solution = "";
for (int i = 0; i < input.length(); i++)
if (input.charAt(i) == 'x')
solveFunction += x;
else
solveFunction += input.charAt(i);
try
solution = solve(solveFunction);
catch (IllegalArgumentException ex)
return 0;
return Double.parseDouble(solution);
public static String clearWhitespace(String input)
String result = "";
for (int i = 0; i < input.length(); i++)
if (!Character.isWhitespace(input.charAt(i)))
result += input.substring(i, i+1);
return result;
public static int[] findParenthesis(String input)
int count = 0;
int first = -1, last = -1;
for (int i = 0; i < input.length(); i++)
if (input.charAt(i) == '(')
if (count == 0)
first = i;
count++;
else if (input.charAt(i) == ')')
count--;
if (count == 0)
last = i;
if (count > 0)
throw new IllegalArgumentException("Missing Right Parenthesis");
else if (count < 0)
throw new IllegalArgumentException("Missing Left Parenthesis");
return new int[]{first, last};
public static String addSubtract(String theInput)
int j, k;
double a, b, solution = 0;
String temp = "", input = theInput;
for (int i = 0; i < input.length(); i++)
if (input.charAt(i) == '+' || input.charAt(i) == '~')
j = findNums(input, i)[0];
k = findNums(input, i)[1];
b = Double.parseDouble(input.substring(i + 1, k));
if (i == 0)
if (input.charAt(i) == '+')
solution = lastAnswer + b;
else if (input.charAt(i) == '~')
solution = lastAnswer - b;
else
a = Double.parseDouble(input.substring(j, i));
if (input.charAt(i) == '+')
solution = a + b;
else if (input.charAt(i) == '~')
solution = a - b;
if (i != 0)
temp = input.substring(0, j);
temp += solution + input.substring(k, input.length());
input = temp;
i = 0;
return input;
public static String multiplyDivide(String theInput)
int j, k;
double a = 0, b = 0, solution = 0;
String temp = "", input = theInput;
for (int i = 0; i < input.length(); i++)
if (input.charAt(i) == '*' || input.charAt(i) == '/' || input.charAt(i) == '%')
j = findNums(input, i)[0];
k = findNums(input, i)[1];
b = Double.parseDouble(input.substring(i + 1, k));
if (i == 0)
if (input.charAt(i) == '*')
solution = lastAnswer * b;
else if (input.charAt(i) == '/')
if (b == 0)
throw new IllegalArgumentException("Divide by Zero Error");
solution = lastAnswer / b;
else if (input.charAt(i) == '%')
solution = lastAnswer % b;
else
a = Double.parseDouble(input.substring(j, i));
if (input.charAt(i) == '*')
solution = a * b;
else if (input.charAt(i) == '/')
if (b == 0)
throw new IllegalArgumentException("Divide by Zero Error");
solution = a / b;
else if (input.charAt(i) == '%')
solution = a % b;
if (i != 0)
temp = input.substring(0, j);
temp += solution + input.substring(k, input.length());
input = temp;
i = 0;
return input;
public static String exponents(String theInput)
int j, k;
double a, b, solution = 0;
String temp = "", input = theInput;
for (int i = 0; i < input.length(); i++)
if (input.charAt(i) == '^')
j = findNums(input, i)[0];
k = findNums(input, i)[1];
b = Double.parseDouble(input.substring(i + 1, k));
if (i == 0)
if (input.charAt(i) == '^')
solution = Math.pow(lastAnswer, b);
else
a = Double.parseDouble(input.substring(j, i));
if (input.charAt(i) == '^')
solution = Math.pow(a, b);
if (i != 0)
temp = input.substring(0, j);
temp += solution + input.substring(k, input.length());
input = temp;
i = 0;
return input;
public static String fourLetterFunctions(String theInput)
int k;
double b, solution = 0;
String temp = "", input = theInput;
for (int i = 0; i < input.length() - 4; i++)
if (input.substring(i, i + 4).equals("asin") || input.substring(i, i + 4).equals("acos") || input.substring(i, i + 4).equals("atan") || input.substring(i, i + 4).equals("acsc") || input.substring(i, i + 4).equals("asec") || input.substring(i, i + 4).equals("acot"))
k = findNums(input, i + 3)[1];
b = Double.parseDouble(input.substring(i + 4, k));
//System.out.println(b);
if (input.substring(i, i + 4).equals("asin"))
if (Math.abs(b) > 1)
throw new IllegalArgumentException("Out of Domain");
solution = (radians? Math.asin(b) : Math.asin(b) * 180 / Math.PI);
else if (input.substring(i, i + 4).equals("acos"))
if (Math.abs(b) > 1)
throw new IllegalArgumentException("Out of Domain");
solution = (radians? Math.acos(b) : Math.acos(b) * 180 / Math.PI);
else if (input.substring(i, i + 4).equals("atan"))
solution = (radians? Math.atan(b) : Math.atan(b) * 180 / Math.PI);
else if (input.substring(i, i + 4).equals("acsc"))
if (Math.abs(b) < 1)
throw new IllegalArgumentException("Out of Domain");
solution = (radians? Math.asin(1 / b) : Math.asin(1 / b) * 180 / Math.PI);
else if (input.substring(i, i + 4).equals("asec"))
if (Math.abs(b) < 1)
throw new IllegalArgumentException("Out of Domain");
solution = (radians? Math.acos(1 / b) : Math.acos(1 / b) * 180 / Math.PI);
else if (input.substring(i, i + 4).equals("acot"))
solution = 1 / (radians? Math.atan(1 / b) : Math.atan(1 / b) * 180 / Math.PI);
//System.out.println(solution);
if (i != 0)
temp = input.substring(0, i);
if (i != 0 && Character.isDigit(input.charAt(i - 1)))
temp += "*";
temp += solution;
temp += input.substring(k, input.length());
input = temp;
//System.out.println(temp);
i = 0;
return input;
public static String threeLetterFunctions(String theInput)
int k;
double b, solution = 0;
String temp = "", input = theInput;
for (int i = 0; i < input.length() - 3; i++)
if (input.substring(i, i + 3).equals("sin") || input.substring(i, i + 3).equals("cos") || input.substring(i, i + 3).equals("tan") || input.substring(i, i + 3).equals("log") || input.substring(i, i + 3).equals("csc") || input.substring(i, i + 3).equals("sec") || input.substring(i, i + 3).equals("cot"))
k = findNums(input, i + 2)[1];
b = Double.parseDouble(input.substring(i + 3, k));
//System.out.println(b);
if (input.substring(i, i + 3).equals("sin"))
solution = Math.sin((radians? b : b * 180 / Math.PI));
else if (input.substring(i, i + 3).equals("cos"))
solution = Math.cos((radians? b : b * 180 / Math.PI));
else if (input.substring(i, i + 3).equals("tan"))
if ((b + Math.PI / 2) % Math.PI == 0)
throw new IllegalArgumentException("Out of Domain");
solution = Math.tan((radians? b : b * 180 / Math.PI));
else if (input.substring(i, i + 3).equals("log"))
if (b <= 0)
throw new IllegalArgumentException("Out of Domain");
solution = Math.log10(b);
if (input.substring(i, i + 3).equals("csc"))
if (b % Math.PI == 0)
throw new IllegalArgumentException("Out of Domain");
solution = 1 / Math.sin((radians? b : b * 180 / Math.PI));
else if (input.substring(i, i + 3).equals("sec"))
if ((b + Math.PI / 2) % Math.PI == 0)
throw new IllegalArgumentException("Out of Domain");
solution = 1 / Math.cos((radians? b : b * 180 / Math.PI));
else if (input.substring(i, i + 3).equals("cot"))
if (b % Math.PI == 0)
throw new IllegalArgumentException("Out of Domain");
solution = 1 / Math.tan((radians? b : b * 180 / Math.PI));
//System.out.println(solution);
if (i != 0)
temp = input.substring(0, i);
if (i != 0 && Character.isDigit(input.charAt(i - 1)))
temp += "*";
temp += solution;
temp += input.substring(k, input.length());
input = temp;
//System.out.println(temp);
i = 0;
return input;
public static String twoLetterFunctions(String theInput)
int k;
double b, solution = 0;
String temp = "", input = theInput;
for (int i = 0; i < input.length() - 2; i++)
if (input.substring(i, i + 2).equals("ln"))
k = findNums(input, i + 1)[1];
b = Double.parseDouble(input.substring(i + 2, k));
//System.out.println(b);
if (input.substring(i, i + 2).equals("ln"))
if (b <= 0)
throw new IllegalArgumentException("Out of Domain");
solution = Math.log(b);
//System.out.println(solution);
if (i != 0)
temp = input.substring(0, i);
if (i != 0 && Character.isDigit(input.charAt(i - 1)))
temp += "*";
temp += solution;
temp += input.substring(k, input.length());
input = temp;
//System.out.println(temp);
i = 0;
return input;
public static String replaceVariables(String theInput)
String input = theInput;
String temp = "";
for (int i = 0; i < input.length(); i++)
if (input.charAt(i) == '#')
temp = input.substring(0, i);
if (i != 0 && Character.isDigit(input.charAt(i - 1)))
temp += "*";
temp += Math.E;
if (i != input.length() - 1 && (Character.isDigit(input.charAt(i + 1)) || input.charAt(i + 1) == '-'))
temp += "*";
temp += input.substring(i+1, input.length());
input = temp;
else if (input.charAt(i) == '@')
temp = input.substring(0, i);
if (i != 0 && Character.isDigit(input.charAt(i - 1)))
temp += "*";
temp += Math.PI;
if (i != input.length() - 1 && (Character.isDigit(input.charAt(i + 1)) || input.charAt(i + 1) == '-'))
temp += "*";
temp += input.substring(i+1, input.length());
input = temp;
else if (i < input.length() - 2 && input.substring(i, i + 3).equals("ans"))
temp = input.substring(0, i);
if (i != 0 && Character.isDigit(input.charAt(i - 1)))
temp += "*";
temp += lastAnswer;
if (i != input.length() - 3 && (Character.isDigit(input.charAt(i + 3)) || input.charAt(i + 3) == '-'))
temp += "*";
temp += input.substring(i+3, input.length());
input = temp;
return input;
public static int[] findNums(String input, int charPos)
int k = charPos - 1, j = charPos + 1;
while (k > 0 && (Character.isDigit(input.charAt(k - 1)) || input.charAt(k - 1) == 'E' || input.charAt(k - 1) == '.' || input.charAt(k - 1) == '-'))
k--;
while(j < input.length() && (Character.isDigit(input.charAt(j)) || input.charAt(j) == 'E' || input.charAt(j) == '.' || input.charAt(j) == '-'))
j++;
return new int[]{k,j};
public static String diagnostics(String input)
if (input.equals("checkDiagnostics"))
return "" + (radians? "radians":"degrees");
else if (input.equalsIgnoreCase("radians?"))
return "" + radians;
else if (input.equalsIgnoreCase("enabledegrees"))
radians = false;
return "done";
else if (input.equalsIgnoreCase("enableradians"))
radians = true;
return "done";
else
return null;
import java.awt.Color;
import java.awt.Graphics;
public class Graph
public Graph(int axMin, int axMax, int ayMin, int ayMax, int aappletSize)
/*xSize = x;
ySize = y;*/
xMin = axMin;
xMax = axMax;
yMin = ayMin;
yMax = ayMax;
appletSize = aappletSize;
xScaling = (double) appletSize/(Math.abs(xMin) + Math.abs(xMax));
yScaling = (double) appletSize/(Math.abs(yMin) + Math.abs(yMax));
//System.out.println(xScaling);
//System.out.println(yScaling);
rectCenterX = (xMin + xMax )/ 2;
rectCenterY = (yMin + yMax) / 2;
//System.out.println(rectCenterX);
//System.out.println(rectCenterY);
appletCenterX = (int)((appletSize / 2) - (rectCenterX * xScaling));
appletCenterY = (int)((appletSize / 2) - (rectCenterY * yScaling));
//System.out.println(appletCenterX);
//System.out.println(appletCenterY);
functions = new String[10];
functionsBoolean = new boolean[10];
functionSolutions = new double[10][appletSize];
functionAppletSolutions = new int[10][appletSize];
axis = true;
public void drawGraph(Graphics g)
drawAxis(g);
drawFunctions(g);
public void setFunction(int num, String function)
functions[num] = function;
solveFunctions(num);
public void enableDisableFunction(int function, boolean state)
functionsBoolean[function] = state;
private void drawFunctions(Graphics g)
for (int i = 0; i < 10; i++)
if (functionsBoolean)
g.setColor(colors[i]);
for (int j = 0; j < appletSize - 1; j++)
if ((functionAppletSolutions[i][j + 1] > 0 && functionAppletSolutions[i][j + 1] < appletSize) || (functionAppletSolutions[i][j] > 0 && functionAppletSolutions[i][j] < appletSize))
g.drawLine(j, functionAppletSolutions[i][j], j + 1, functionAppletSolutions[i][j + 1]);
private void solveFunctions(int i)
for (int j = 0; j < appletSize; j++)
//System.out.println(convertToRectangular(j,0)[0]);
//System.out.println(functions.get(i));
//System.out.println(Main.solveFunctionOfX(functions.get(i), convertToRectangular(j,0)[0]));
functionSolutions[i][j] = Main.solveFunctionOfX(functions[i], convertToRectangular(j,0)[0]);
functionAppletSolutions[i][j] = convertToApplet(0, functionSolutions[i][j])[1];
private double[] convertToRectangular(int appletX, int appletY)
double newX = 0, newY = 0;
newX = (double) ((appletX - appletCenterX) / xScaling);
newY = (double) ((appletY - appletCenterY) / yScaling);
return new double[]{newX, newY};
private int[] convertToApplet(double x, double y)
int newX = 0, newY = 0;
newX = (int) (x * xScaling) + appletCenterX;
newY = (int) (-y * yScaling) + appletCenterY;
return new int[]{newX, newY};
private void drawAxis(Graphics g)
if (axis)
g.setColor(Color.black);
//x-axis
g.drawLine(0, appletCenterY, appletSize, appletCenterY);
//y-axis
g.drawLine(appletCenterX, 0, appletCenterX, appletSize);
public void printSolutions(int functionNumber)
for (int i = 0; i < appletSize; i++)
System.out.println(convertToRectangular(i,0)[0] + " | " + functionSolutions[functionNumber][i]);
public void printAppletSolutions(int functionNumber)
for (int i = 0; i < appletSize; i++)
System.out.println(i + " | " + functionAppletSolutions[functionNumber][i]);
public void printFunctionsBoolean()
for (int i = 0; i < functionsBoolean.length; i++)
System.out.println(i + " | " + functionsBoolean[i]);
private boolean axis;
private String[] functions;
private double[][] functionSolutions;
private int[][] functionAppletSolutions;
private boolean[] functionsBoolean;
private int xMin;
private int xMax;
private int yMin;
private int yMax;
private int appletSize;
private double rectCenterX;
private double rectCenterY;
private int appletCenterX;
private int appletCenterY;
private double xScaling;
private double yScaling;
private static Color[] colors = new Color[]{Color.blue, Color.cyan, Color.green, Color.magenta, Color.orange, Color.pink, Color.red, Color.yellow, Color.gray, Color.darkGray};
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
public class GraphMain implements ActionListener, ItemListener
public JMenuBar createJMenuBar()
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(this);
fileMenu.add(exit);
JMenu functionMenu = new JMenu("Function");
menuBar.add(functionMenu);
JMenu function1 = new JMenu("function 1");
JMenuItem edit1 = new JMenuItem("edit 1");
JCheckBoxMenuItem enable1 = new JCheckBoxMenuItem("enable 1");
edit1.addActionListener(this);
enable1.addItemListener(this);
function1.add(edit1);
function1.add(enable1);
functionMenu.add(function1);
JMenu function2 = new JMenu("function 2");
JMenuItem edit2 = new JMenuItem("edit 2");
JCheckBoxMenuItem enable2 = new JCheckBoxMenuItem("enable 2");
edit2.addActionListener(this);
enable2.addItemListener(this);
function2.add(edit2);
function2.add(enable2);
functionMenu.add(function2);
JMenu function3 = new JMenu("function 3");
JMenuItem edit3 = new JMenuItem("edit 3");
JCheckBoxMenuItem enable3 = new JCheckBoxMenuItem("enable 3");
edit3.addActionListener(this);
enable3.addItemListener(this);
function3.add(edit3);
function3.add(enable3);
functionMenu.add(function3);
JMenu function4 = new JMenu("function 4");
JMenuItem edit4 = new JMenuItem("edit 4");
JCheckBoxMenuItem enable4 = new JCheckBoxMenuItem("enable 4");
edit4.addActionListener(this);
enable4.addItemListener(this);
function4.add(edit4);
function4.add(enable4);
functionMenu.add(function4);
JMenu function5 = new JMenu("function 5");
JMenuItem edit5 = new JMenuItem("edit 5");
JCheckBoxMenuItem enable5 = new JCheckBoxMenuItem("enable 5");
edit5.addActionListener(this);
enable5.addItemListener(this);
function5.add(edit5);
function5.add(enable5);
functionMenu.add(function5);
JMenu function6 = new JMenu("function 6");
JMenuItem edit6 = new JMenuItem("edit 6");
JCheckBoxMenuItem enable6 = new JCheckBoxMenuItem("enable 6");
edit6.addActionListener(this);
enable6.addItemListener(this);
function6.add(edit6);
function6.add(enable6);
functionMenu.add(function6);
JMenu function7 = new JMenu("function 7");
JMenuItem edit7 = new JMenuItem("edit 7");
JCheckBoxMenuItem enable7 = new JCheckBoxMenuItem("enable 7");
edit7.addActionListener(this);
enable7.addItemListener(this);
function7.add(edit7);
function7.add(enable7);
functionMenu.add(function7);
JMenu function8 = new JMenu("function 8");
JMenuItem edit8 = new JMenuItem("edit 8");
JCheckBoxMenuItem enable8 = new JCheckBoxMenuItem("enable 8");
edit8.addActionListener(this);
enable8.addItemListener(this);
function8.add(edit8);
function8.add(enable8);
functionMenu.add(function8);
JMenu function9 = new JMenu("function 9");
JMenuItem edit9 = new JMenuItem("edit 9");
JCheckBoxMenuItem enable9 = new JCheckBoxMenuItem("enable 9");
edit9.addActionListener(this);
enable9.addItemListener(this);
function9.add(edit9);
function9.add(enable9);
functionMenu.add(function9);
JMenu function10 = new JMenu("function 10");
JMenuItem edit10 = new JMenuItem("edit 10");
JCheckBoxMenuItem enable10 = new JCheckBoxMenuItem("enable 10");
edit10.addActionListener(this);
enable10.addItemListener(this);
function10.add(edit10);
function10.add(enable10);
functionMenu.add(function10);
return menuBar;
public Container createContentPane()
JPanel contentPane = new JPanel()
public void run()
while (true)
repaint();
public void paintComponent(Graphics g)
//System.out.println(getWidth());
//System.out.println(getHeight());
graph.drawGraph(g);
//graph.printAppletSolutions(0);
contentPane.setOpaque(true);
return contentPane;
public void actionPerformed(ActionEvent e)
JMenuItem source = (JMenuItem) (e.getSource());
String what = source.getText();
if (what.equals("Exit"))
quit();
else if (what.equals("edit 1"))
graph.setFunction(0, JOptionPane.showInputDialog(null, "Enter function 1."));
else if (what.equals("edit 2"))
graph.setFunction(1, JOptionPane.showInputDialog(null, "Enter function 2."));
else if (what.equals("edit 3"))
graph.setFunction(2, JOptionPane.showInputDialog(null, "Enter function 3."));
else if (what.equals("edit 4"))
graph.setFunction(3, JOptionPane.showInputDialog(null, "Enter function 4."));
else if (what.equals("edit 5"))
graph.setFunction(4, JOptionPane.showInputDialog(null, "Enter function 5."));
else if (what.equals("edit 6"))
graph.setFunction(5, JOptionPane.showInputDialog(null, "Enter function 6."));
else if (what.equals("edit 7"))
graph.setFunction(6, JOptionPane.showInputDialog(null, "Enter function 7."));
else if (what.equals("edit 8"))
graph.setFunction(7, JOptionPane.showInputDialog(null, "Enter function 8."));
else if (what.equals("edit 9"))
graph.setFunction(8, JOptionPane.showInputDialog(null, "Enter function 9."));
else if (what.equals("edit 10"))
graph.setFunction(9, JOptionPane.showInputDialog(null, "Enter function 10."));
public void itemStateChanged(ItemEvent e)
JCheckBoxMenuItem source = (JCheckBoxMenuItem)(e.getSource());
String what = source.getText();
if (what.equals("enable 1"))
graph.enableDisableFunction(0, source.getState());
else if (what.equals("enable 2"))
graph.enableDisableFunction(1, source.getState());
else if (what.equals("enable 3"))
graph.enableDisableFunction(2, source.getState());
else if (what.equals("enable 4"))
graph.enableDisableFunction(3, source.getState());
else if (what.equals("enable 5"))
graph.enableDisableFunction(4, source.getState());
else if (what.equals("enable 6"))
graph.enableDisableFunction(5, source.getState());
else if (what.equals("enable 7"))
graph.enableDisableFunction(6, source.getState());
else if (what.equals("enable 8"))
graph.enableDisableFunction(7, source.getState());
else if (what.equals("enable 9"))
graph.enableDisableFunction(8, source.getState());
else if (what.equals("enable 10"))
graph.enableDisableFunction(9, source.getState());
protected void quit()
System.exit(0);
private static void createAndShowGUI()
JFrame frame = new JFrame("Graph");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphMain main = new GraphMain();
frame.setJMenuBar(main.createJMenuBar());
frame.setContentPane(main.createContentPane());
frame.setSize(408, 457);
/*GraphComponent component = new GraphComponent();
frame.add(component);*/
frame.setVisible(true);
public static void main(String[] args)
/*for (int i = 1; i <= 10; i++)
System.out.println("JMenu function" + i + " = new JMenu(function " + i + ");\n" +
"JMenuItem edit" + i + " = new JMenuItem(edit " + i + ");\n" +
"JCheckBoxMenuItem enable" + i + " = new JCheckBoxMenuItem(enable " + i + ");\n" +
"edit" + i + ".addActionListener(this);\n" +
"enable" + i + ".addItemListener(this);\n" +
"function" + i + ".add(edit" + i + ");\n" +
"function" + i + ".add(enable" + i + ");\n" +
"functionMenu.add(function" + i + ");\n");
graph = new Graph(-10, 10, -10, 10, 400);
graph.setFunction(0, "x");
graph.setFunction(1, "x^2");
graph.setFunction(2, "x^3");
graph.setFunction(3, "x^4");
graph.setFunction(4, "x^5");
graph.setFunction(5, "x^6");
graph.setFunction(6, "x^7");
graph.sIf only the x-positive part of graph is showing up, check the behaviour of Math.pow
when the first argument is negative. (I know you are trying to raise numbers to a
positive integral power, but I have no idea what happens further up when you
parse the expression.) -
JScrollPane containing JPanel HELP!
Hi again,
I'll try my luck again!
Ok, I have a JPanel that uses a GridBagLayout with 3 columns and many rows. Each row is of the form:
[JLabel][JTextField][JButton]
Ok. Since I have many of these rows, and my application should be a constant size, I need to somehow make you able to scroll down the list of these labels,textfields and buttons - to the one you want. I have tried making the containing JPanel the viewport of a JScrollPane, however, when I only have a couple of rows of labels, textfields, and buttons, each expands to fit the viewport size - and they turn out looking really dumb.
How can I get it so that the labels, textfields and buttons are only the height of the text in each?
Please please, please, please help me.
sincerely, Edd.Chenge the weight (x&y) in the GridBagConstraints of the components you don't want to expand to 0.0. Change the fill to GridBagConstraints.NONE.
-
JPanel help, i am so very noob
hey, can someone help me with Jpanel, i want to make the JPanel like a gridlayout, does anyone know how? if not, can a Jframe have like a selfcontainedframe? (just wondering, i don't ecen know if that word exists, i know jpanel has a selfcontainedpanel or something)
Maybe you want in Internal Frame:
http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html
Take a look at the Table Of Contents from above. There is also a section on Layout Managers. -
Locate a JPanel in an other JPanel (HELP !!!)
I add the class affectation (see below) in a JPanel but I can't succeed in locating it in this JPanel..
I have tried to use setLocate and setBounds but it doesn't work
public class Affectation extends JPanel{
public Affectation(int deb, int fin,Color couleur){
this.setBackground(couleur);
this.setBorder(BorderFactory.createLineBorder(Color.black));
//this.setBounds(new Rectangle(deb,10,fin-deb,20));
this.setLocation(deb, 7);
this.setPreferredSize (new Dimension(fin-deb,20));
this.setMinimumSize (new Dimension(fin-deb,20));
this.setMaximumSize (new Dimension(fin-deb,20));
}Here's an example that uses absolute positioning to get a drag effect:import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
public Test () {
Dimension sizeA = new Dimension (300, 300);
Dimension sizeB = new Dimension (300, 300);
DragPanel dragPanelA = new DragPanel (sizeA, new Rectangle (100, 100, 100, 100), Color.YELLOW);
DragPanel dragPanelB = new DragPanel (sizeB, new Rectangle (100, 100, 100, 100), Color.GREEN);
WrapPanel wrapPanelA = new WrapPanel (sizeA, dragPanelA, Color.GREEN);
WrapPanel wrapPanelB = new WrapPanel (sizeB, dragPanelB, Color.YELLOW);
getContentPane ().setLayout (new GridLayout (1, 2));
getContentPane ().add (wrapPanelA);
getContentPane ().add (wrapPanelB);
setDefaultCloseOperation (DISPOSE_ON_CLOSE);
setResizable (false);
setTitle ("Drag those panels!");
pack ();
setLocationRelativeTo (null);
show ();
private class WrapPanel extends JPanel {
private Dimension size;
public WrapPanel (Dimension size, Component component, Color background) {
this.size = size;
setLayout (null);
add (component);
setBackground (background);
public Dimension getPreferredSize () {
return size;
private class DragPanel extends JPanel {
private Dimension outerSize;
private Rectangle bounds;
public DragPanel (Dimension outerSize, Rectangle bounds, Color background) {
this.outerSize = outerSize;
this.bounds = bounds;
setBounds (bounds);
setBackground (background);
DragListener dragListener = new DragListener ();
addMouseListener (dragListener);
addMouseMotionListener (dragListener);
private class DragListener implements MouseListener, MouseMotionListener {
private Point previousPoint;
public DragListener () {
previousPoint = null;
public void mousePressed (MouseEvent event) {
previousPoint = event.getPoint ();
public void mouseReleased (MouseEvent event) {
previousPoint = null;
public void mouseDragged (MouseEvent event) {
Point point = event.getPoint ();
int dx = point.x - previousPoint.x;
int dy = point.y - previousPoint.y;
bounds.x = getBetween (bounds.x + dx, 0, outerSize.width - bounds.width);
bounds.y = getBetween (bounds.y + dy, 0, outerSize.height - bounds.height);
setBounds (bounds);
private int getBetween (int value, int lower, int upper) {
return (value < lower) ? lower : (value > upper) ? upper : value;
public void mouseClicked (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
public void mouseMoved (MouseEvent event) {}
public static void main (String[] parameters) {
new Test ();
}Alternatively, you could create a super wrap panel (or something similar) to place the wrap panels in.
Kind regards,
Levi -
Javax.swing.JPanel Help
my application is sort of a game, i planned on having a JPanel subclass called EventPanel have an instance variable _curPanel.
curPanel is of type JPanel. In the constructor I can set curPanel to Other JPanel subclasses. I have another subclass of JPanel called MainScreen, which has the main screen for the game.
I can set curPanel = new MainScreen(); in the constructor for eventPanel. And it works.
But if I try to change _curPanel after i've made it, it wont show up. I have a method which signature
void setPanel(javax.swing.JPanel panel)
_curPanel = panel;
repaint();
}to change the EventPanel, but nothing changes.
In the MainScreen class there is a method call
_eventPanel.setPanel(new NewPlayerPanel());and nothing changes in the code. I have a JTextArea logging info, and in the constructor for NewPlayerPanel at the end it prints a message in my JTextArea. The Panel is being created but not showing up.
I have also tried creating the panel in an instance variable, setting it to setVisbile(true) and trying again and it doesnt work.In other words...
char c=evt.getKeyChar();c is some character based on this event.
if(c=='1'){Ok, let's say it is '1'...
...> char c2=evt.getKeyChar();Then c2 is also '1'.evt.getKeyChar() isn't going to magically change to be something different than it returned when you called it a few lines up before, so...>if(c2=='a')...this can never be true, given the above. -
i have a panel which is bigger than the main window's size. i want to add it onto the ScrollPane. but the scrollbar is not working. how do i refresh the scrollbar so that the scrollbar comes when the JPanel is attached onto it.
the full code is
public EditorPanel(int flag,String title,EditorFrame ed)
Toolkit tk=Toolkit.getDefaultToolkit();
clipBoard=tk.getSystemClipboard();
write = new JTextPane();
fileFlag=flag;
fileName=title;
edf=ed;
EditorKit editorKit = new StyledEditorKit()
public Document createDefaultDocument()
{return new ColorSyntax();
searchIndex=0;
// creating the toolbar
toolBar=new JToolBar();
addButtons(toolBar);
toolBar.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
toolBar.setFloatable(false);
toolBar.setBounds(0, 0, 800, 20);
write.setEditorKitForContentType("text/8085", editorKit);
write.setContentType("text/8085");
write.replaceSelection("");
write.requestFocus();
write.addKeyListener(this);
write.registerKeyboardAction(edf.getUndoAction(),KeyStroke.getKeyStroke,KeyEvent.VK_Z,InputEvent.CTRL_MASK),JComponent.WHEN_IN_FOCUSED_WINDOW);
write.registerKeyboardAction(edf.getRedoAction(),KeyStroke.getKeyStroke(KeyEvent.VK_Y,InputEvent.CTRL_MASK),JComponent.WHEN_IN_FOCUSED_WINDOW);
Dimension d=tk.getScreenSize();
StyledDocument styledDoc = write.getStyledDocument();
AbstractDocument doc = (AbstractDocument)styledDoc;
doc.addUndoableEditListener(new MyUndoableEditListener());
//problem is here
scrollpane = new JScrollPane(write);
scrollpane.setPreferredSize(new Dimension((2*d.width)/3 - 15,3*d.height/4));
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// making the object of the device panel to be added onto the device scroller
devAddPanel =new DeviceAddPanel();
deviceScrollpane = new JScrollPane();
deviceScrollpane.setViewportView(devAddPanel);
deviceScrollpane.setPreferredSize(new Dimension((d.width)/3 - 15,3*d.height/4));
deviceScrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(toolBar, BorderLayout.PAGE_START);
//Create a split pane with the two scroll panes in it.
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,deviceScrollpane,scrollpane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(((d.width)/3)-5);
splitPane.setContinuousLayout(true);
splitPane.setDividerSize(15);
add(splitPane, BorderLayout.CENTER);
//problem ends here
i am creating a split pane in which on the left i am adding the device panel which is giving the problem even though the panel is bigger that the scrollpane's size it is not showing the vertical scrollbar. the right side with the text area is working fine -
JPanel help Plzzzzzzzzzzz URGENT!
Hey,
I have JPanel filled with images........how to identify the images with mouse clicks...????????????????????Geez- the guy's a little desperate... be nice, people. It's not that hard.
Well, to answer the question, you simply need to gather the x/y coordinates of your images, determine the x/y coordinates of your mouseclick: add a Mouse Listener to your JComponent, with a Mouse Input Adapter as its argument. In the MouseInputAdapter, you create the mousePressed() method, like:
private MouseInputAdapter mia() {
MouseInputAdapter mia = new MouseInputAdapter() {
public void mousePressed(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
}Somewhere inside your mousePressed code you can have other code that looks to see if it's inside an image, etc. (substitute mouseClicked for mousePressed if you'd rather it be a complete click).
It's true, though, that the question is vague so a more structured and focussed query would probably gather a more focussed response.
-Mike Schwager -
Adding a jPanel to another jPanel help
I have a class NavigationButtonsClass which has the navigationalPanel which in turn has buttons back, next ... etc.
public JPanel navigationalPanel = new JPanel();
I have another class ProjectClass in which I gave the following
NavigationButtonsClass newNavigationButtonsClass = new NavigationButtonsClass();
jPanel1.add(newNavigationButtonsClass.navigationalPanel, new XYConstraints(0, 0, 795, -1));
this.getContentPane().add(jPanel1, new XYConstraints(1, 420, 798, 45));
Is something wrong here. I am not able to see the navigationalPanel.
Thanks.Modify ur NavigationButtonsClass like,
public class NavigationButtonsClass extends JPanel
add(backButton);
add(cancelButton);
}Now in ur ProjectClass
this.getContentPane().add(new NavigationButtonsClass(),BorderLayout.SOUTH);I have assumed ur Project class extends JFrame... -
Netbeans, java3d, menubar, toolbar, jpanel HELP
I'm attempting to make an application using netbeans which features a menu, a toolbar, and a jpanel beneath that which displays a Canvas3D. I got this to partially work, but the Canvas3D will not automatically resize. If I .add the canvas3D to the frame, then it resizes automatically but it writes over the toolbar (but not the jmenu since I made it inherit jpopupmenu).
Does anyone know of some good information for how to get 3D to work with a Java application? I don't even care if its Java3D...JOGL...any of the 3D libraries out there would be fine, I just need it to cooperate nicely with a GUI toolkit!
thanks for any info!!
-ZomHello, I am fighting with the netbeans platform + java3d as well and I am seeing the same problems as you have reported.
Are you using the netbeans RCP framework ?, if this is the case, could you
send me an email: [email protected]
Thanks a lot in advance! -
How do I draw an image through a rectangle?
I have worked with c# in the past, and i remember being able to draw an image but drawing it within the bounds of the rectangle. I would do this so collision detection was easy. Any suggestions?
btw since im so very new to the language, i am even having trouble with g.drawImage stuff :(
any help would be amazing -_-hollow wrote:
hmm ya i was messing around with that already, i guess im just retarded. i will keep looking thanks! ><No, you are not retarded. You are just incredibly impatient. Take a step back and ease yourself into the language. Take the time to read some articles while you're at it. I would also take a look at JavaFX2, it is a more modern approach to client application development and is less clunky than Java2D with a very active community. It might be that you are more comfortable with it. -
Getting the size of an internal frame?
Hi allm
I want to be able to get the size of an internal frame. I have set the size of the main JFrame to that of Windows by calling Toolkit.getScreenSize(); But i can't seem to find an equivalent for internal frames.
Basically I have two components in the internal frame that I want to have equal width. I was going to find out the size of the internal frame and then half it and applay a horizontal strut to each component.
If there is a better way of doing it i'm open to suggestions but any help at all is much appreciated
Thanks
Dylan
BorderLayout border = new BorderLayout();
content.setLayout(border);
Box left = Box.createVerticalBox();
left.add(Box.createHorizontalStrut(400));
JPanel Create = new JPanel();
Create.setBorder(new TitledBorder (new EtchedBorder(), "Create Database"));
left.add(Create);
Box right = Box.createVerticalBox();
right.add(Box.createHorizontalStrut(400));
JPanel Help = new JPanel();
Help.setBorder(new TitledBorder (new EtchedBorder(), "Help"));
right.add(Help);
content.add(left, BorderLayout.CENTER);
content.add(right, BorderLayout.CENTER);The situation is that I have a class that has about 80
instance fields of basic data types. But it was
getting overly complicated. As a number of these
fields related to year and day data I tried to
re-write with GregorianCalendar instead.
There are in the region of 45,000 instance of my clas
being held in an array, however when I tried to use my
modified class (with the Calendar fields replacing the
basic data types) I kept running into OutOfMemoryError
after about 25,000 instances were created. So I
figured that the GregorianCalendar class must be
eating up my memory. Was intrigued, but couldn't find
out how to calculate the size of my new class.
Hmmm, serialize it you say? Ok, I'll try that.ok don't do that ;)
ummm i was giving advice assuming (incorrectly i turns out) that you were trying to see how much space the serialized object would take up when written to disk or over a network etc.
this does not appear to be your problem.
so here are my new more informed suggestions.
1) if you were going to write out the "data" parts of your object so
it could be re-created what would they be. i'm thinking you could
just boil it all down maybe to a long as in Date.getTime(); then
you could have a long[] array with 45,000 slots. this should take up far less memory than having myObject[] with 45,000 slots. then you
could have one actual object that you insert the data into to play
around with. this may not be the idealists solution but if you have a
lot of objects you may not want to carry around all the excess
stuff.
2) as an aside you say you tried to re-write the GregorianCalendar...
have your tried extending it or extending Calendar. the idea of
extending other non-final classes is you can provide your own
implementation of some things or add totally new methods without having
to re-write an existing class.
just some ideas... -
Picture Editing, urgent :)
Hello
I have the following problem:
I want to put a JPEG Image (400,400) in an other JPEG Image(1024,768).
So I tried that way:
I created a BufferedImage(1024,768,Type_int-_...); then
Graphics g = BufferedImage.getGraphics(); then
drawImage(image,0,0,this);
Then I save the File with the sun package.This works. But there is no picture in the File. There is only a black area(1024,768).
drawLine or drawString works,but I have trouble with the drawImage function
Please help me
Thanks
drawImage doesn�t workdid you copied the content of the small image to the big one?? How did you do this? I remember that there is a function that may enlarge a picture.... Why do you want to put that image in another one?
-
Help with adding a JPanel with multiple images to a JFrame
I'm trying to make a program that reads a "maze" and displays a series of graphics depending on the character readed. The input is made from a file and the output must be placed in a JFrame from another class, but i can't get anything displayed. I have tried a lot of things, and i am a bit lost now, so i would thank any help. The input is something like this:
20
SXXXXXXXXXXXXXXXXXXX
XXXX XXXXXXXXXXX
X XXXXX
X X XX XXXXXXXXXXXX
X XXXXXXXXX XXX
X X XXXXXXXXX XXXXX
X XXXXX XXXXX XXXXX
XX XXXXX XX XXXX
XX XXXXX XXXXXXXX
XX XX XXXX XXXXXXXX
XX XX XXXXXXXX
XX XXX XXXXXXXXXXXXX
X XXXXXXXXXXXXX
XX XXXXXXX !
XX XXXXXX XXXXXXXXX
XX XXXXXXX XXXXXXXXX
XX XXXXXXXX
XX XXXX XXXXXXXXXXXX
XX XXXX XXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
Generated by the Random Maze Generator
And the code for the "translator" is this:
package project;
import java.io.*;
import java.awt.*;
import javax.swing.*;
public class Translator extends JFrame {
private FileReader Reader;
private int size;
Image wall,blank,exit,start,step1,step2;
public Translator(){}
public Translator(File F){
try {
Reader=new FileReader(F);}
catch (IOException e){
JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
try {
size=Reader.read();
System.out.write(size);}
catch (IOException e){
JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
Toolkit theKit=Toolkit.getDefaultToolkit();
wall=theKit.getImage("wall.gif");
blank=theKit.getImage("blanktile.jpg");
exit=theKit.getImage("exit.jpg");
start=theKit.getImage("start.jpg");
step1=theKit.getImage("start.jpg");
step2=theKit.getImage("step1.jpg");
JPanel panel=new JPanel(){
public void paintComponent(Graphics g) {
super.paintComponents(g);
int ch=0;
System.out.print("a1 ");
int currentx=0;
int currenty=0;
try {ch=Reader.read();
System.out.write(ch);}
catch (IOException e){}
System.out.print("b1 ");
while(ch!=-1){
try {ch=Reader.read();}
catch (IOException e){}
System.out.write(ch);
switch (ch){
case '\n':{currenty++;
break;}
case 'X':{System.out.print(">x<");
g.drawImage(wall,(currentx++)*20,currenty*20,this);
break;}
case ' ':{
g.drawImage(blank,(currentx++)*20,currenty*20,this);
break;}
case '!':{
g.drawImage(exit,(currentx++)*20,currenty*20,this);
break;}
case 'S':{
g.drawImage(start,(currentx++)*20,currenty*20,this);
break;}
case '-':{
g.drawImage(step1,(currentx++)*20,currenty*20,this);
break;}
case 'o':{
g.drawImage(step2,(currentx++)*20,currenty*20,this);
break;}
case 'G':{ch=-1;
break;}
}//Swith
}//While
}//paintComponent
};//Panel
panel.setOpaque(true);
setContentPane(panel);
}//Constructor
}//Classforget all those systems.out and that stuff, that is just for the testing
i call it in another class in this way:
public Maze(){
firstFrame=new JFrame("Random Maze Generator");
firstFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
(...)//more constructor code here
Translator T=new Translator(savefile);
firstFrame.add(T);
firstFrame.getContentPane().add(c);
firstFrame.setBounds(d.width/3,d.height/3,d.width/2,d.height/4);
firstFrame.setVisible(true);
c.setSize(d.width/2,d.height/4);
c.show();
}i know it may be a very basic or concept problem, but i can't get it solved
thanks for any helpTry this. It's trivial to convert it to use your images.
If you insist on storing the maze in a file, just read one line at a
time into an ArrayList than convert to an array and pass that to the
MazePanel constructor.
Any questions, just ask.
import java.awt.*;
import javax.swing.*;
public class CFreman1
static class MazePanel
extends JPanel
private final static int DIM= 20;
private String[] mMaze;
public MazePanel(String[] maze) { mMaze= maze; }
public Dimension getPreferredSize() {
return new Dimension(mMaze[0].length()*DIM, mMaze.length*DIM);
public void paint(Graphics g)
g.setColor(Color.BLACK);
g.fillRect(0, 0, getSize().width, getSize().height);
for (int y= 0; y< mMaze.length; y++) {
String row= mMaze[y];
for (int x= 0; x< row.length(); x++) {
Color color= null;
switch (row.charAt(x)) {
case 'S':
color= Color.YELLOW;
break;
case 'X':
color= Color.BLUE;
break;
case '!':
color= Color.RED;
break;
if (color != null) {
g.setColor(color);
g.fillOval(x*DIM, y*DIM, DIM, DIM);
public static void main(String[] argv)
String[] maze= {
"SXXXXXXXXXXXXXXXXXXX",
" XXXX XXXXXXXXXXX",
"X XXXXX",
"X X XX XXXXXXXXXXXX",
"X XXXXXXXXX XXX",
"X X XXXXXXXXX XXXXX",
"X XXXXX XXXXX XXXXX",
"XX XXXXX XX XXXX",
"XX XXXXX XXXXXXXX",
"XX XX XXXX XXXXXXXX",
"XX XX XXXXXXXX",
"XX XXX XXXXXXXXXXXXX",
"X XXXXXXXXXXXXX",
"XX XXXXXXX !",
"XX XXXXXX XXXXXXXXX",
"XX XXXXXXX XXXXXXXXX",
"XX XXXXXXXX",
"XX XXXX XXXXXXXXXXXX",
"XX XXXX XXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXX"
JFrame frame= new JFrame("CFreman1");
frame.getContentPane().add(new MazePanel(maze));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
Maybe you are looking for
-
Error to export to a pdf from an indd document
Here is the error I get : Process: Adobe InDesign CS6 [3599] Path: /Applications/Adobe InDesign CS6/Adobe InDesign CS6.app/Contents/MacOS/Adobe InDesign CS6 Identifier: com.adobe.InDesign Version: 8.0.0.370 (8000) Code Type: X86 (Na
-
I have a new Samsung laptop with Windows 8. I installed iTunes and needed to burn a CD. However, it says the driver is not supported. What do I do?
-
Oracle APP'S Installations Context Value Management Could not started
oracle APP'S Installations Context Value Management Could not started how it is started
-
TRACE FILE의 PERMISSION 조정하는 방법
제품 : ORACLE SERVER 작성날짜 : 1998-04-28 제목 ==== oracle trace file 을 dba group 에 속하지 않는 user 들에게 permission 을 허용하는 방법 문제 ==== Oracle 의 모든 trace file 은 owner 가 oracle user, group 이 dba 이고 640 permission 을 갖습니다. 예를 들면, -rw-r----- oracle dba 따라서, UNIX 에서는 $
-
How to download CC apps once for mass deployment offline? [was: Download]
HI! We are facing a mass installation of Adobe CC for all our students. In order to reduce the bandwidth used we are looking at a way download CC once and distribute it to our students laptops. Where can we download CC and in what way can we deploy i