JPanel help
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.s
If 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.)
Similar Messages
-
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. -
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.
EricMaybe this thread will give you an idea:
http://forum.java.sun.com/thread.jsp?forum=57&thread=492100 -
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! -
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... -
Need help making ball move and bounce off of sides of JPanel
I'm currently working on a program that creates a ball of random color. I'm trying to make the ball move around the JPanel it is contained in and if it hits a wall it should bounce off of it. I have been able to draw the ball and make it fill with a random color. However, I cannot get it to move around and bounce off the walls. Below is the code for the class that creates the ball. Should I possible be using multithreads? As part of the project requirements I will need to utilizes threads and include a runnable. However, I wanted to get it working with one first and than add to it as the final product needs to include new balls being added with each mouse click. Any help would be appreciated.
Thanks
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Ball extends JPanel{
Graphics g;
int rval; // red color value
int gval; // green color value
int bval; // blue color value
private int x = 1;
private int y = 1;
private int dx = 2;
private int dy = 2;
public void paintComponent(Graphics g){
for(int counter = 0; counter < 100; counter++){
// randomly chooses red, green and blue values changing color of ball each time
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);
super.paintComponent(g);
g.drawOval(0,0,30,30); // draws circle
g.setColor(new Color(rval,gval,bval)); // takes random numbers from above and creates RGB color value to be displayed
g.fillOval(x,y,30,30); // adds color to circle
move(g);
} // end paintComponent
public void move(Graphics g){
g.fillOval(x, y, 30, 30);
x += dx;
y += dy;
if(x < 0){
x = 0;
dx = -dx;
if (x + 30 >= 400) {
x = 400 - 30;
dx = -dx;
if (y < 0) {
y = 0;
dy = -dy;
if (y + 30 >= 400) {
y = 400 - 30;
dy = -dy;
g.fillOval(x, y, 30, 30);
g.dispose();
} // end Ball classCreate a bounding box using the size of the panel. Each time you move the ball, check that it's still inside the box. If it isn't, then change it's direction. You know where the ball is, (x, y), so just compare those values to the boundary values.
-
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);
} -
URGENT! Need help with scrolling on a JPanel!
Hello Guys! I guess there has been many postings about this subject in the forum, but the postings I found there.... still couldn't solve my problem...
So, straight to the problem:
I am drawing some primitive graphic on a JPanel. This JPanel is then placed in a JScrollPane. When running the code, the scrollbars are showing and the graphic is painted nicely. But when I try to scroll to see the parts of the graphics not visible in the current scrollbarview, nothing else than some flickering is happening... No movement what so ever...
What on earth must I do to activate the scroll functionality on my JPanel??? Please Help!
And yes, I have tried implementing the 'Scrollable' interface... But it did not make any difference...
Code snippets:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.util.*;
public class FilterComp extends JPanel {//implements Scrollable {
protected DefaultMutableTreeNode root;
protected Image buffer;
protected int lastW = 0;
protected int origoX = 0;
protected final StringBuffer sb = new StringBuffer();
// protected int maxUnitIncrement = 1;
protected JScrollPane scrollpane = new JScrollPane();
* Constructor for the FilterComp object
*@param scrollpane Description of the Parameter
public FilterComp(JScrollPane scrollpane) {
super();
// setPreferredSize(new Dimension(1000, 500));
this.setBackground(Color.magenta);
// setOpaque(false);
setLayout(
new BorderLayout() {
public Dimension preferredLayoutSize(Container cont) {
return new Dimension(1000, 600);
this.scrollpane = scrollpane;
scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollpane.setPreferredSize( new Dimension( 500, 500 ) );
scrollpane.getViewport().add( this, null );
// scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
repaint();
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getSize().width;
if (w != lastW) {
buffer = null;
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (root != null) {
int h = getHeight(root);
if (buffer == null) {
buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g3 = (Graphics2D) buffer.getGraphics();
g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g3.setColor(Color.black);
g3.setStroke(new BasicStroke(2));
paint(g3, (w / 2) + origoX, 10, w / 2, root);
lastW = w;
AffineTransform old = g2.getTransform();
AffineTransform trans = new AffineTransform();
trans.translate((w / 2) + origoX, (getHeight() - (h * 40)) / 2);
g2.setTransform(trans);
g2.drawImage(buffer, (-w / 2) + origoX, 0, null);
g2.setTransform(old);
updateUI();
* Description of the Method
*@param g Description of the Parameter
public void update(Graphics g) {
// Call paint to reduce flickering
paint(g);
* Description of the Method
*@param g2 Description of the Parameter
*@param x Description of the Parameter
*@param y Description of the Parameter
*@param w Description of the Parameter
*@param node Description of the Parameter
private void paint(Graphics2D g2, int x, int y, int w, DefaultMutableTreeNode node) {
if (node.getChildCount() == 2) {
DefaultMutableTreeNode c1 = (DefaultMutableTreeNode) node.getChildAt(0);
DefaultMutableTreeNode c2 = (DefaultMutableTreeNode) node.getChildAt(1);
if (c1.getChildCount() == 0 && c2.getChildCount() == 0) {
String s = c1.getUserObject().toString() + " " + node.getUserObject() + " " + c2.getUserObject();
paint(g2, x, y, s);
} else {
g2.drawLine(x - (w / 2), y, x + (w / 2), y);
Font f = g2.getFont();
g2.setFont(new Font(f.getName(), Font.BOLD | Font.ITALIC, f.getSize() + 2));
paint(g2, x, y, node.getUserObject().toString());
g2.setFont(f);
g2.drawLine(x - (w / 2), y, x - (w / 2), y + 40);
g2.drawLine(x + (w / 2), y, x + (w / 2), y + 40);
paint(g2, x - (w / 2), y + 40, w / 2, c1);
paint(g2, x + (w / 2), y + 40, w / 2, c2);
} else if (node.getChildCount() == 0) {
paint(g2, x, y, node.getUserObject().toString());
* Description of the Method
*@param g2 Description of the Parameter
*@param x Description of the Parameter
*@param y Description of the Parameter
*@param s Description of the Parameter
private void paint(Graphics2D g2, int x, int y, String s) {
y += 10;
StringTokenizer st = new StringTokenizer(s, "\\", false);
if (s.indexOf("'") != -1 && st.countTokens() > 1) {
int sh = g2.getFontMetrics().getHeight();
while (st.hasMoreTokens()) {
String t = st.nextToken();
if (st.hasMoreTokens()) {
t += "/";
int sw = g2.getFontMetrics().stringWidth(t);
g2.drawString(t, x - (sw / 2), y);
y += sh;
} else {
int sw = g2.getFontMetrics().stringWidth(s);
g2.drawString(s, x - (sw / 2), y);
* Sets the root attribute of the FilterComp object
*@param root The new root value
public void setRoot(DefaultMutableTreeNode root) {
this.root = root;
buffer = null;
* Gets the root attribute of the FilterComp object
*@return The root value
public DefaultMutableTreeNode getRoot() {
return root;
* Gets the height attribute of the FilterComp object
*@param t Description of the Parameter
*@return The height value
private int getHeight(TreeNode t) {
int h = 1;
int c = t.getChildCount();
if (c > 0) {
if (c > 1) {
h += Math.max(getHeight(t.getChildAt(0)), getHeight(t.getChildAt(1)));
} else {
h += getHeight(t.getChildAt(0));
return h;
* Sets the x attribute of the FilterComp object
*@param x The new x value
public void setX(int x) {
origoX = x;
* Gets the x attribute of the FilterComp object
*@return The x value
public int getX() {
return origoX;
* Gets the preferredScrollableViewportSize attribute of the FilterComp
* object
*@return The preferredScrollableViewportSize value
// public Dimension getPreferredScrollableViewportSize() {
// return getPreferredSize();
* Gets the scrollableBlockIncrement attribute of the FilterComp object
*@param r Description of the Parameter
*@param orientation Description of the Parameter
*@param direction Description of the Parameter
*@return The scrollableBlockIncrement value
// public int getScrollableBlockIncrement(Rectangle r, int orientation, int direction) {
// return 10;
* Gets the scrollableTracksViewportHeight attribute of the FilterComp object
*@return The scrollableTracksViewportHeight value
// public boolean getScrollableTracksViewportHeight() {
// return false;
* Gets the scrollableTracksViewportWidth attribute of the FilterComp object
*@return The scrollableTracksViewportWidth value
// public boolean getScrollableTracksViewportWidth() {
// return false;
* Gets the scrollableUnitIncrement attribute of the FilterComp object
*@param r Description of the Parameter
*@param orientation Description of the Parameter
*@param direction Description of the Parameter
*@return The scrollableUnitIncrement value
// public int getScrollableUnitIncrement(Rectangle r, int orientation, int direction) {
// return 10;
}The Scrollable interface should be implemented by a JPanel set as the JScrollPane's viewport or scrolling may not function. Although it is said to be only necessary for tables, lists, and trees, without it I have never had success with images. Even the Java Swing Tutorial on scrolling images with JScrollPane uses the Scrollable interface.
I donot know what you are doing wrong here, but I use JScrollPane with a JPanel implementing Scrollable interface and it works very well scrolling images drawn into the JPanel.
You can scroll using other components, such as the JScrollBar or even by using a MouseListener/MouseMotionListener combination, but this is all done behind the scenes with the use of JScrollPane/Scrollable combination.
You could try this approach using an ImageIcon within a JLabel:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
public class Test extends JFrame {
BufferedImage bi;
Graphics2D g_bi;
public Test() {
super("Scroll Test");
makeImage();
Container contentPane = getContentPane();
MyView view = new MyView(new ImageIcon(bi));
JScrollPane sp = new JScrollPane(view);
contentPane.add(sp);
setSize(200, 200);
setVisible(true);
private void makeImage() {
bi = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB);
g_bi = bi.createGraphics();
g_bi.setColor(Color.white);
g_bi.fillRect(0,0,320,240);
g_bi.setColor(Color.black);
g_bi.drawLine(0,0,320,240);
public static void main(String args[]) {
Test test = new Test();
class MyView extends JLabel {
ImageIcon icon;
public MyView(ImageIcon ii) {
super(ii);
icon = ii;
public void paintComponent(Graphics g) {
g.drawImage(icon.getImage(),0,0,this);
}Robert Templeton -
Help needed in printing a JPanel in Swing..
Hi,
I'm working on a Printing task using Swing. I'm trying to print a JPanel. All i'm doing is by creating a "java.awt.print.Book" object and adding (append) some content to it. And these pages are in the form of JPanel. I've created a separate class for this which extends the JPanel. I've overridden the print() method. I have tried many things that i found on the web and it simply doesn't work. At the end it just renders an empty page, when i try to print it. I'm just pasting a sample code of the my custom JPanel's print method here:
public int print(Graphics g, PageFormat pageformat, int pagenb)
throws PrinterException {
//if(pagenb != this.pagenb) return Printable.NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setClip(0, 0, this.getWidth(), this.getHeight());
g2d.setColor(Color.BLACK);
//disable double buffering before printing
RepaintManager rp = RepaintManager.currentManager(this);
rp.setDoubleBufferingEnabled(false);
this.paint(g2d);
rp.setDoubleBufferingEnabled(true);
return Printable.PAGE_EXISTS;
}Please help me where i'm going wrong. I'm just trying to print the JPanel with their contents.
Thanks in advance.Hi,
Try this
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.AbstractAction;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class PrintablePanel extends JPanel implements Printable {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final PrintablePanel target = new PrintablePanel(
new BorderLayout());
target.add(new JColorChooser());
frame.add(target, BorderLayout.CENTER);
JToolBar toolBar = new JToolBar();
frame.add(toolBar, BorderLayout.PAGE_START);
toolBar.add(new AbstractAction("Print") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent event) {
PrinterJob printerJob = PrinterJob.getPrinterJob();
printerJob.setPrintable(target);
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
frame.pack();
frame.setVisible(true);
public PrintablePanel() {
super();
public PrintablePanel(LayoutManager layout) {
super(layout);
@Override
public int print(Graphics g, PageFormat format, int page)
throws PrinterException {
if (page == 0) {
Graphics2D g2 = (Graphics2D) g;
g2.translate(format.getImageableX(), format.getImageableY());
print(g2);
g2.translate(-format.getImageableX(), -format.getImageableY());
return Printable.PAGE_EXISTS;
} else {
return Printable.NO_SUCH_PAGE;
}Piet
Edit: Sorry. Just now I see that you want to use the Swing print mechanism. But I guess the implementation of the Printable interface remains the same.
Edited by: pietblok on 14-nov-2008 17:23
Maybe you are looking for
-
ERROR in this BAPI_CUSTOMER_GETLIST
Hello, Please help me ,I am getting error while executing this report. I want to Execute a BAPI . BAPI_CUSTOMER_GETLIST. INPUT : I,EQ,0000002156. where it went wrong REPORT ZRBAPI_CUSTOMER_GETLIST. DATA : IDRANGE LIKE BAPICUSTOMER_IDRANGE
-
Reports Queue Manager - Status Information
Hi there, I would like to know if you can get status information from the reports queue manager. For your information: We are still using Forms/Reports 6i but looking forward to use 10g via web frontend. 1.) In detail I would like to control the 'num
-
How can I get LR2 to "See" keywords previously entered in Bridge?
Few months ago I started using Lightroom 2. It works well for me but there's one aspect which doesn't and I can find a workaround. Any suggestions, please. I had already keyworded my files in PS CS3 Bridge and imported my keyword hierarchy into LR2
-
Need a report to see the inbound deliveries on STO
Hello, I would like to run a report which will give me the list of open STOs which i can filter by material, supply plant, receiving plant or date. Is there a standard report available for this? Thanks Bala
-
InDesign search multiple formats at once in find and replace
I am pretty new to InDesign and InDesign forums. I am having problems figuring out how to do this task. I am using CS6, and I have a rather large document that has a glitch in the formatting. The Latin names for species are in italics, but for so