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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Javaclassnotfound javax.swing.JPanel in a applet

    Hi,
    I have a applet which use a class which have the code
    import javax.swing.JPanel;
    public class WebPanel extends JPanel implements Runnable{
    Applet parent;
    i compile it with jdk1.2.2
    my problem is that when i try to run the applet on a Internet Explorer navigator it give me a
    javaclassnotfound javax.swing.JPanel
    problem.
    Javax.swing.JPanel is�nt in IExploter?
    Should i put the javax.swing.Jpanel class in the jar fije?
    Where i can find it?
    Thanks in advance.

    forgot to mention this...get the plug in here:
    http://java.sun.com/products/plugin/
    read the intstructions, u might have to do some 'applet conversion' ....u'll know what I mean when u install the plugin
    good luck

  • Accessing javax.swing.JPanel from outside the EDT

    Hi everybody!
    I am not new to Java but to Swing.
    Please consider the following:
    public class MyPanel extends JPanel
         private int number = 0;
         private Object object = null;
         public int getNumber()
              return number;
         public void setNumber(int aNumber)
              number = aNumber;
         public Object getObject()
              return object;
         public void setObject(Object aObject)
              object = aObject;
    Question:
    Is it save to call the getters and setters defined above from a Thread other than the Event Dispatching Thread.
    From my point of view and my understanding of Swing this should be save as the getters and setters do not touch anything other than the methods and instances defined within the object layer of MyPanel.
    Please help :-)

    jboeing wrote:
    I might be wrong, but I think it's safe to touch the non-Swing methods in a subclass from other threads. The main concern in accessing Swing off the EDT is that you can concurrently modify parts of code, but since the EDT does not touch your getters and setters, at least it won't make deadlocks. Perfect, exactly what I would suggest. I couldn't have put it better.
    The only oddities may occur if the member variable you set is used in logic for an overriden method (like paintComponent), but I don't think this will be too problematic in most cases.See what you mean so: What about synchronizing the getters and setters. Then only the scheduler would block the EDT as long as another Thread was touching the members. As no wait() and notify() calls arise this should not result in any deadlocks. The worst thing I could think of is that the responsiveness of the user interface may degrade if the EDT had to wait for a while as to many Threads were already waiting for synchronized accesss.
    >
    Edit:
    Oh, and in the future, use the "*Code Formatting Tags*", see http://forum.java.sun.com/help.jspa?sec=formatting
    Edited by: jboeing on Nov 13, 2007 1:14 PM
    public class Apology{
        public static void main(String[] args){
            System.out.println("Thank you for your kind advice :-)");
            System.out.println("but please don't ask me why this is quoted style");
    }Edited by: tog on Nov 14, 2007 6:08 PM

  • I need to control the position and size of each java swing component, help!

    I setup a GUI which include 2 panels, each includes some components, I want to setup the size and position of these components, I use setBonus or setSize, but doesn't work at all. please help me to fix it. thanks
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.FlowLayout;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.event.*;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.JPanel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.DefaultListModel;
    public class weather extends JFrame {
    private String[] entries={"1","22","333","4444"} ;
    private JTextField country;
    private JList jl;
    private JTextField latitude;
    private JTextField currentTime;
    private JTextField wind;
    private JTextField visibilityField;
    private JTextField skycondition;
    private JTextField dewpoint;
    private JTextField relativehumidity;
    private JTextField presure;
    private JButton search;
    private DefaultListModel listModel;
    private JPanel p1,p2;
    public weather() {
         setUpUIComponent();
    setTitle("Weather Report ");
    setSize(600, 400);
    setResizable(false);
    setVisible(true);
    private void setUpUIComponent(){
         p1 = new JPanel();
    p2 = new JPanel();
         country=new JTextField(10);
         latitude=new JTextField(12);
    currentTime=new JTextField(12);
    wind=new JTextField(12);
    visibilityField=new JTextField(12);
    skycondition=new JTextField(12);
    dewpoint=new JTextField(12);
    relativehumidity=new JTextField(12);
    presure=new JTextField(12);
    search=new JButton("SEARCH");
    listModel = new DefaultListModel();
    jl = new JList(listModel);
    // jl=new JList(entries);
    JScrollPane jsp=new JScrollPane(jl);
    jl.setVisibleRowCount(8);
    jsp.setBounds(120,120,80,80);
    p1.add(country);
    p1.add(search);
    p1.add(jsp);
    p2.add(new JLabel("latitude"));
    p2.add(latitude);
    p2.add(new JLabel("time"));
    p2.add(currentTime);
    p2.add(new JLabel("wind"));
    p2.add(wind);
    p2.add(new JLabel("visibility"));
    p2.add(visibilityField);
    p2.add(new JLabel("skycondition"));
    p2.add(skycondition);
    p2.add(new JLabel("dewpoint"));
    p2.add(dewpoint);
    p2.add(new JLabel("relativehumidity"));
    p2.add(relativehumidity);
    p2.add(new JLabel("presure"));
    p2.add(presure);
    this.getContentPane().setLayout(new FlowLayout());
    this.setLayout(new GridLayout(1,2));
    p2.setLayout(new GridLayout(8, 2));
    this.add(p1);
    this.add(p2);
    public static void main(String[] args) {
    JFrame frame = new weather();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    [http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]
    db

  • 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.)

  • Javax.swing.KeyStroke

    When i use Swing with PJ i get some errors about javax.swing.KeyStroke:
    java.lang.NoSuchFieldException
    at java.lang.Class.getField()
    at javax.swing.KeyStroke.getKeyStroke()
    at javax.swing.plaf.metal.MetalLookAndFeel.initComponentDefaults()
    at javax.swing.plaf.basic.BasicLookAndFeel.getDefaults()
    at javax.swing.plaf.metal.MetalLookAndFeel.getDefaults()
    at javax.swing.UIManager.setLookAndFeel()
    at javax.swing.UIManager.setLookAndFeel()
    at javax.swing.UIManager.initializeDefaultLAF()
    at javax.swing.UIManager.initialize()
    at javax.swing.UIManager.maybeInitialize()
    at javax.swing.UIManager.getUI()
    at javax.swing.JPanel.updateUI()
    at javax.swing.JPanel.<init>()
    at javax.swing.JPanel.<init>()
    at javax.swing.JRootPane.createGlassPane()
    at javax.swing.JRootPane.<init>()
    at javax.swing.JFrame.createRootPane()
    at javax.swing.JFrame.frameInit()
    at javax.swing.JFrame.<init>()
    java.lang.Error: Unrecognized keycode name: VK_KP_LEFT
    at javax.swing.KeyStroke.getKeyStroke()
    at javax.swing.plaf.metal.MetalLookAndFeel.initComponentDefaults()
    at javax.swing.plaf.basic.BasicLookAndFeel.getDefaults()
    at javax.swing.plaf.metal.MetalLookAndFeel.getDefaults()
    at javax.swing.UIManager.setLookAndFeel()
    at javax.swing.UIManager.setLookAndFeel()
    at javax.swing.UIManager.initializeDefaultLAF()
    at javax.swing.UIManager.initialize()
    at javax.swing.UIManager.maybeInitialize()
    at javax.swing.UIManager.getUI()
    at javax.swing.JPanel.updateUI()
    at javax.swing.JPanel.<init>()
    at javax.swing.JPanel.<init>()
    at javax.swing.JRootPane.createGlassPane()
    at javax.swing.JRootPane.<init>()
    at javax.swing.JFrame.createRootPane()
    at javax.swing.JFrame.frameInit()
    at javax.swing.JFrame.<init>()
    Could someone help me?

    Refer to the bug database (bugid = 4309057)
    http://developer.java.sun.com/developer/bugParade/bugs/4309057.html
    Here the workaround:
    Fix the problem yourself by changing SwingUtilites to test for "Class.getPackage" which is 1.2 specific and has not been introduced to pJava:
    Method m = Class.class.getMethod("getPackage", null);Re-Jar the swingclasses and enjoy your Swing application running on PersonalJava....
    Herbie

  • Cannot Import javax.swing.JOptionPane   Please HELP!!!

    import javax.swing.JOptionPane;
    this line of code returns the error:
    C:\Java Files\BankAccount\BankAccount_Test.java:1: Class javax.swing.JOptionPane not found in import.
    import javax.swing.JOptionPane;
    ^
    1 error
    Process completed.
    Please help, I don't know what the problem could be....

    Swing was not part of any JDK's earlier than 1.2. Swing (or anything with a J in front of it, ie. JFrame, JOptionPane, etc...) was probably the most dramatic (if not largest) modification/addition to the Java language, that's why versions later than, and including, 1.2 are known as "Java 2".

  • Help..Javax.swing

    I need to find where SPECIFIC I can download this package.I'm trying to import this for a combo box....
    import javac.swing.*;
    and I can't find the right package that contains it. Any information would be appreciated. Thanks!!

    it should be:
    import javax.swing.*;

  • [HELP! ] why my program thows a javax.swing.text.ChangedCharSetException?

    there's the source:
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.border.*;
    class HTMLMagician extends JFrame
         protected static final String APP_NAME="HTML Magician V1.0 Produced By V Studio";
         protected JTextPane hm_textPane;
         protected StyleSheet hm_styleSheet;
         protected HTMLEditorKit html_kit;
         protected HTMLDocument html_document;
         protected JMenuBar hm_menuBar;
         protected JToolBar hm_toolBar;
         protected JFileChooser hm_fileChooser;
         protected File current_file;
         protected boolean text_changed=false;
         public HTMLMagician()
              super(APP_NAME);
              setSize(800,600);
              getContentPane().setLayout(new BorderLayout());
              produceMenuBar();
              hm_textPane=new JTextPane();
              html_kit=new HTMLEditorKit();
              hm_textPane.setEditorKit(html_kit);
              JScrollPane textPane_scrollPane=new JScrollPane();
              textPane_scrollPane.getViewport().add(hm_textPane);
              getContentPane().add(textPane_scrollPane,BorderLayout.CENTER);
              hm_fileChooser=new JFileChooser();
              javax.swing.filechooser.FileFilter hm_filter=new javax.swing.filechooser.FileFilter()
                   public boolean accept(File pathname)
                        if(pathname.isDirectory())
                             return true;
                        String ext_name=pathname.getName().toLowerCase();
                        if(ext_name.endsWith(".htm"))
                             return true;
                        if(ext_name.endsWith(".html"))
                             return true;
                        if(ext_name.endsWith(".asp"))
                             return true;
                        if(ext_name.endsWith(".jsp"))
                             return true;
                        if(ext_name.endsWith(".css"))
                             return true;
                        if(ext_name.endsWith(".php"))
                             return true;
                        if(ext_name.endsWith(".aspx"))
                             return true;
                        if(ext_name.endsWith(".xml"))
                             return true;
                        if(ext_name.endsWith(".txt"))
                             return true;
                        return false;
                   public String getDescription()
                        return "HTML files(*.htm,*.html,*.asp,*.jsp,*.css,*.php,*.aspx,*.xml)";
              hm_fileChooser.setAcceptAllFileFilterUsed(false);
              hm_fileChooser.setFileFilter(hm_filter);
              try
                   File dir=(new File(".")).getCanonicalFile();
                   hm_fileChooser.setCurrentDirectory(dir);
              }catch(IOException ex)
                   showError(ex,"Error openning current directory");
              newDocument();
              WindowListener action_winClose=new WindowAdapter()
                   public void windowClosing(WindowEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              addWindowListener(action_winClose);
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              setVisible(true);
         protected void produceMenuBar()
              hm_menuBar=new JMenuBar();
              hm_toolBar=new JToolBar();
              JMenu menu_file=new JMenu("File");
              menu_file.setMnemonic('f');
              ImageIcon icon_new=new ImageIcon("imgs/file.gif");
              Action action_new=new AbstractAction("New",icon_new)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        newDocument();
              JMenuItem item_new=new JMenuItem(action_new);
              item_new.setMnemonic('n');
              item_new.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));
              menu_file.add(item_new);
              JButton button_new=hm_toolBar.add(action_new);
              ImageIcon icon_open=new ImageIcon("imgs/folder_open.gif");
              Action action_open=new AbstractAction("Open...",icon_open)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        openDocument();
              JMenuItem item_open=new JMenuItem(action_open);
              item_open.setMnemonic('o');
              item_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
              menu_file.add(item_open);
              JButton button_open=hm_toolBar.add(action_open);
              ImageIcon icon_save=new ImageIcon("imgs/floppy.gif");
              Action action_save=new AbstractAction("Save",icon_save)
                   public void actionPerformed(ActionEvent evt)
                        saveAs(false);
              JMenuItem item_save=new JMenuItem(action_save);
              item_save.setMnemonic('s');
              item_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
              menu_file.add(item_save);
              JButton button_save=hm_toolBar.add(action_save);
              Action action_saveAs=new AbstractAction("Save As...")
                   public void actionPerformed(ActionEvent evt)
                        saveAs(true);
              JMenuItem item_saveAs=new JMenuItem(action_saveAs);
              item_saveAs.setMnemonic('a');
              item_saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
              menu_file.add(item_saveAs);
              menu_file.addSeparator();
              Action action_close=new AbstractAction("Quit")
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              JMenuItem item_exit=new JMenuItem(action_close);
              item_exit.setMnemonic('q');
              item_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));
              menu_file.add(item_exit);
              hm_menuBar.add(menu_file);
              setJMenuBar(hm_menuBar);
              getContentPane().add(hm_toolBar,BorderLayout.NORTH);
         protected String getDocumentName()
              return current_file==null ? "Untitled" : current_file.getName();
         protected void newDocument()
              html_document=(HTMLDocument)html_kit.createDefaultDocument();
              hm_styleSheet=html_document.getStyleSheet();
              hm_textPane.setDocument(html_document);
              current_file=null;
              setTitle(getDocumentName()+" - "+APP_NAME);
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected void openDocument()
              if(hm_fileChooser.showOpenDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                   return;
              File f=hm_fileChooser.getSelectedFile();
              if(f==null || !f.isFile())
                   return;
              current_file=f;
              setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   InputStream in=new FileInputStream(current_file);
                   html_document=(HTMLDocument)html_kit.createDefaultDocument();
                   html_kit.read(in,html_document,0);
                   hm_styleSheet=html_document.getStyleSheet();
                   hm_textPane.setDocument(html_document);
                   in.close();
              }catch(Exception ex)
                   showError(ex,"Error openning file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected boolean saveAs(boolean as)
              if(!as && !text_changed)
                   return true;
              if(as || current_file==null)
                   if(hm_fileChooser.showSaveDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                        return false;
                   File f=hm_fileChooser.getSelectedFile();
                   if(f==null || !f.isFile())
                        return false;
                   current_file=f;
                   setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   OutputStream out=new FileOutputStream(current_file);
                   html_kit.write(out,html_document,0,html_document.getLength());
                   out.close();
              }catch(Exception ex)
                   showError(ex,"Error saving file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              return true;
         protected boolean promptToSave()
              if(!text_changed)
                   return true;
              int result=JOptionPane.showConfirmDialog(this,"Save change to "+getDocumentName(),APP_NAME,JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
              switch(result)
                   case JOptionPane.YES_OPTION:
                        if(!saveAs(false))
                             return false;
                        return true;
                   case JOptionPane.NO_OPTION:
                        return true;
                   case JOptionPane.CANCEL_OPTION:
                        return false;
              return true;
         protected void showError(Exception ex,String message)
              ex.printStackTrace();
              JOptionPane.showMessageDialog(this,message,APP_NAME,JOptionPane.WARNING_MESSAGE);
         public static void main(String[] args)
              new HTMLMagician();
         class action_textChanged implements DocumentListener
              public void changedUpdate(DocumentEvent evt)
                   text_changed=true;
              public void insertUpdate(DocumentEvent evt)
                   text_changed=true;
              public void removeUpdate(DocumentEvent evt)
                   text_changed=true;
    when i open a .html file,the command output :
    javax.swing.text.ChangedCharSetException
         at javax.swing.text.html.parser.DocumentParser.handleEmptyTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.startTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseContent(Unknown Source)
         at javax.swing.text.html.parser.Parser.parse(Unknown Source)
         at javax.swing.text.html.parser.DocumentParser.parse(Unknown Source)
         at javax.swing.text.html.parser.ParserDelegator.parse(Unknown Source)
         at javax.swing.text.html.HTMLEditorKit.read(Unknown Source)
         at javax.swing.text.DefaultEditorKit.read(Unknown Source)
         at HTMLMagician.openDocument(HTMLMagician.java:222)
         at HTMLMagician$4.actionPerformed(HTMLMagician.java:128)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    why? what's wrong? thanks

    The DocumentParser seems to throw a ChangedCharSetException if it finds a "http-equiv" meta tag for "content-type" or "charset" and if the parser's "ignoreCharSet" property is set to false on creation.

  • Newbie compiler help using javax.swing class

    current java ver java version "1.5.0_02"
    error msg
    [error]
    C:\Documents and Settings\Neil\Desktop\Java>javac neiltest2.java
    neiltest2.java:12: package javax does not exist
    import javax.swing;
    ^
    neiltest2.java:28: cannot resolve symbol
    symbol : variable JOptionPane
    location: class neiltest2
    JOptionPane.showMessageDialog(null, "The total is " + intSum);
    ^
    2 errors
    [error]
    * neiltest2.java
    * Created on 02 June 2005, 19:02
    * @author  Neil
    * @version
    import javax.swing;
    public class neiltest2 {
        /** Creates new neiltest2 */
        public neiltest2() {
        * @param args the command line arguments
        public static void main (String args[]) {
            int intSum;
            intSum = 14+35;
            JOptionPane.showMessageDialog(null, "The total is " + intSum);
            System.exit(0);
    }TIA
    Neil

    Use either
    import javax.swing.JOptionPanel;
    or
    import javax.swing.*;
    � {�                                                                                                                                                                               

  • Help ! inaccurate time recorded using javax.swing.timer

    Hi All,
    I am currently trying to write a stopwatch for timing application events such as loggon, save, exit ... for this I have created a simple Swing GUI and I am using the javax.swing.timer and updating a the time on a Jlabel. The trouble that I am having is that the time is out by up to 20 seconds over a 10 mins. Is there any way to get a more accruate time ?? The code that I am using is attached below.
    private Timer run = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    timeTaken.setText("<html><font size = 5><b>" + (df.format(timeHours)) + ":" + (df.format(timeMins)) + ":"
    + (df.format(timeSeconds++)) + "</b></font><html>");
    receordedTimeValue = ((df.format(timeHours)) + ":" + (df.format(timeMins)) + ":"
    + (df.format(timeSeconds)));
    if (timeSeconds == 60) {
    timeMins++;
    timeSeconds = 0;
    if (timeMins == 60) {
    timeHours++;
    timeMins = 0;

    To get more accurate time you should use the System.currentTimeMillis() method.
    Try this code :
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CountUpLabel extends JLabel{
         javax.swing.Timer timer;
         long startTime, count;
         public CountUpLabel() {
              super(" ", SwingConstants.CENTER);
              timer = new javax.swing.Timer(500, new ActionListener() { // less than or equal to 1000 (1000, 500, 250,200,100) 
                   public void actionPerformed(ActionEvent event) {
                        if (startTime == -1) {          
                             count = 0;               
                             startTime = System.currentTimeMillis();
                        else {
                             count = System.currentTimeMillis()-startTime;
                        setText(getStringTime(count));
         private static final String getStringTime(long millis) {
              int seconds = (int)(millis/1000);
              int minutes = (int)(seconds/60);
              int hours = (int)(minutes/60);
              minutes -= hours*60;
              seconds -= (hours*3600)+(minutes*60);
              return(((hours<10)?"0"+hours:""+hours)+":"+((minutes<10)?"0"+minutes:""+minutes)+":"+((seconds<10)?"0"+seconds:""+seconds));
         public void start() {
              startTime = -1;
              timer.setInitialDelay(0);
              timer.start();
         public long stop() {
              timer.stop();
              return(count);
         public static void main(String[] args) {
              JFrame frame = new JFrame("Countdown");
              CountUpLabel countUp = new CountUpLabel();
              frame.getContentPane().add(countUp, BorderLayout.CENTER);
              frame.setBounds(200,200,200,100);
              frame.setVisible(true);
              countUp.start();
    Denis

  • Variable textArea not found in class javax.swing.JFrame...

    Making progress on this issue -- but still stuck. Again trying to get the text from a JTextArea on exit:
            frame.addWindowListener
           (new WindowAdapter() {
             public void windowClosing(WindowEvent e)
                System.out.println("Why me???" + frame.textArea.getText());
            });User MARSIAN helped me understand the scope fo the variables and now that has been fixed. Unfortunately I cannot access my variable textArea in the above code. If get this error:
    Error: variable textArea not found in class javax.swing.JFrame
    What am I doing wrong?
    import  java.net.*;
    import  javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import FragImpl.*;
    public class Framework extends WindowAdapter {
        public int numWindows = 0;
        private Point lastLocation = null;
        private int maxX = 500;
        private int maxY = 500;
        JFrame frame;
        public Framework() {
            newFrag();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            maxX = screenSize.width - 50;
            maxY = screenSize.height - 50;
            makeNewWindow();
        public void makeNewWindow() {
            frame = new MyFrame(this);  //*
            numWindows++;
            System.out.println("Number of windows: " + numWindows);
            if (lastLocation != null) {
                //Move the window over and down 40 pixels.
                lastLocation.translate(40, 40);
                if ((lastLocation.x > maxX) || (lastLocation.y > maxY)) {
                    lastLocation.setLocation(0, 0);
                frame.setLocation(lastLocation);
            } else {
                lastLocation = frame.getLocation();
            System.out.println("Frame location: " + lastLocation);
            frame.setVisible(true);
            frame.addWindowListener
           (new WindowAdapter() {
             public void windowClosing(WindowEvent e)
                System.out.println("Why me???" + frame.textArea.getText());
        //This method must be evoked from the event-dispatching thread.
        public void quit(JFrame frame) {
            if (quitConfirmed(frame)) {
                System.exit(0);
            System.out.println("Quit operation not confirmed; staying alive.");
        private boolean quitConfirmed(JFrame frame) {
            String s1 = "Quit";
            String s2 = "Cancel";
            Object[] options = {s1, s2};
            int n = JOptionPane.showOptionDialog(frame,
                    "Windows are still open.\nDo you really want to quit?",
                    "Quit Confirmation",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    s1);
            if (n == JOptionPane.YES_OPTION) {
                return true;
            } else {
                return false;
         private void newFrag()
              Frag frag = new FragImpl();
        public static void main(String[] args) {
            Framework framework = new Framework();
    class MyFrame extends JFrame {
        protected Dimension defaultSize = new Dimension(200, 200);
        protected Framework framework = null;
        private Color color = Color.yellow;
        private Container c;
        JTextArea textArea;
        public MyFrame(Framework controller) {
            super("New Frame");
            framework = controller;
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setSize(defaultSize);
            //Create a text area.
            textArea = new JTextArea(
                    "This is an editable JTextArea " +
                    "that has been initialized with the setText method. " +
                    "A text area is a \"plain\" text component, " +
                    "which means that although it can display text " +
                    "in any font, all of the text is in the same font."
            textArea.setFont(new Font("Serif", Font.ITALIC, 16));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            textArea.setBackground ( Color.yellow );
            JScrollPane areaScrollPane = new JScrollPane(textArea);
            //Create the status area.
            JPanel statusPane = new JPanel(new GridLayout(1, 1));
            ImageIcon icoOpen = null;
            URL url = null;
            try
                icoOpen = new ImageIcon("post_it0a.gif"); //("doc04d.gif");
            catch(Exception ex)
                ex.printStackTrace();
                System.exit(1);
            setIconImage(icoOpen.getImage());
            c = getContentPane();
            c.setBackground ( Color.yellow );
            c.add ( areaScrollPane, BorderLayout.CENTER )  ;
            c.add ( statusPane, BorderLayout.SOUTH );
            c.repaint ();
    }

    Yeah!!! It works. Turned out to be a combination of DrKlap's and Martisan's suggestions -- had to change var frame's declaration from JFrame to MyFrame:
        MyFrame frame;Next, created the external class -- but again changed JFrame references to MyFrame:
    public class ShowOnExit extends WindowAdapter {
    //   JFrame aFrame;
       MyFrame aFrame;
       public ShowOnExit(MyFrame f) {
          aFrame = f;
       public void windowClosing(WindowEvent e)
          System.out.println("Why me???" + aFrame.textArea.getText()); // aFrame here not frame !!!
    }This worked. So looks like even though the original code added a WindowListener to 'frame', the listener didn't couldn't access frame's methods unless it was explicitly passed in as a parameter. Let me know if that's wrong.
    Thanks again, all.

  • Swing ActionListener help?

    Hi there,
    I'm trying to get to grips with Swing and I'm reasonably comfortable with laying out the GUI now. However, I'm still trying to get to grips with ActionListeners. As I understand it, you can have any old class as an ActionListener as long as it implements the ActionListener interface.....then you can just add this ActionListener to a component using .addActionListener().
    Couple of questions though....
    1. Is it generally bad design to just have a component call <whatever>.addActionListener(this) and then just implement the actionPerformed() method within the same class?
    2. Do you have to define a seperate ActionListener class for each type of component, or can you use one ActionListener for, say, one whole GUI screen? How do you usually organise these things?
    3. Anyone point me towards some decent tutorials on Java Swing event-handling?....preferably not the Sun ones, although if they are regarded as the best, I'll take 'em. :)
    Thanks for your time.

    URgent help need.
    i need to link the page together : by clicking the button on the index page.
    it will show the revelant class file. I have try my ationPerformed method to the actionlistener, it cannot work.
    Thanks in advance.
    // class mtab
    // the tab menu where it display the gui
    import javax.swing.*;
    import java.awt.*;
    public class mtab {
    private static final int frame_height = 480;
    private static final int frame_width = 680;
    public static void main (String [] args){
    JFrame frame = new JFrame ("Mrt Timing System");
    frame.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE);
    frame.setSize(frame_width,frame_height);
    JTabbedPane tp = new JTabbedPane ();
    tp.addTab("Mrt Timing System", new sample());
    frame.setResizable(false);
    frame.getContentPane().add(tp);
    frame.setSize(680,480);
    frame.show();
    // index page
    // class sample
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import javax.swing.border.*;
    class sample extends JPanel implements ActionListener
    //button
    private JButton TimingButton;
    private JButton ViewButton;
    private JButton FrequencyButton;
    private JButton calculateButton;
    private CardLayout mycard;
    private JPanel SelectXPanel;
    private JPanel SelectYPanel;
    private JPanel SelectZPanel;
    private JPanel bigFrame, mainPane;
    // constructor
    public sample() {
    super(new BorderLayout());
    //create the object
    //create button and set it
    TimingButton = new JButton("MRT Timing Calculator");
    TimingButton.addActionListener(this);
    ViewButton = new JButton("View First and Last Train");
    ViewButton.addActionListener(this);
    FrequencyButton = new JButton("Show the Train Frequency");
    FrequencyButton.addActionListener(this);
    // Layout
    //Lay out the button in a panel.
    JPanel buttonPane = new JPanel(new GridLayout(3,0));
    buttonPane.add(TimingButton);
    buttonPane.add(ViewButton);
    buttonPane.add(FrequencyButton);
    // Layout the button panel into another panel.
    JPanel buttonPane2 = new JPanel(new GridLayout(0,1));
    buttonPane2.add(buttonPane);
    tfrequency x = new tfrequency();
    fviewl2 y = new fviewl2 ();
    timing z = new timing ();
    JPanel SelectXPanel = new JPanel(new GridLayout(0,1));
    SelectXPanel.add(x);
    JPanel SelectYPanel = new JPanel(new GridLayout(0,1));
    SelectYPanel.add(y);
    JPanel SelectZPanel = new JPanel(new GridLayout(0,1));
    SelectZPanel.add(z);
    // Layout the button by putting in between the rigid area
    JPanel mainPane = new JPanel(new GridLayout(3,0));
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(buttonPane2);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.setBorder(new TitledBorder("MRT Timing System"));
    // x = new tfrequency();
    // The overall panel -- divide the frame into two parts: west and east.
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    //bigFrame.add(x,BorderLayout.EAST); // this is where i want to link the page
    // this page being the index page. there being nothing to display.
    add(bigFrame);
    //Create the GUI and show it. For thread safety,
    public void actionPerformed (ActionEvent e){
    if (e.getSource() == TimingButton ){
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectZPanel,BorderLayout.EAST);
    add(bigFrame);
    else if (e.getSource() == ViewButton ){
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectYPanel,BorderLayout.EAST);
    add(bigFrame);
    else if (e.getSource() == FrequencyButton ){
    JPanel bigFrame2 = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectXPanel,BorderLayout.EAST);
    add(bigFrame);
    // Train Frequency Page
    // class fviewl2
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import javax.swing.border.*;
    class fviewl2 extends JPanel implements ActionListener
    //Labels to identify the fields
    private JLabel stationLabel;
    private JLabel firstLabel;
    private JLabel lastLabel;
    //Strings for the labels
    private static String station = "MRT Station:";
    private static String first = "First Train Time:";
    private static String last = "Last Train Time:";
    //Fields for data entry
    private JFormattedTextField stationField;
    private JFormattedTextField firstField;
    private JFormattedTextField lastField;
    //button
    private JButton homeButton;
    private JButton cancelButton;
    private JButton calculateButton;
    public fviewl2()
    super(new BorderLayout());
    //create the object
    //Create the Labels
    stationLabel = new JLabel(station);
    firstLabel = new JLabel (first);
    lastLabel = new JLabel (last) ;
    //Create the text fields .// MRT Station:
    stationField = new JFormattedTextField();
    stationField.setColumns(10);
    stationField.setBounds(300,300,5,5);
    //Create the text fields // First Train Time:
    firstField = new JFormattedTextField();
    firstField.setColumns(10);
    firstField.setBounds(300,300,5,5);
    //Create the text fields //Last Train Time:
    lastField = new JFormattedTextField();
    lastField.setColumns(10);
    lastField.setBounds(300,300,5,5);
    //Tell accessibility tools about label/textfield pairs, matching label for the field
    stationLabel.setLabelFor(stationField);
    firstLabel.setLabelFor(firstField);
    lastLabel.setLabelFor(lastField);
    //create button and set it
    homeButton = new JButton("Home");
    //homeButton.addActionListener(this);
    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(this);
    calculateButton = new JButton("Get Time");
    // Layout
    //MRT Station Label // insert into the panel
    JPanel StationPane = new JPanel(new GridLayout(0,1));
    StationPane.add(stationLabel);
    //MRT Station input field // insert into the panel
    JPanel StationInput = new JPanel(new GridLayout(0,1));
    StationInput.add(stationField);
    //Get Time Button // insert into the panel
    JPanel GetTime = new JPanel(new GridLayout(0,1));
    GetTime.add(calculateButton);
    //Lay out the labels in a panel.
    JPanel FlabelL = new JPanel(new GridLayout(0,1));
    FlabelL.add(firstLabel);
    FlabelL.add(lastLabel);
    // Layout the fields in a panel
    JPanel FFieldL = new JPanel(new GridLayout(0,1));
    FFieldL.add(firstField);
    FFieldL.add(lastField);
    //Lay out the button in a panel.
    JPanel buttonPane = new JPanel(new GridLayout(1,0));
    buttonPane.add(homeButton);
    buttonPane.add(cancelButton);
    // Layout all components in the main panel
    JPanel mainPane = new JPanel(new GridLayout(4,2));
    mainPane.add(StationPane);
    mainPane.add(StationInput);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(GetTime);
    mainPane.add(FlabelL);
    mainPane.add(FFieldL);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(buttonPane);
    mainPane.setBorder(new TitledBorder("View First and Last Train"));
    JPanel leftPane = new JPanel(new GridLayout(1,0));
    leftPane.add(Box.createRigidArea(new Dimension(0,1)));
    leftPane.add(mainPane);
    leftPane.add(Box.createRigidArea(new Dimension(0,1)));
    JPanel hahaFrame = new JPanel(new GridLayout(0,1));
    hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
    hahaFrame.setBorder(BorderFactory.createEmptyBorder(30, 10, 80, 150));
    hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
    JPanel bigFrame = new JPanel();
    bigFrame.add(hahaFrame, BorderLayout.NORTH);
    bigFrame.add(leftPane, BorderLayout.CENTER);
    add(bigFrame, BorderLayout.CENTER);
    //Create the GUI and show it. For thread safety,
    private void cancelButtonClicked()
    stationField.setText("");
    firstField.setText("");
    lastField.setText("");
    public void actionPerformed (ActionEvent e){
    if (e.getSource() == cancelButton){
    cancelButtonClicked();
    }

  • Saving an off screen Swing JPanel to a BufferedImage

    First, thanks for reading this. I have read through almost the whole forum and tried countless deviations of examples given here, but to no success.
    The situation is that from an Java 1.3 Applet, I am creating the ability for a user to create a simple graphic using standard Swing JTextArea components. This gives him/her the ability to place text arbitrarily on an JPanel. This works fine. The problem comes when the user wants to preview the image with the parametes replaced in the JTextAreas.
    We are generating GIF files after the user puts in the data. The problem occurs when we create an off screen JPanel with new JTextAreas with the parameters replaced with the test data filled in. We seem unable to create a BufferedImage from the un-shown JPanel.
    I have tried putting the JPanel in a JFrame and showing it before I call paint/print, etc. The only thing that seems to happen is that the JPanel background color is rendered to the GIF file, but not the JTextAreas on the JPanel. I have sucessfully written directly to the Graphics of the JPanel using drawString and generated a GIF, but that does not accomplish our goal.
    Any help would be appreciated. A test routine is included to give you the code. TIA.
    Kurt
    void test() {
    int height = 400;
    int width = 400;
    JFrame jf = new JFrame();
    jf.setBounds(0, 0, width, height);
    JPanel p = new JPanel();
    p.setBackground(Color.blue);
    p.setSize(width,height);
    JTextArea ta = new JTextArea();
    ta.setBackground(Color.black);
    ta.setForeground(Color.red);
    ta.setText("This is the text to set");
    ta.setColumns(10);
    ta.setRows(3);
    ta.setEditable(true);
    ta.setEnabled(true);
    ta.setVisible(true);
    p.add(ta);
    p.validate();
    jf.getContentPane().add(p);
    jf.validate();
    saveToFile(p);
    // This was taken and slightly modified for the AnimagedGifEncoder
    void saveToFile(JComponent source) {
    int w = source.getWidth();
    int h = source.getHeight();
    int type = BufferedImage.TYPE_INT_RGB;
    BufferedImage image = new BufferedImage(w, h, type);
    Graphics2D g2 = image.createGraphics();
    source.paint(g2);
    g2.dispose();
    AnimatedGifEncoder gif = new AnimatedGifEncoder();
    gif.start("D:/tmp/gifs/mygif.gif");
    gif.setDelay(1000);
    gif.addFrame(image);
    gif.finish();

    Your approach "putting the JPanel in a JFrame and showing it before I call paint/print" was ok, but it must be done in another thread, this sample is doing a similar job.
    You will see that when the print dialog is shown, the frame is fully visible with the button,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.print.*;
    public class PrintF extends JFrame
         JPanel  pan = new JPanel();
         JButton pri = new JButton("Print");
         JButton b1 = new JButton("The Click");
    public PrintF()
         super("This is a full frame print test");
         setBounds(1,1,500,350);     
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
                   dispose();     
                   System.exit(0);
         getContentPane().add("Center",pan);
         pan.setBackground(Color.white);
         pan.add(new JLabel("Label 1"));
         pan.add(pri);
         pri.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   TheT t = new TheT(b1);
    //               printIt(); 
         setVisible(true);
    public class TheT extends Thread  implements Printable
         JFrame  frame = new JFrame("The printed frame");  
    public TheT(JButton b)
         frame.setBounds(50,50,400,350);     
         frame.getContentPane().setLayout(null);     
         frame.getContentPane().add(b);
         b.setBounds(20,80,150,30);     
         start();
    public void run()
         frame.setVisible(true);
         printIt(); 
         frame.dispose();
    private void printIt()
         PrinterJob pj = PrinterJob.getPrinterJob();  
         PageFormat pf = pj.defaultPage();
         pf.setOrientation(pf.LANDSCAPE);
         pj.setPrintable(this,pf);
         if (pj.printDialog())
              try
                   pj.print();
              catch (Exception e){}    
    public int print(Graphics g, PageFormat pf, int pi)
                                                throws PrinterException
         if (pi > 0)
              setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
              return Printable.NO_SUCH_PAGE;
         setCursor(new Cursor(Cursor.WAIT_CURSOR));
         g.translate((int)pf.getImageableX()+2,(int)pf.getImageableY()+2);
         try
              Robot     r     = new Robot();
              Rectangle rect  = frame.getBounds();
              Image     image = r.createScreenCapture(rect);
              g.drawImage(image,2,2,null);
         catch(AWTException awe)
              System.out.println("robot excepton occurred");
         return(Printable.PAGE_EXISTS);
    public static void main (String[] args)
         new PrintF();  
    }       Noah

  • Fix for PENDING in javax.swing.text.html.ParagraphView line #131

    Investigating source of HTMLEditorKit I found many PENDING things. That's fix for one of them - proper minimal necessary span detecting in table cells.
    Hope it will help to somebody else.
    import javax.swing.*;
    import javax.swing.text.html.*;
    import javax.swing.text.html.ParagraphView;
    import javax.swing.text.*;
    import java.awt.*;
    import java.text.*;
    import java.util.ArrayList;
    public class App extends JFrame {
        public static String htmlString="<html>\n" +
                "<body>\n" +
                "<p>The following table is used to illustrate the PENDING in javax.swing.text.html.ParagraphView line #131 fix.</p>\n" +
                "<table cellspacing=\"0\" border=\"1\" width=\"50%\" cellpadding=\"3\">\n" +
                "<tr>\n" +
                "<td>\n" +
                "<p>111111111111111111111111111111111<b>bold</b>22222222222222222222222222222</p>\n" +
                "</td>\n" +
                "<td>\n" +
                "<p>-</p>\n" +
                "</td>\n" +
                "</tr>\n" +
                "</table>\n" +
                "<p></p>\n" +
                "</body>\n" +
                "</html>";
        JEditorPane editor=new JEditorPane();
        JEditorPane editor2=new JEditorPane();
        public static void main(String[] args) {
            App app = new App();
            app.setVisible(true);
        public App() {
            super("HTML span fix example");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JSplitPane split=new JSplitPane(JSplitPane.VERTICAL_SPLIT, createFixedPanel(), createOriginalPanel());
            getContentPane().add(split);
            setSize(700, 500);
            split.setDividerLocation(240);
            setLocationRelativeTo(null);
        JComponent createOriginalPanel() {
            JPanel p=new JPanel(new BorderLayout());
            p.add(new JLabel("Original HTMLEditorKit"), BorderLayout.NORTH);
            HTMLEditorKit kit=new HTMLEditorKit();
            editor2.setEditorKit(kit);
            editor2.setContentType("text/html");
            editor2.setText(htmlString);
            p.add(new JScrollPane(editor2), BorderLayout.CENTER);
            return p;
        JComponent createFixedPanel() {
            JPanel p=new JPanel(new BorderLayout());
            p.add(new JLabel("Fixed HTMLEditorKit"), BorderLayout.NORTH);
            HTMLEditorKit kit=new MyHTMLEditorKit();
            editor.setEditorKit(kit);
            editor.setContentType("text/html");
            editor.setText(htmlString);
            p.add(new JScrollPane(editor), BorderLayout.CENTER);
            return p;
    class MyHTMLEditorKit extends HTMLEditorKit {
        ViewFactory defaultFactory=new MyHTMLFactory();
        public ViewFactory getViewFactory() {
            return defaultFactory;
    class MyHTMLFactory extends HTMLEditorKit.HTMLFactory {
        public View create(Element elem) {
            View v=super.create(elem);
            if (v instanceof ParagraphView) {
                v=new MyParagraphView(elem);
            return v;
    class MyParagraphView extends ParagraphView {
        public MyParagraphView(Element elem) {
            super(elem);
        protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
            r = super.calculateMinorAxisRequirements(axis, r);
            float min=getLongestWordSpan();
            r.minimum = Math.max(r.minimum, (int) min);
            return r;
        public float getLongestWordSpan() {
            if (getContainer()!=null && getContainer() instanceof JTextComponent) {
                try {
                    int offs=0;
                    JTextComponent c=(JTextComponent)getContainer();
                    Document doc=getDocument();
                    int start=getStartOffset();
                    int end=getEndOffset()-1; //don't need the last \n
                    String text=doc.getText(start, end - start);
                    if(text.length() > 1) {
                        BreakIterator words = BreakIterator.getWordInstance(c.getLocale());
                        words.setText(text);
                        ArrayList<Integer> wordBounds=new ArrayList<Integer>();
                        wordBounds.add(offs);
                        int count=1;
                        while (offs<text.length() && words.isBoundary(offs)) {
                            offs=words.next(count);
                            wordBounds.add(offs);
                        float max=0;
                        for (int i=1; i<wordBounds.size(); i++) {
                            int wStart=wordBounds.get(i-1)+start;
                            int wEnd=wordBounds.get(i)+start;
                            float span=getLayoutSpan(wStart,wEnd);
                            if (span>max) {
                                max=span;
                        return max;
                } catch (BadLocationException e) {
                    e.printStackTrace();
            return 0;
        public float getLayoutSpan(int startOffset, int endOffset) {
            float res=0;
            try {
                Rectangle r=new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE);
                int startIndex= layoutPool.getViewIndex(startOffset,Position.Bias.Forward);
                int endIndex= layoutPool.getViewIndex(endOffset,Position.Bias.Forward);
                View startView=layoutPool.getView(startIndex);
                View endView=layoutPool.getView(endIndex);
                int x1=startView.modelToView(startOffset,r,Position.Bias.Forward).getBounds().x;
                int x2=endView.modelToView(endOffset,r,Position.Bias.Forward).getBounds().x;
                res=startView.getPreferredSpan(View.X_AXIS)-x1;
                for (int i=startIndex+1; i<endIndex; i++) {
                    res+=layoutPool.getView(i).getPreferredSpan(View.X_AXIS);
                res+=x2;
            } catch (BadLocationException e) {
                e.printStackTrace();
            return res;
    }Regards,
    Stas

    I'm changing the foreground color with
    MutableAttributeSet attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, newColor);
    int start=MyJTextPane..getSelectionStart();
    int end=MyJTextPane.getSelectionEnd();
    if (start != end) {
    htmlDoc.setCharacterAttributes(start, end, attr, false);
    else {
    MutableAttributeSet inputAttributes =htmlEditorKit.getInputAttributes();
    inputAttributes.addAttributes(attr);   

Maybe you are looking for

  • Remote database problem with Geometry data type

    Hello! I'm trying to insert and update a spatial table in a remote database. The syntax looks like: insert into tableA@remotedb (col1, col2) select col1, col2 from tableA where col3='abc'; This works fine with regular tables. But when I try it on spa

  • ICC profiles missing from the menu (InDesign 6.0.4.)

    After the update to InDesign 6.0.4 icc profiles saved in Macintosh HD/Library/ColorSync/Profiles does not list in InDesign profiles menus. But they show up in Photoshop CS4. Why? I've tried to reset the InDesign's preferences folder and fixed file pe

  • Unable to deploy optional components in axis adapter sda

    OS Windows 2003 and PI Version 7.0 Hi guys, Currently we are having problems in deplying optional components in axis adapter sda archive, we have included the optional components inside the provider.xml file inside the sda as per sapnote #1039369 but

  • Bapi to create the MIRO

    Hi All I  want to  create MIRO using the purchase order document, can any one please suggest the BAPI with which i can create. Thanks & Regards, Nehaa.

  • Acrobat Update not installed

    We deploy Adobe 9 Standard through Altiris.  The problem is that the option to run updates is not present on the Help menu, even when being run with an administrator login (we are Windows XP).  I have looked through Program Files\Common Files and in