GUI Problem (Swing JFrame/JPanel). HELP!

Hi,
I made an small application for calculate some things.
I download i piece of code for creating bar chart and i icluded in my code. But i have problem when i am trying to show the chart in the Frame. All the buttons, textfields, labels goes to left and half are hiding.
If i open the chart on a new frame i dont have problem.
the problem apears when after i put the panel in the frame i try to put the chart in the frame. Look the code:
add(p);     //Put the panel in the Frame
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!that command mades me the problem!
Here are 2 screenshots
1. When i put the chart in the Frame (the problem)
http://www.iweb.gr/images/InFrame.jpg
2. When i put the chart on new frame (works fine)
http://www.iweb.gr/images/NewFrame.jpg
Hopes someone can help. Thanks
The code List:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
//The main class of the program
public class PlantFertilizer  extends JFrame{//The main class is a subclass of Frame
     private Label lN, lP,lK;//These show the value of the observable
     public TextField tN, tP, tK;
     private MyData thedata;//The observable we are going to watch
     private double[] values=new double[3];
    private String[] names=new String[3];
    private String title;
public PlantFertilizer(){
     thedata=new MyData();// create the observable
     addWindowListener(new WindowAdapter(){//if user closes the Frame, quit
          public void windowClosing(WindowEvent e){
               System.exit(0);
     setSize(400,500);//Set size
     setTitle(getClass().getName()+" By Pantelis Stoumpis");
     JPanel p = new JPanel();    //Make a panel for buttons and output
     //Input Data Area
     p.add(new Label("-------------------------Input Data Area--------------------------",Label.CENTER));
     p.add(new Label("Nitrogen (N)"));
     tN = new TextField();p.add(tN);
     p.add(new Label("Phosphorus (P)"));
     tP = new TextField();p.add(tP);
     p.add(new Label("Potassium (K)"));
     tK = new TextField();p.add(tK);
     lN=new Label("N = %", Label.CENTER);
     p.add(lN);     //Put the N label in the panel
     lP=new Label("P = %", Label.CENTER);
     p.add(lP);          //Put the P label in the panel
     lK=new Label("K = %", Label.CENTER);
     p.add(lK);          //Put the K label in the panel
     addButton(p,"Apply",          //Apply new Values
     new ActionListener(){
     public void actionPerformed(ActionEvent evt){
          int iNt = Integer.parseInt(tN.getText());
          int iPt = Integer.parseInt(tP.getText());
          int iKt = Integer.parseInt(tK.getText());
          thedata.addOne(iNt,iPt,iKt);          //which adds one to the observable
          JFrame f = new JFrame();
         f.setSize(400, 300);
          values[0] = 40;
         names[0] = "N";
         values[1] = 20;
         names[1] = "P";
         values[2] = 30;
         names[2] = "K";
         f.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"));
          f.setVisible(true);
     addButton(p,"Close",          //add a close button to quit the program
     new ActionListener(){
     public void actionPerformed(ActionEvent evt){
          System.exit(0);
add(p);     //Put the panel in the Frame
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!
//A utility function to add a button with a given title and action
public void addButton(Container c, String title,ActionListener a)
          Button b=new Button(title);
          c.add(b);
          b.addActionListener(a);
public class ChartPanel extends JPanel {
  private double[] values;
  private String[] names;
  private String title;
  public ChartPanel(double[] v, String[] n, String t) {
    names = n;
    values = v;
    title = t;
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (values == null || values.length == 0)
      return;
    double minValue = 0;
    double maxValue = 0;
    for (int i = 0; i < values.length; i++) {
      if (minValue > values)
minValue = values[i];
if (maxValue < values[i])
maxValue = values[i];
//Dimension d = getSize();
//int clientWidth = d.width;
//int clientHeight = d.height;
//int barWidth = clientWidth / values.length;
//Dimension d = 100;
     int clientWidth = 100;
     int clientHeight = 150;
int barWidth = clientWidth / values.length;
Font titleFont = new Font("SansSerif", Font.BOLD, 12);
FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);
int titleWidth = titleFontMetrics.stringWidth(title);
int y = titleFontMetrics.getAscent();
int x = (clientWidth - titleWidth) / 2;
g.setFont(titleFont);
g.drawString(title, 10, 300);
int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();
if (maxValue == minValue)
return;
double scale = (clientHeight - top - bottom) / (maxValue - minValue);
y = clientHeight - labelFontMetrics.getDescent();
g.setFont(labelFont);
for (int i = 0; i < values.length; i++) {
int valueX = i * barWidth + 1;
int valueY = top;
int height = (int) (values[i] * scale);
if (values[i] >= 0)
valueY += (int) ((maxValue - values[i]) * scale);
else {
valueY += (int) (maxValue * scale);
height = -height;
g.setColor(Color.red);
g.fillRect(valueX, valueY, barWidth - 2, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY, barWidth - 2, height);
int labelWidth = labelFontMetrics.stringWidth(names[i]);
x = i * barWidth + (barWidth - labelWidth) / 2;
g.drawString(names[i], x, y);
//main is called when we start the application
public static void main(String[]args){
               PlantFertilizer od = new PlantFertilizer();//make an observationsDemo frame
               NWatcher watchitN = new NWatcher(od.lN);//make an observer
               od.thedata.addObserver(watchitN);//register observer with the observable
               PWatcher watchitP = new PWatcher(od.lP);//make an observer
               od.thedata.addObserver(watchitP);//register observer with the observable
               KWatcher watchitK = new KWatcher(od.lK);//make an observer
               od.thedata.addObserver(watchitK);//register observer with the observable
               od.setVisible(true);//show the frame on the screen

Why are you putting Labels and TextFields (heavyweight AWT components) into a lightweight JPanels?
What's the first rule of Swing? DO NOT MIX heavyweight AWT components and lightweight Swing components. Period. Never.
There's Swing equivalents for every single AWT component, and then some. There's no excuse for not using them.
However, if this chart library code is AWT based, then you should make a completely AWT based UI. Or find a different library based on Swing (like JFreeChart).
And finally:
add(p);     //Put the panel in the Frame
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!is wrong....
add(p);      // <-- The problem!!
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"));You don't call add on JFrame or JDialog to add things to it, unless you know what you're doing. And you clearly don't, else you wouldn't have done it. What you probably want to do is this:
this.getContentPane().add(p, BorderLayout.SOUTH);
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"), BorderLayout.CENTER);

Similar Messages

  • Problem with JFrame, JPanel and getInsets()...

    hi, this is my problem:
    I have a JFrame and I want add a JPanel to its ContentPan, I need to know the JFrame's getInsets values to set (with setBounds()) the right dimensions of the JPanel, but if I call getInsets() before of setVisible(true) I obtain all 0 values, if I call setVisible(true) before of add() I obtain the right values, but the JPanel is not showed.
    By now I have solved with this sequence:
    new panel();
    contpan.add(panel);
    getInsets();
    panel.setBounds();but I would pass the bounds values to my panel constructor, something like this:
    new panel(getInsets(););
    contpan.add(panel);Could someone help me?

    I have just found this post:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=302473
    And the first way seems to be the only way to solve the problem... :(
    Now the question is, does it exist a way to refresh a JFrame after that I have uset setVisible(true)?
    If it does exist I could have something like this:
    setVisible(true)
    new panel(getInsets(););
    contpan.add(panel);
    REFRESH();

  • Problem with JFrame , please help !

    hello , all !
    I define a JFrame1 as ancestor
    I set the JFrame's contentPane Layout to borderLayout ,
    and add some component in south , north , and add a menu , in its constructor
    then I define a new JFrame2 inherit from JFrame1, I also add a Jpanel component
    to contentPane center in its constructor !
    but something a wrong , I can't see the Jpanel , only see the components which add in JFrame1?
    this is why ?
    thanks
    /* source code */
    public class JFrame1{
    public JFrame1(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(borderLayout1);
    statusBar.setBorder(BorderFactory.createEtchedBorder());
    statusBar.setText("Hello , Young follow! ");
    contentPane.add(statusBar, BorderLayout.SOUTH);
    toolbar = new Toolbar_DataEntry(this);
    contentPane.add(toolbar, BorderLayout.NORTH);
    menubar = new Menu_DataEntry(this);
    this.setJMenuBar(menubar);
    public class JFrame2 extends JFrame1 {
    public JFrame2() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    JPanel bodyPane = new JPanel();
    bodyPane.setDataModule(queryDataSet1);
    queryDataSet1.Opendatabase();
    bodyPane.setBorder(null);
    this.setTitle("Frame Title");
    bodyPane.setBounds(new Rectangle(4, 5, 427, 114));
    contentPane.setPreferredSize(bodyPane.getPreferredSize());
    contentPane.setMinimumSize(bodyPane.getMinimumSize());
    Frame_Resize();

    The problem is that the constructor for JFrame2 does not automatically call the constructor for JFrame1. Therefore the JFrame1 constructor never gets called.
    You must do this yourself with the super() method.
    public JFrame2() {
    super();
    try {
    jbinit();
    catch( Exception e )
    e.printStackTrace();
    Remember that this rule applies to all descendent classes.

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Problem with JFrame and JPanel

    Okay, well I'm busy doing a lodge management program for a project and I have programmed this JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FinalTest extends JFrame
         public JPanel contentPane;
         public JImagePanel imgPanel;
         private JLabel[] cottageIcon;
         private boolean keepMoving;
         private int selectedCottage;
         public FinalTest()
              super();
              initializeComponent();
              addActionListeners();
              this.setVisible(true);
         private void initializeComponent()
              contentPane = (JPanel)getContentPane();
              contentPane.setLayout(null);
              imgPanel = new JImagePanel("back.png");
               imgPanel.setLayout(null);
              imgPanel.setBackground(new Color(1, 0, 0));
                   addComponent(contentPane, imgPanel, 10,10,imgPanel.getImageWidth(),imgPanel.getImageHeight());
              cottageIcon = new JLabel[6];
              keepMoving = true;
              selectedCottage = 0;
              cottageIcon[0] =  new JLabel();
              //This component will never be added or shown, but needs to be there to cover for no cottage selected
              for(int a = 1; a < cottageIcon.length; a++)
                   cottageIcon[a] = new JLabel("C" + (a));
                   cottageIcon[a].setBackground(new Color(255, 0, 0));
                    cottageIcon[a].setHorizontalAlignment(SwingConstants.CENTER);
                    cottageIcon[a].setHorizontalTextPosition(SwingConstants.LEADING);
                    cottageIcon[a].setForeground(new Color(255, 255, 255));
                    cottageIcon[a].setOpaque(true);
                    addComponent(imgPanel,cottageIcon[a],12,(a-1)*35 + 12,30,30);
                this.setTitle("Cottage Chooser");
                this.setLocationRelativeTo(null);
              this.setSize(new Dimension(540, 430));
         private void addActionListeners()
              imgPanel.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        imgPanel_mousePressed(e);
                   public void mouseReleased(MouseEvent e)
                        imgPanel_mouseReleased(e);
                   public void mouseEntered(MouseEvent e)
                        imgPanel_mouseEntered(e);
              imgPanel.addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseDragged(MouseEvent e)
                        imgPanel_mouseDragged(e);
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         private void imgPanel_mousePressed(MouseEvent e)
              for(int a = 1; a < cottageIcon.length; a++)
                   if(withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()))
                        System.out.println("B" + withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()));
                        selectedCottage = a;
                        keepMoving = true;
         private void imgPanel_mouseReleased(MouseEvent e)
              System.out.println("called");
              selectedCottage = 0;
              keepMoving = false;
         private void imgPanel_mouseDragged(MouseEvent e)
               System.out.println("XXX" + Math.random() * 100);
              if(keepMoving)
                   int x = e.getX();
                    int y = e.getY();
                    if(selectedCottage!= 0)
                         cottageIcon[selectedCottage].setBounds(x-(30/2),y-(30/2),30,30);
                    if(!legalBounds(imgPanel,cottageIcon[selectedCottage]))
                        keepMoving = false;
                        cottageIcon[selectedCottage].setBounds(imgPanel.getWidth()/2,imgPanel.getHeight()/2,30,30);
              System.out.println(cottageIcon[selectedCottage].getBounds());
         private void imgPanel_mouseEntered(MouseEvent e)
               System.out.println("entered");
         private void but1_actionPerformed(ActionEvent e)
              String input = JOptionPane.showInputDialog(null,"Enter selected cottage");
              selectedCottage = Integer.parseInt(input) - 1;
         public boolean legalBounds(Component containerComponent, Component subComponent)
              int contWidth = containerComponent.getWidth();
              int contHeight = containerComponent.getHeight();
              int subComponentX = subComponent.getX();
              int subComponentY = subComponent.getY();
              int subComponentWidth = subComponent.getWidth();
              int subComponentHeight = subComponent.getHeight();
              if((subComponentX < 0) || (subComponentY < 0) || (subComponentX > contWidth) || (subComponentY > contHeight))
                   return false;
              return true;
         public boolean withinBounds(int mouseX, int mouseY, Rectangle componentRectangle)
              int componentX = (int)componentRectangle.getX();
              int componentY = (int)componentRectangle.getY();
              int componentHeight = (int)componentRectangle.getHeight();
              int componentWidth = (int)componentRectangle.getWidth();
              if((mouseX >= componentX) && (mouseX <= (componentX + componentWidth)) && (mouseY >= componentY) && (mouseY <= (componentY + componentWidth)))
                   return true;
              return false;
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              FinalTest ft = new FinalTest();
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class JImagePanel extends JPanel
      private Image image;
      public JImagePanel(String imgFileName)
           image = new ImageIcon(imgFileName).getImage();
        setLayout(null);
      public void paintComponent(Graphics g)
        g.drawImage(image, 0, 0, null);
      public Dimension getImageSize()
                Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
             return size;
      public int getImageWidth()
                int width = image.getWidth(null);
                return width;
      public int getImageHeight()
              int height = image.getHeight(null);
              return height;
    }Now the problem I'm having is changing that class to a JFrame, it seems simple but I keep having problems like when it runs from another JFrame nothing pops up. I can do it like this:
    FinalTest ft = new FinalTest();
    ft.setVisible(false);
    JPanel example = ft.contentPanehowever I will probably be marked down on this for bad code. I'm not asking for the work to be done for me, but I'm really stuck on this and just need some pointers so I can carry on with the project. Thanks,
    Steve

    CeciNEstPasUnProgrammeur wrote:
    I'd actually consider your GUI being a JPanel instead of a JFrame quite good design - makes it easy to put the stuff into an applet when necessary...
    Anyway, you should set setVisible() to true to make it appear, not to false. Otherwise, I don't seem to understand your problem.That is actually my problem. I am trying to convert this JFrame to a JPanel

  • Plz help with me gui problem(arraylist)

    my program
    stocksymbol ------------------ stockname ------------------ enter
    (label) (textfield) (label) (textfield) (button)
    create a gui application using jframe and jpanel so that user can enter stock details(symbol,name) when user press "enter(button)" the text entered in the textfield should be add to an arraylist.
    when we close the window ,we have to print the items present in the arraylist....
    i have created all the components but iam getting difficult in display the arraylist when i close the window
    i have created these classes
    public class Stock {?}
    public class StockEntryFrame extends JFrame {
    // code to allow the frame to handle a window closing event ? when the window is closed,
    // the stock list should be printed. ?
    public class StockEntryPanel extends JPanel {
    public StockEntryPanel(ArrayList<Stock> stockList) {
    can u plz help me how to diplay the contents in arraylist

    MY PROGRAM IS LIKE THIS:::::::::
    STOCKNAME-----------
    STOCKSYMBOL---------
    STOCK PRICE--------
    ENTER(BUTTON)
    WHEN USER ENTERS HIS INPUT IN THE TEXT BOX AND PRESS ENTER, THEN THE TEXT PRESENT IN THE TEXTBOX SHOULD BE ENTERED INTO AN ARRAYLIST.
    THIS IS A GUI PROGRAM......
    WHEN WE CLOSE THE FRAME ,WE HAVE TO DISPLAY THE CONTENTS PRESENT IN THE ARRAYLIST
    I HAVE CREATED THE PROGRAM LIKE THIS
    CLASS STOCKENTRYPANEL EXTENDS JPANEL
    //ADDING ALL THE COMPONETNS TO THE PANEL
    CLASS STOCKENTRY FRAME EXTENDS JFRAME
    //ADDING PANEL TO THE FRAME
    //I NEED THE CODE HERE
    WHEN WE CLOSE THE WINDOW THE ARRAYLIST DETAILS SHOULD BE PRINTED
    }

  • Problems painting a JPanel component on a JFrame

    Hi.
    I've built a subclass of JPanel that has some controls on it, such as JPanels, JCheckBoxes, images, etc. I need to repaint this JPanel periodically because its contents are constantly changing.
    I have it added to a main JFrame (this JFrame has also other JPanels in other locations of its content pane), and when I try to repaint this JPanel, it does not seem to be double buffered, because it momentaneously repaints other parts of the window into the JPanel region, and after that it repaints what it should.
    I have tested a Panel instead of a JPanel to do the same task, and the Panel works fine.
    Basically, the code is:
    public class MyFrame extends JFrame
    JPanel myPanel = new JPanel();
    JPanel myPanel2 = new JPanel();
    JPanel myPanel3 = new JPanel();
    public MyFrame()
    getContentPane().setLayout(null);
    getContentPane().setSize(600, 400);
    myPanel.setBounds(0, 0, 200, 200);
    myPanel2.setBounds(0, 200, 200, 200);
    myPanel3.setBounds(0, 400, 200, 100);
    getContentPane().add(myPanel);
    getContentPane().add(myPanel2);
    getContentPane().add(myPanel3);
    // javax.swing.Timer to update myPanel
    Timer t = new Timer( 2000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    myPanel.repaint();
    t.start();
    I actually use othe class names and field names, but the structure is basically the same.
    Any idea of what am I doing wrong? Why Panels work fine in the same situation, into the same JFrame?
    Thank you.

    Try constructing your JPanels as doublebuffered then. (new JPanel(A layoutmanager, true)). The latter parameter is a boolean for creating a doublebuffered JPanel or not. Try with calling myPanel.revalidate() after repainting.

  • GUI - Problem with GridBag

    Hi everyone,
    I have been trying to get this GUI built from the ground up and I have encountered a problem with the GridBag(exception error that the fields being added can not be done. Also, my method main seems to be off track, I have a working program which the display fields have been modified to display object and everything else is the same except that I can not get the GUI to run.
    The following is the code and any suggestions as to what I can do to get this going will be appreciated. Thank you.
    import javax.swing.JLabel; /* displays text and images*/
    import javax.swing.SwingConstants; /* common constants used with Swing*/
    import javax.swing.Icon; /* interface used to manipulate images*/
    import javax.swing.ImageIcon; /* loads images*/
    import javax.swing.JOptionPane;
    import java.util.*;
    import java.io.PrintStream;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.text.*;     
    import javax.swing.JFrame;/* provides basic window features*/     
    import java.util.Arrays;
    import javax.swing.ImageIcon.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class FinalInventoryGUI extends JFrame
    {//Private variables.
    private GridBagLayout layout = new GridBagLayout();
    private GridBagConstraints constraints = new GridBagConstraints();
    //Private data from main program
    private String productName;
    private String itmeNumber;
    private double unitPrice;
    private int unitStock;
    private double productValue;
    private double inventoryValue;
    private double reStkfee;
    //Declaration of the JLabels.
    private JLabel logoLabel;
    private JLabel productNameLabel;
    private JLabel itemNumberLabel;
    private JLabel unitPriceLabel;
    private JLabel unitStockLabel;
    private JLabel productValueLabel;
    private JLabel InventoryValueLabel;
    private JLabel reStkfeeLabel;
    //Declaration of the text Fields for data Entry.     
    private JTextField productNameText;
    private JTextField itemNumberText;
    private JTextField unitPriceText;
    private JTextField unitStockText;
    private JTextField productValueText;
    private JTextField inventoryValueText;
    private JTextField reStkfeeText;
    private JTextField titleText;
    //Declaration of the JButtons for user interface.
    private JButton first;//To move to first element in the array.
    private JButton next;//To move to next element in the array.
    private JButton previous;//To move to next element in the array.
    private JButton lastButton;//To move to the first element in the array.
    private JButton addButton;//To add a product to the array.
    private JButton modifyButton;//To modify an element in the array.
    private JButton deleteButton;//To remove a product from the array.
    private JButton saveButton;//To save the array elements to C:\.
    private JButton searchButton;//To search for an element in the array.
    private Product products[];//Declaration of array product[] for storing entries.
    private int NumOfProducts;//Declaration of the variable defining the number of products.
    private int Index=0;//Setting the counter index to initiate at "0".
    //Constants
    private final static int LOGO_WIDTH  = 4;
    private final static int LOGO_HEIGHT = 4;
    private final static int LABEL_WIDTH  = 1;
    private final static int LABEL_HEIGHT = 1;
    private final static int TEXT_WIDTH  = LOGO_WIDTH-LABEL_WIDTH;
    private final static int TEXT_HEIGHT = 1;
    private final static int BUTTON_WIDTH  = 1;
    private final static int BUTTON_HEIGHT = 1;
    private final static int LABEL_START_ROW = LABEL_HEIGHT+LABEL_WIDTH+1;
    private final static int LABEL_COLUMN = 0;
    private final static int TEXT_START_ROW = LABEL_START_ROW;
    private final static int TEXT_COLUMN = LABEL_WIDTH+1;
    private final static int BUTTON_START_ROW = LABEL_START_ROW+9*LABEL_HEIGHT;
    private final static int BUTTON_COLUMN = LABEL_COLUMN;
    private final static int SEARCH_START_ROW = BUTTON_START_ROW+3;
    final static String EMPTY_ARRAY_MESSAGE = "Hit ADD to add a new PRODUCT";
    //Constructor-New instance of the JLabelTextFieldView.
    public FinalInventoryGUI( Product productsIn)
        {//Passing the frame title to JFrame, set the IconImage.
             super("Welcome To The Inventory Program");
             setLayout(layout);
             //Copy the input array(products).
             setProduct(productsIn);//maybe the title?????
             //Start the display with the first element of the array.
             index = 0;
             //Build the GUI
             buildGUI();
             //Values
             updateAllTextFields();
             }//End of the constructor for building the GUI.
             //Methods for copying the input of Product array to the GUIs private array
             //variable
             private void setInventoryArray(Product productsIn[])
                  products = new Product[productIn.length];
                  for (int i = 0; i<products.length; i++)
                  {//Creates A Product array element from the input array.
                       prodcuts[i] = new Product(productIn);
                   products[i] = new Product(productIn[i].productName(), productIn[i].itemNumber(),
                                                      productIn[i].unitStock(), productIn[i].unitPrice());
              //System prints out a ineof the productsIn array to a string.
         }//End of the for statment.
         }//End for copying the array.
         //A method for updating each of the GUIs fields.
         private void updateAllTextFields()
              if(products.length > 0)//Then update the JTextField display.
              {// Update the product name text field.
              productNameText.setText(products[index].productName());
              //Update the Update the itemNumber text field.
              itemNumberText.set(String.format("%d", products[index].itemNumber()));
              //Update the title text field.
              titleText.setText(dvd[index].title());
              //Update the unitStock text field.
              unitStockText.setText(String.format("%d",products[index].unitStock()));
              //Update the unit price textField.
              unitPriceText.setText(String.format("$%.2f",products[index].unitPrice()));
              //Update the productValue textField.
              productValueText.setText(String.format("$%.2f", products[index].productValue()));
              //Update the restocking fee text field.
              reStkfeeText.setText(String.format("$%.2f",reStkfee()));
              //Update the total value of the inventory text field.
              inventoryValueText.setText(String.formtat("$%.2f",Product.productValue(products)));
              }//End of the if statement.
              else//Put a special message in the fields.
              {//Update the productName textField.
              productNameText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the itemNumber textField
              itemNumberText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the title textField.
              titleText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the units in stock textField.
              unitStockText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the unitPrice textFied.
              unitPriceText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the productValue textField.
              productValueText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the restocking fee textField.
              reStkfeeText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the totatl inventoryValue textField.
              inventoryValueText.setText(EMPTY_ARRAY_MESSAGE);
              }//End else
         }//Set the appropriate fields editable or uneditable.
         private void setModifiableTextFieldsEnabled(Boolean state)
         {//The fields of the product name, item number, unit price,
         // and stock can be editable or non editable.
         itemNumber.setEditable(state);
         productName.setEditable(state);
         unitPrice.setEditable(state);
         unitStock.setEditable(state);
         }//End setting of the modifiable textFields.
         //Methods for the JButton methods.
         private class ButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
              {//This is the first button being pressed by the user.
                   if(event.getSource()==firstButton)
                        handleFirstButton();
                   }//End if
                   else if(event.getSource()==previousButton)//Button previous is pressed by user.
                        handlePreviousButton();
                   }//End else if
                   else if (event.getSource()==nextButton)//Button next is pressed by user.
                        handleNextButton();
                   }//End else if.
                   else if (event.getSource()==lastButton)//Button last is pressed by the user.
                        handleLastButton();
                   }//End else if.
                   else if(event.getSource()==firstButton)
                        handleFirstButton();
                   }//End else if.
         }//End metod of actionPeformed.
         }//End class ButtonHandler
         //Displaying the first element of the Product array
         private void handlerFirstButton()
         {//Setting the index to the first element in the array.
              index = 0;
         //Update and disable modification
         updateAllFields();
         setModifiableTextFieldsEnabled(false);
         }//End method for handling the first button.
         //Displaying the next element of the products array or wrap to the first.
         private void handleNextButton()
         {//Incrementation of the index.
         index++;
         //If the index exceeds the last valid array element, wrap around to the first
         //element of the array.
         if(index > products.length-1)
              index = 0;
         }//End if statment.
         //Update and disable the modification.
         updateAllFields();
         setModifiableTextFieldsEnabled(false);
         }//End method of handleNextButton.     
         private void handlePreviousButton()
              index--;
              if(index < 0)
                   index = products.length -1;
              }//End if statment.
              //Update and disabe modification.
              updateAllTextFields();
              setModifiableTextFieldsEnabled(false);
         }//End method of handlePreviousButton.
         private void handleLastButton()
              index--;
              if(index < products.length -1)
                   index = 2;
              }//End if statment.
              updateAllTextFields();
              setMdifiableTextFieldsEnabled(false);
              }//End method for handleLatButton
         //The textFieldHandler class - handling the events of the buttonsmethods
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
              {//The user pressed "ENTER" in the JTextField "title" text.
              if(event.getSource() == itemNumber)
                   //HandleItemNumberTextField()is fired.
              }//End the if statement.
              //The user pressed "ENTER" in the JTextField "title" text.
              else if (event.getSource() == titleText)
                   //HandleTitleTextField() is fired.
              }//End the if statement.
         //The user pressed "ENTER" in the JTextField "unitStoc" text.
              else if(event.getSource() == unitStockText)
                   //HandleUnitStockTextField() is fired.
              }//End the if statment
              //The user pressed "ENTER" in the JtextField "unitPrice" text.
              else if (event.getSource() == unitPriceText)
                   //HandleUnitPriceTextField() is fired.
              }//End the if statment.
         //The user pressed "ENTER" in the JTextField "Search" text.
         else if(event.getSource() == searchText)
              //HandleSearchTextField() is fired.
         }//End the if statment.
              }//End the method actionPerformed.
         }//End the inner class TextFieldhandler.
              //The GUI methods.
              //Building the GUI.
              private void BuildGUI()
              {//Mthod for adding the LOGO.
              buildLogo();
              //Add the text fields and their labels.
              buildLabels();
              buildTextFields();
              //Add the navigation and other buttons.
              buildMainButtons();
              //Provide value to the Fields.
              updateAllTextFields();
              //provide some setup to the frame.
                        setSize(FRAME_LENGTH, FRAME_WIDTH);
                        setLocation(FRAME-XLOC, FRAME_YLOC);
                        setResizable(false);
                        //PACK(); IS THIS NOT PART OF THE GUI ADDED AT THE END OR IS WHAT
                        //FOLLOWS THE SAME AS SAYING ".PACK()".
                        setDefaultCloseOperation(EXIT_ON_CLOSE);//DOES IT MATTER WHERE THIS LINE FALLS?
                        //WHEN I TRIED TO USE IT IN THE MAIN I RECEIVED AN ERROR AND THE SAME WHEN I
                        //PLACED IT IN THE CONSTRUCTOR--WHY?.
                        setVisible(true);
              }//End of building the GUI.
              //Addin the LOGO to the Frame.
              private void buildLogo()
                   constraints.weightx = 2;
                   constraints.weigthy = 1;
                   logoLabel = new JLabel(new ImageIcon("O2K.jpg"));
                   logoLabel.setText("Products Inventory");
                   constraints.fill = GridBagConstraints.BOTH;
                   addToGridbag(logoLabel,2,2,LOGO_WIDTH, LOGO_HEIGHT);
                   //Creating a vertical space.
                   addToGridBag(new JLabel(""),LOGO_HEIGHT+1,0, LOGO_WIDTH, LABEL_WIDTH);
              }//End the method with building the LOGO.
                   //Build the panel just containing the text.
                   private void buildLabels()
                   {//Set up if for readability).
                   int rows = 0;
                   int column = 0;
                   int width = 0;
                   int height = 0;
              column = LABEL_COLUMN;
              width = LABEL_WIDTH;
              height = LABEL_HEIGHT;
                   constraints.weightx = 1;
                   constraints.weighty = 0;
                        constraints.fill = GridbagConstraints.Both;
                        //Create the name labes and name the TextFields.
                        productNameLabel = new JLabel("Product Name:");
                        productnamelabel.setLabelfor(productNameField);
                        productNameLabel.setLabelFor(productNameText);
                        productNameLabel.setToolTipText("Enter The Product Name Here");
                        row = Label_START_ROW;          
                        addToGridBag(productNameLabel, row, column, width, height);
                        //Create the itemNumberLabel and TextField.
                        itemNumberLabel = new JLabel("Product Id:");
                        itemNumberLabel.setLabelFor(itemNumberText);
                        row += LABEL_HEIGHT;
                        addToGridBag(itemNumber, row, column, width, height);
                        //Create the title label for the Product and the title text field.
                        titleLabel = new JLabel("Inventory Of Products:");
                        titleLabel.setLabelFor(titleText);
                        row += LABEL_HEIGHT;
                        addToGridBag(titleLabel,row,column,width,height);
                        //Create the unitStock label and textField.
                        unitStockLabel = new JLabel("Units In Stock:");
                        unitStockLabel.setLabelFor(unitStockLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(unitStocklabel, row, column, height);
                        //Creat the unitPrice label and textField.
                        unitPriceLabel = new JLabel("Unit Price");
                        unitPriceLabel.setLabelFor(unitPriceLabel);
                        unitPriceLabel.setToolTipText("The Cost Of The Product");
                        row += LABEL_HEIGHT;
                        addToGridBag(unitPriceLabel, row, column, height);
                        //Create the productValue label and textField.
                        productValueLabel = new JLabel("Total Product Value:");          
                        productValueLabel.setLabelFor(productValueLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(productValue, row, column, height);
                        //Create the restocking fee of 1.05% Label and textField.
                        reStkfeeLabel = new JLabel("Product Restock Fee:");
                        reStkfeeLabel.setLabelFor(reStkfeeLabel);
                        row+= LABEL_HEIGHT;
                        addToGridBag(reStkfee, row, column, height);
                        //Create a vertical space.
                        row += LABEL_HEIGHT;
                        //Create the Total Inventory Value label and textField.
                        inventoryValueLabel = new JLabel("Total Inventory Value:");
                        inventoryValueLabel.setLabelFor(inventoryValueLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(inventoryValue, row, column, height);
              }//End the method for building the labels
                        //Build the methods for the TextFields.
                        private void buildTextFields()
                             {//Defining the variables
                             int row = 0;
                             int column = 0;
                             int width = 0;
                             int height = 0;
                             column = TEXT_COLUMN;
                             width = TEXT_WIDTH;
                             height = TEXT_HEIGHT;
                             constraints.fill = GridBagConstraints.BOTH;
                             constraints.weightx = 1;                    
                             TextFieldHandler handler = new TextFieldHandler();
                             productNameText = new JTextField("Product Name");
                             productNameText.setEditable(false);
                             row = TEXT_START_ROW;
                             addToGridBag(productNameText, row, column, height);
                        itemNumberText = new JTextField("Product Id");
                        itemNumberText.setEditable(false);
                        row = TEXT_START_ROW;
                        addToGridBag(itemNumberText, row, column, height);
                        titleText = new JTextField("Title");
                        titleText.addActionListener(handler);
                        titleText.setEditable(false);
                        row += TEXT_HEIGHT;
                        addToGridBag(titleText, row, column, height);
                        unitPriceText = new JTextField("Unit Price");
                        unitPriceText.addActionListener(handler);
                        unitPrice.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(unitPriceText, row, column, height);
                        unitStockText = new JTextField("Units In Stock");
                        unitStockText.addActionListener(handler);
                        unitStockText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(unitStockText, row, column, height);
                        productValueText =new TextField("Product Value");
                        productValueText.addActionListener(handler);
                        productValueText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(productValueText, row, cloumn, height);
                             reStkfeeText =new JTextField("Restock Fee");
                        reStkfeeText.addActionListener(handler);
                        reStkfeeText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(reStkfeeText, row, cloumn, height);
                        //Creat vertical space.
                        row += TEXT_HEIGHT;
                        addToGridBag(new JLabel(""),row, column, height);
                        inventoryValueText =new TextField("Inventory Value");
                        inventoryValueText.addActionListener(handler);
                        inventoryValueText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(inventoryValueText, row, cloumn, height);
                        }//End the methods for building the TextFields.
                             //Add the main buttons to the frame.
                   private void buildMainButtons()
                             {//Declaraing the variables.
                             int row = 0;
                             int column = 0;
                             int width = 0;
                             int height = 0;                         
                             row =BUTTON_START_ROW;
                             column = BUTTON_COLUMN;
                             width = BUTTON_WIDTH;
                             height = BUTTON_HEIGHT;
                             constraints.weightx = 1;
                             constraints.weighty = 0;                         
                             //The constraints.fill = GridBagConstraints.HORIZONTAL;
                             ButtonHandler handler = new ButtonHandler();
                             //Creat a veritical space.
                             addToGridbag(new JLabel(""), row, column, width, height);
                             firstButton = new JButton("First");
                             firstButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(firstButton, row, column, width, height);                         
                             previousButton = new JButton("Previous");
                             previousButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(previousButton, row, column, width, height);     
                             nextButton = new JButton("Next");
                             nextButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(nextButton, row, column, width, height);     
                             lastButton = new JButton("Last");
                             lastButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(lastButton, row, column, width, height);     
                             addButton = new JButton("Add");
                             addButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(addButton, row, column, width, height);                         
                             deleteButton = new JButton("Delete");
                             deleteButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(deleteButton, row, column, width, height);
                             saveButton = new JButton("Save");
                             saveButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(saveButton, row, column, width, height);     
                             searchButton = new JButton("Search");
                             searchButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(searchButton, row, column, width, height);                         
                        //End methods for building the main butt0ns.
         private void addToGridBag(Component component, int row, int column, int width, int height)
         {               //Set up the upper-left corner of the component gridx and gridy.
                             constraints.gridx = column;
                             constraints.gridy = row;
                             //Set the numbers of rows and columns the components occupies.
                             constraints.gridwidth = width;
                             constraints.gridheight = height;
                             //set the constraints
                             Layout.setConstraints(component, constraints);
                             //Add the component to the JFrame.
                             add(component);                    
                        }//End method for addGridBag.                     
              //End class JLabelTextFieldViewGui.
    class Invetnory4
              public static void main(String args[])
                        {   //An array variable.
                             Product[]inventory;
                             inventory = new Product[10];
                             //Create and pass control to the GUI
                             FinalInventory gui = new FinaInventoryGUI(inventory);           
                        }//End method main
                   }//End class Inventory4     
    /*Inventory.java*/
    /*Means for importing program packages*/
    /*Beginning of the class type Inventory*/

    Hi Bryan,
    I took your advice and decided to take a different approach to the problem I am having, I decided to stay somewhat with the basics with little knowledge I have about coding. I am new to this and I am trying to learn through the fire but it's getting hot so if you don't mind, can you tell me what I need to do to fix the error messages I am getting.
    1. "else" without "if',
    2. can't load my icon-a JPG
    3. exception in thread amin
    process complete.
    4.Text area for displaying an iteration of the input
    the code is not as long as the other one! any help will be appreciated. Also I am attaching the code to the GUI that does work but I can not seem to get the actionListener aspect to work. Thanks again.
      //this one works and it serves as a model for what I am //trying to do in the fields. as well as designate a text area                                                              //where a each entry per iteration of input is displayed
    * @(#)InventoryGUIFrame.java
    * @author
    * @version 1.00 2008/2/2
    package components;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    * FormattedTextFieldDemo.java requires no other files.
    * It implements a mortgage calculator that uses four
    * JFormattedTextFields.
    public class InventoryGUIFrame extends JFrame
              String productName;
              String itemNumber;
              double unitPrice;
              double unitStock;
              //Labels to identify the fields
              private JLabel productNamelabel;
              private JLabel itemNumberlabel;
              private JLabel unitPricelabel;
              private JLabel unitStocklabel;
              //Fields for data Entry     
              private JTextField productNameField;
              private JTextField itemNumberField;
              private JTextField unitPriceField;
              private     JTextField unitStockField;
                   //Adding the JButtons
              JButton firstButton;
              JButton nextButton;
              JButton previousButton;
              JButton searchButton;
              JButton addButton;
              JButton deleteButton;
              JButton saveButton;
              //Constructor          
    public InventoryGUIFrame()
             super("Welcome To The Inventory Program");
             setLayout(new FlowLayout());
             setDefaultCloseOperation(EXIT_ON_CLOSE);
             JFrame Frame = new JFrame();
             Frame JPanel = new Frame();
             JPanel  JLabel= new JPanel();
             TextArea area = new TextArea();
         productNamelabel = new JLabel("PRODUCT  NAME");
         productNamelabel.setToolTipText("Name of the item you wish to calculate");
        add(productNamelabel);
         productNameField= new JTextField(8);
         add(productNameField);
         itemNumberlabel = new JLabel("PRODUCT  NUMBER");
         itemNumberlabel.setToolTipText("Number identifying the product");
         add(itemNumberlabel);
         itemNumberField =new JTextField(5);
         add(itemNumberField);
         unitPricelabel=new JLabel("PRODUCT  PRICE");
         unitPricelabel.setToolTipText("What is the cost of the product?:");
         add(unitPricelabel);
         unitPriceField = new JTextField(5);
         add(unitPriceField);          
         unitStocklabel = new JLabel("UNITS  IN  STOCK");
         unitStocklabel.setToolTipText("How many products in inventory?:");
         add(unitStocklabel);
         unitStockField = new JTextField(5);
         add(unitStockField);
         firstButton =new JButton("First");
         add(firstButton);
         nextButton = new JButton("Next");
         add(nextButton);
         previousButton = new JButton("Previous");
         add(previousButton);
         addButton = new JButton("Add");
         add(addButton);
         deleteButton = new JButton("Delete");
         add(deleteButton);
         saveButton = new JButton("Save");
         add(saveButton);
         searchButton = new JButton("Search");
         add(searchButton);
         public static void main(String args[])
         InventoryGUIFrame frame  = new InventoryGUIFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(740,150);
         frame.setVisible(true);
      class InventorySystem6
    {     /*Declaration of products[] and the maximum storing capacity*/
       private Product products[] = new Product[MAX_NUM_OF_PRODUCTS];
       /*Prompts user to make another selection or exit program*/
       private static final String STOP_COMMAND = "stop";
            /*parameters defining maximun numbers of products available for storing in */
    private static final int MAX_NUM_OF_PRODUCTS = 100;
    /*Declaration of the variables */
    String name;
    String item;
    double stock;
    double price;
    double reStkfee=1.05;
    double pValue;
    double iValue;
    public InventorySystem6()
         /*Empty Constructor*/
    }/*Beginning of product input by the user*/
    public void inputProductInfo()
    {     /*Declaration of currency format*/     
                   DecimalFormat Currency = new DecimalFormat();
                   Scanner input = new Scanner(System.in);
                   /*Beginning of the Loop*/
                   JOptionPane.showMessageDialog(null,"Welcome to the Inventory Program\n","Welcome to the Inventory Program\n",
                   JOptionPane.PLAIN_MESSAGE);               
                   for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
                   name = JOptionPane.showInputDialog( "What is the Product Name? ");
                   if(name.equalsIgnoreCase("stop"))
                   break;
         String item = JOptionPane.showInputDialog("Enter the products ID");
         String priceStr =JOptionPane.showInputDialog("Enter the products price");
         double price=Double.parseDouble(priceStr);
                   String stockStr=JOptionPane.showInputDialog("Enter the units in stock " );
                   double stock = Double.parseDouble(stockStr);          
                   double sum=price*stock;
              JOptionPane.showMessageDialog(null,"The product value is:"+sum, "pValue",
              JOptionPane.PLAIN_MESSAGE);
                   /* JOptionPane.showMessageDialog(null,"The Product Name is:"+productName, "productName"
                   ,"\n","The Product Id is "+productId,"Product ID"
                        ,"\n","The Unit Price is"+unitPrice,"Unit Price"
                             ,"\n","The Units In Stock is"+unitStock,"UnitStock"
                                  ,"\n","The Product Value is"+productValue, "productValue"
                                       ,"\n","The Restocking Fee is "+reStockfee,"Restock Fee"
                                            ,"\n","The Inventory Value is"+inventoryValue,"Inventory Value"
                                                 ,"\n","The Inventory Restock Fee is"+reStockfee,"Restock Fee"
                                                      ,"\n",JOptionPane.PLAIN_MESSAGE);*/
              //Product products[] = new Product[100];
                   products[i] = new Product();
                   products[i].setitem(item);
                   products[i].setname(name);
                   products[i].setprice(price);
                   products[i].setstock(stock);
                   products[i].setpValue(sum);
                   products[i].setreStkfee(reStkfee);
                   iValue += sum + products[i].getreStkfee();
    public void displayProductInfo()
    { /*Initialization of the variable total inventory value*/
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
    for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
              Product product = products[i];
              if(product==null)
              System.out.println(products[i]);
                   break;
         System.out.printf("product name: %s\n ", product.getname());
         System.out.printf("product ID: %s \n", product.getitem());
         System.out.printf("Unit Price: %s \n", moneyFormat.format(product.getprice()));
         System.out.printf("units in Stock: %s \n", product.getstock());
         System.out.printf("Total product Value: %s \n", moneyFormat.format(product.getpValue()));
         System.out.printf("Restocking fee: %s \n", moneyFormat.format(product.getreStkfee()));
         System.out.printf("Inventory Value: %s \n", iValue);
    }/*Beginning of method main*/
    public static void main(String[] args)
    {/*Message*/
         /*Means for retrieving and storing new data input into inventory program*/
    InventorySystem6 JTableImageCreator = new InventorySystem6();
    JTableImageCreator.displayProductInfo();
    JTableImageCreator.inputProductInfo();
    class Product
    /*Declaration of and default value of specified variables*/
    //private Product products[] = new Product[100];
    private String item;
    String name;
    private double stock;
    private double price;
    private double pValue;
    private double reStkfee;
    //private String productNames[] = new String[1000]; //declaration of array "productNames" to store Product Names
    private double iValue;
    /*method defining the get and set values of each individual variable*/
    public String getname()
    {/*Mean for storing and retrieving input of name*/
    return name;
    }/*Means for setting the product name*/
    public void setname(String name)
    {/*null pointer argument exception defining metod for obtainng product name*/
    this.name = name;
    }/*Means for getting the units identifcation number inputted by the user*/
    public String getitem()
    {/*Means for returning the user input*/
    return item;
    }/*Means for setting the units identifcation */
    public void setitem(String item)
    {/*null pointer argument exception for setting the product identification number*/
    this.item = item;
    }/*Means for getting the units value input*/
    public double getstock()
    {/*Means for returning the variable of the units*/
    return stock;
    }/*Means for setting the units value*/
    public void setstock(double stock)
    this.stock = stock;
    public double getprice()
    {/*Means for returning the dollar value of the price of the unit(s)*/
    return price;
    }/*Means for setting and requesting user to input + dollar amt*/
    public void setprice(double price)
    this.price = price ;
    }/*Means for setting the value of the total product value*/
    public void setpValue(double pValue)
    this.pValue = pValue+(price*stock);
    }/*Means for getting the value of the product*/
    public double getpValue()
    {/*Means for returning the value*/
         return pValue;
    }/*Means for getting the TtlInventoryValue of products entered*/
    public void setiValue(double iValue)
    {/*Condition Statement*/
              this.iValue=iValue;
    public double getiValue()
              return iValue;
    public void setreStkfee(double reStkfee)
         this.reStkfee=stock*price*1.05;
    /*Means for setting restockin fee of the total products*/
    public double getreStkfee()
    {/*Means for calculating the restocking fee of each products units nStock*/
                   return reStkfee;
    }/*Method for string the elements in [i] for display*/
    public String toString()
         {/*Means for returning defined string of elements in [i]*/
              return "Product{" +
    "item="+ item +
    ", name="+ name +
    ", stock="+ stock +
    ", price="+price +
    ", pValue="+pValue +
    ", reStkfee="+ reStkfee +
    ", iValue="+iValue+     
    }/*End set and get method*/
    }/*End of class Product*/
    /*Delcaration of the class type sortproductNames*/                    
    class sortproductNames extends Product
    {/*Declaration of the variable productName*/
    protected String name;
    /*Means for setting and getting values of the variable productName*/
    public void setname(String name)
    this.name = name;
    public String getname()
    return name;
    public int compareTo(Object object)
    { // for sorting by product name
    Product anotherProduct = (Product) object;
    return name.compareTo( anotherProduct.name);
                   g.drawImage(image,0,0,200,50,0,0,image.getWidth(null), image.getHeight(null),null);
              else;
                   g.drawString("O2K", 10,10);
    * @(#)InventoryGUIFrame.java
    * @author
    * @version 1.00 2008/2/2
    package components;
    import java.io.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.imagio.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    * FormattedTextFieldDemo.java requires no other files.
    * It implements a mortgage calculator that uses four
    * JFormattedTextFields.
    public class InventoryGUIPanelFrameTextArea extends JFrame
    String productName;
    String itemNumber;
    double unitPrice;
    double unitStock;
    //Labels to identify the fields
    private JLabel productNamelabel;
    private JLabel itemNumberlabel;
    private JLabel unitPricelabel;
    private JLabel unitStocklabel;
    //Fields for data Entry     
    private JTextField productNameField;
    private JTextField itemNumberField;
    private JTextField unitPriceField;
    private     JTextField unitStockField;
    private Product[] products;
    private int unitStock;
    private int currentIndex=0;
    //Adding the JButtons
    JButton firstButton;
    JButton nextButton;
    JButton previousButton;
    JButton searchButton;
    JButton addButton;
    JButton deleteButton;
    JButton saveButton;
    //Constructor          
    public InventoryGUIPanelFrameTextArea()
    super("Welcome To The Inventory Program");
    this.products = products;
    this.numOfProducts = products;
    JFrame JPanel = new JFrame();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new GridLayout());
    showLogo();
    showLabels();
    showInputFields();
    showButtons();
    public void showLogo()
    O2K myLogo = new O2K();
    this.add(myLogo);
    public void showLabels()
    JPanel panel = new JPanel();
    panel.add(new JLabel("PRODUCT NAME"));
    panel.add(new JLabel("ITEM NUMBER"));
    panel.add(new JLabel("UNIT PRICE"));
    panel.add(new JLabel("UNITS IN STOCK"));
    this.add(panel);
    public void showInputFields()
    itemNumber =new JTextField(5);
    itemNumber.setEditable(false);
    productName= new JTextField(10);
    productName.setEditable(false);
    unitPrice= new JTextField(5);
    unitPrice.setEditable(false);
    unitStock = new JTextField(10);
    unitStock.setEditable(false);
    panel.setEditable(false);
    panel.add(itemNumber);
    panel.add(productName);
    panel.add(unitPrice);
    panel.add(unitStock);
    this.add(panel);
    public void showButtons()
    JPanel panel = new JPanel();
    first = new JButton("First");
    next = new JButton("Next");
    previous = new JButton("Previous");
    add = new JButton ("Add");
    delete = new JButton ("Delete");
    search = new JButton ("Search");
    save = new JButton ("Save");
    panel.add(first);
    panel.add(next);
    panel.add(previous);
    panel.add(add);
    panel.add(delete);
    panel.add(search);
    panel.add(save);
    panel.add(this);
    ButtonActionHandler handler = new ButtonActionHandler();
    first.addActionListener(handler);
    next.addActionListener(handler);
    previous.addActionListener(handler);
    add.addActionListener(handler);
    delete.addActionListener(handler);
    search.addActionListener(handler);
    save.addActinListener(handler);
    this.add(panel);
    setFields(0);
    protected void paintComponent (Graphics g)
    public void setFields(int i)
    setItemNumber(i);
    setProductName(i);
    setUnitPrice(i);
    setUnitStock(i);
    public void setItemNumber( int i)
    itemNumber.setText(products[i].getItemNumber());
    public void setProductName(int i)
    productname.setText(products[i].getProductName());
    public void setUnitPrice( int i)
    unitPrice.setText(String.valueOf(products[i].getunitPrice()));
    public void setUnitStock(int i)
    unitStock.setText(String.valueOf(products[i].getunitStock()));
    private class ButtonActionHandler implements ActionListener
    public void actionPerformed(ActionEvent event)
    if(event.getSource()==first)
    currentIndex=0;
    setFields(currentIndex);
    else if(event.getSource()==next)
    currentIndex++;
    if(currentIndex==unitStock);
    currentIndex--;
    setFields(currentIndex);
    else if (event.getSource()==previous)
    currentIndex--;
    if(curentIndex < 0)
    currentIndex=0;
    setFields(currentIndex);
    else if(event.getSource()==last)
    currentIndex = unitStock -1;
    setFields(currentIndex);
    else if(event.getSource()==add)
    currentIndex = productName ++;
    setFields(currentIndex);
    else if(event.getSource()==delete)
    currentIndex= productName -1;
    setFields(currentIndex);
    else if (event.getSource()==search)
    currentIndex=productName ++;
    setFields(currentIndex);
    else if (event.getSource()==save)
    currentIndex=productName ++;
    setFields(currentIndex);
    public static void main(String args[])
    JFrame mainFrame = new JFrame();
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setSize(400,300);
    mainFrame.setVisible(true);
    class InventorySystem6
    {     /*Declaration of products[] and the maximum storing capacity*/
    private Product products[] = new Product[MAX_NUM_OF_PRODUCTS];
    /*Prompts user to make another selection or exit program*/
    private static final String STOP_COMMAND = "stop";
         /*parameters defining maximun numbers of products available for storing in [i]*/
    private static final int MAX_NUM_OF_PRODUCTS = 100;
    /*Declaration of the variables */
    String name;
    String item;
    double stock;
    double price;
    double reStkfee=1.05;
    double pValue;
    double iValue;
    public InventorySystem6()
         /*Empty Constructor*/
    }/*Beginning of product input by the user*/
    public void inputProductInfo()
    {     /*Declaration of currency format*/     
                   DecimalFormat Currency = new DecimalFormat();
                   Scanner input = new Scanner(System.in);
                   /*Beginning of the Loop*/
                   JOptionPane.showMessageDialog(null,"Welcome to the Inventory Program\n","Welcome to the Inventory Program\n",
                   JOptionPane.PLAIN_MESSAGE);               
                   for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
                   name = JOptionPane.showInputDialog( "What is the Product Name? ");
                   if(name.equalsIgnoreCase("stop"))
                   break;
         String item = JOptionPane.showInputDialog("Enter the products ID");
         String priceStr =JOptionPane.showInputDialog("Enter the products price");
         double price=Double.parseDouble(priceStr);
                   String stockStr=JOptionPane.showInputDialog("Enter the units in stock " );
                   double stock = Double.parseDouble(stockStr);          
                   double sum=price*stock;
              JOptionPane.showMessageDialog(null,"The product value is:"+sum, "pValue",
              JOptionPane.PLAIN_MESSAGE);
                   /* JOptionPane.showMessageDialog(null,"The Product Name is:"+productName, "productName"
                   ,"\n","The Product Id is "+productId,"Product ID"
                        ,"\n","The Unit Price is"+unitPrice,"Unit Price"
                             ,"\n","The Units In Stock is"+unitStock,"UnitStock"
                                  ,"\n","The Product Value is"+productValue, "productValue"
                                       ,"\n","The Restocking Fee is "+reStockfee,"Restock Fee"
                                            ,"\n","The Inventory Value is"+inventoryValue,"Inventory Value"
                                                 ,"\n","The Inventory Restock Fee is"+reStockfee,"Restock Fee"
                                                      ,"\n",JOptionPane.PLAIN_MESSAGE);*/
              //Product products[] = new Product[100];
                   products[i] = new Product();
                   products[i].setItemNumber(itemNumber);
                   products[i].setPrdocutName(productName);
                   products[i].setUnitPrice(unitPrice);
                   products[i].setUnitStock(unitStock);
                   products[i].setProductValue(sum);
                   products[i].setReStkfee(reStkfee);
                   inventoryValue += sum + products[i].getreStkfee();
    public void displayProductInfo()
    { /*Initialization of the variable total inventory value*/
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
    for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
              Product product = products[i];
              if(product==null)
              System.out.println(products[i]);
                   break;
         System.out.printf("product name: %s\n ", product.getproductName());
         System.out.printf("product ID: %s \n", product.getitemNumber());
         System.out.printf("Unit Price: %s \n", moneyFormat.format(product.getunitPrice()));
         System.out.printf("units in Stock: %s \n", product.getunitStock());
         System.out.printf("Total product Value: %s \n", moneyFormat.format(product.getproductValue()));
         System.out.printf("Restocking fee: %s \n", moneyFormat.format(product.getreStkfee()));
         System.out.printf("Inventory Value: %s \n", inventoryValue);
    }/*Beginning of method main*/
    public static void main(String[] args)
    {/*Message*/
         /*Means for retrieving and storing new data input into inventory program*/
    InventorySystem6 JTableImageCreator = new InventorySystem6();
    JTableImageCreator.displayProductInfo();
    JTableImageCreator.inputProductInfo();
    class Product
    /*Declaration of and default value of specified variables*/
    //private Product products[] = new Product[100];
    protected String itemNumber;
    protected String prodcutname;
    protected double unitStock;
    protected double unitPrice;
    protected double productValue;
    protected double reStkfee;
    protected double inventoryValue;
    //private String productNames[] = new String[1000]; //declaration of array "productNames" to store Product Names
    /*method defining the get and set values of each individual variable*/
    public String getproductName()
    {/*Mean for storing and retrieving input of name*/
    return productName;
    }/*Means for setting the product name*/
    public void setProductName(String productName)
    {/*null pointer argument exception defining metod for obtainng product name*/
    this.productName = ProductName;
    }/*Means for getting the units identifcation number inputted by the user*/
    public String getitemNumber()
    {/*Means for returning the user input*/
    return itemNumber;
    }/*Means for setting the units identifcation */
    public void setItemNumber(String itemNumber)
    {/*null pointer argument exception for setting the product identification number*/
    this.itemNumber = itemNumber;
    }/*Means for getting the units value input*/
    public double getunitStock()
    {/*Means for returning the variable of the units*/
    return unitStock;
    }/*Means for setting the units value*/
    public void setUnitStock(double unitStock)
    this.unitStock = unitStock;
    public double getunitPrice()
    {/*Means for returning the dollar value of the price of the unit(s)*/
    return unitPrice;
    }/*Means for setting and requesting user to input + dollar amt*/
    public void setUnitPrice(double unitPrice)
    this.unitPrice = unitPrice ;
    }/*Means for setting the value of the total product value*/
    public void setProductValue(double prodcutValue)
    this.prodcutValue = unitPrice*unitStock;
    }/*Means for getting the value of the product*/
    public double getproductValue()
    {/*Means for returning the value*/
         return productValue;
    }/*Means for getting the TtlInventoryValue of products entered*/
    public void setInvetnoryValue(double invetnoryValue)
    {/*Condition Statement*/
              this.inventoryValue=inventoryValue;
    public double getinvetotyValue()
              return productValue;
    public void setReStkfee(double reStkfee)
         this.reStkfee=stock*price*1.05;
    /*Means for setting restockin fee of the total products*/
    public double getreStkfee()
    {/*Means for calculating the restocking fee of each products units nStock*/
                   return reStkfee;
    }/*Method for string the elements in [i] for display*/
    public String toString()
         {/*Means for returning defined string of elements in [i]*/
              return "Product{" +
    "itemNumber="+ itemNumber +
    ", productName="+ productName +
    ", unitStock="+ unitStock +
    ", unitPrice="+unitPrice +
    ", productValue="+prodcutValue +
    ", reStkfee="+ reStkfee +
    ", inventoryValue="+inventoryValue+     
    }/*End set and get method*/
    }/*End of class Product*/
    /*Delcaration of the class type sortproductNames*/                    
    class sortproductNames extends Product
    {/*Declaration of the variable productName*/
    protected String name;
    /*Means for setting and getting values of the variable productName*/
    public void setProdcutName(String productName)
    this.productName = productName;
    public String getproductName()
    return productName;
    public int compareTo(Object object)
    { // for sorting by product name
    Product anotherProduct = (Product) object;
    return productName.compareTo( anotherProduct.productName);
         class myGraphics extends component          
              private BufferedImage image;
              private boolean imageFound = true;
              public myGraphics()
                   super();
                   try
                        image=ImageIO.read(new File("Logo.jpg"));
                   catch(IOException x)
                        x.printStackTrace();
                        imageFound = false;
              public void paint(Graphics g)
                   g.drawImage(image,0,0,200,50,0,0,image.getWidth(null), image.getHeight(null),null);
              else;
                   g.drawString("O2K", 10,10);

  • Strange GUI freezing TrayIcon + PopupMenu, please help

    Can anybody help me ?
    I wrote very simple program demostrating some GUI activities (changing JPanel background color and tray icon). The problem is that my program freez when I popup tray icon menu (right click) ! :(
    I checked it on Windows XP and 2000 on Java 6.0 b105 and u1 b03.
    I also tryed popup menu manually via .show() from new thread, but it still blocks my program GUI.
    Can you just copy & paste this program, run it and tell me behaviour on your computer ???? Thank you very much.
    Maby somebody know what I am doing wrong and how to use PopupMenu without blocking other GUI operations ???
    //====================================
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class IsTrayIconMenuBlocking3
            public static void main( String[] args ) throws Exception
                    // --- JFrame & JPanel section
                    final JPanel jp = new JPanel();
                    JFrame jf = new JFrame();
                    jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                    jf.add( jp );
                    jf.setSize( 300 , 300 );
                    jf.setVisible( true );
                    // --- menu item action
                    ActionListener itemExitAction = new ActionListener()
                            public void actionPerformed( ActionEvent e )
                                    System.out.println( "item action: exit" );
                                    System.exit( 0 );
                    // --- popup menu
                    PopupMenu pm = new PopupMenu( "Tray Menu" );
                    MenuItem mi = new MenuItem( "Exit" );
                    mi.addActionListener( itemExitAction);
                    pm.add( mi );
                    // --- system tray & tray icon
                    final TrayIcon ti = new
              TrayIcon( ((ImageIcon)UIManager.getIcon("OptionPane.questionIcon")).getImage() ,"Tray Icon" , pm );
                    SystemTray st = SystemTray.getSystemTray();
                    ti.setImageAutoSize( true );
                    st.add( ti );
                    // --- color & icon changing loop
                    final Image[] trayIcons = new Image[3];
                    trayIcons[0] = ((ImageIcon)UIManager.getIcon("OptionPane.errorIcon")).getImage();
                    trayIcons[1] = ((ImageIcon)UIManager.getIcon("OptionPane.warningIcon")).getImage();
                    trayIcons[2] = ((ImageIcon)UIManager.getIcon("OptionPane.informationIcon")).getImage();
                    Runnable colorChanger = new Runnable()
                            private int counter = 0;
                            private int icon_no = 0;
                            public void run()
                                    System.out.println( "Hello from EDT " + counter++ );
                                    if( jp.getBackground() == Color.RED )
                                            jp.setBackground( Color.BLUE );
                                    else
                                            jp.setBackground( Color.RED );
                                    ti.setImage( trayIcons[icon_no++] );
                                    if( icon_no == trayIcons.length ) icon_no = 0;
                    while( true )
                            javax.swing.SwingUtilities.invokeLater( colorChanger);
                            try{Thread.sleep( 500 );} catch ( Exception e ){}
    //==================================== Once again, thanks !!
    Artur Stanek, PL

    Yes. It happens to me too.
    I have tried using SwingWorker but nothing changes.
    It seems to me that PopupMenu blocks the EDT, try
    to put on you test frame a popup, probably when pop-up
    your gui stops to change colors.
    package test;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class IsTrayIconMenuBlocking3
       public static void main(String[] args) throws Exception
          final JPanel jp = new JPanel();
          JFrame jf = new JFrame();
          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          jf.add(jp);
          jf.setSize(300, 300);
          jf.setVisible(true);
          WorkerTray vTray  = new WorkerTray();
          vTray.execute();
          ColorChanger vColor = new ColorChanger(jp, vTray.get());
          vColor.execute();
    package test;
    import java.awt.Color;
    import java.awt.Image;
    import java.awt.TrayIcon;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
    import javax.swing.UIManager;
    public class ColorChanger extends SwingWorker<Boolean, Void>
       JPanel      jp;
       TrayIcon    ti;
       private int counter   = 0;
       private int icon_no   = 0;
       Image[]     trayIcons = new Image[3];
       public ColorChanger(JPanel aPanel, TrayIcon anIcon)
          jp = aPanel;
          ti = anIcon;
          trayIcons[0] = ((ImageIcon) UIManager.getIcon("OptionPane.errorIcon"))
                .getImage();
          trayIcons[1] = ((ImageIcon) UIManager
                .getIcon("OptionPane.warningIcon")).getImage();
          trayIcons[2] = ((ImageIcon) UIManager
                .getIcon("OptionPane.informationIcon")).getImage();
       @Override
       protected Boolean doInBackground() throws Exception
          boolean vCicle = true;
          while (vCicle)
             System.out.println("Hello from EDT " + counter++);
             if (jp.getBackground() == Color.RED)
                SwingUtilities.invokeLater(new Runnable()
                   public void run()
                      jp.setBackground(Color.BLUE);
             else
                SwingUtilities.invokeLater(new Runnable()
                   public void run()
                      jp.setBackground(Color.RED);
             ti.setImage(trayIcons[icon_no++]);
             if (icon_no == trayIcons.length)
                icon_no = 0;
             Thread.currentThread().sleep(500);
          return new Boolean(true);
    package test;
    import java.awt.MenuItem;
    import java.awt.PopupMenu;
    import java.awt.SystemTray;
    import java.awt.TrayIcon;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.SwingWorker;
    import javax.swing.UIManager;
    public class WorkerTray extends SwingWorker<TrayIcon, Void>
       TrayIcon wTray;
       public WorkerTray()
       @Override
       protected TrayIcon doInBackground() throws Exception
          PopupMenu pm = new PopupMenu("Tray Menu");
          MenuItem mi = new MenuItem("Exit");
          // mi.addActionListener(itemExitAction);
          pm.add(mi);
          // --- system tray & tray icon
          wTray = new TrayIcon(((ImageIcon) UIManager
                .getIcon("OptionPane.questionIcon")).getImage(), "Tray Icon", pm);
          mi.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent aE)
                      System.out.println("quiquiquiquqi");
                      System.exit(0);
          SystemTray st = SystemTray.getSystemTray();
          wTray.setImageAutoSize(true);
          st.add(wTray);
          return wTray;
    }

  • Problem with JFrame code

    Can anyone say the problem with the attached code. When I run the program, only, maximize, minimize and close options are viewable and nothing else.
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.LineBorder;
    * Created on Mar 24, 2008
    * @author Anand
    public class JBackGroundImageDemo extends JFrame
        Container con = null;
        JPanel panelBgImg;
        public JBackGroundImageDemo()
            setTitle("JBackGroundImageDemo");
            con = getContentPane();
            con.setLayout(null);
            ImageIcon imh = new ImageIcon("aditi.jpg");
            setSize(imh.getIconWidth(), imh.getIconHeight());
            panelBgImg = new JPanel()
                public void paintComponent(Graphics g)
                    Image img = new ImageIcon("aditi.jpg").getImage();
                    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                    setPreferredSize(size);
                    setMinimumSize(size);
                    setMaximumSize(size);
                    setSize(size);
                    setLayout(null);
                    g.drawImage(img, 0, 0, null);
            con.add(panelBgImg);
            panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());
            GridBagLayout layout = new GridBagLayout();
            JPanel panelContent = new JPanel(layout);
            GridBagConstraints gc = new GridBagConstraints();
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 1;
            JLabel label = new JLabel("UserName: ", JLabel.LEFT);                       
            panelContent.add(label, gc);
            gc.gridx = 2;
            gc.gridy = 1;
            JTextField txtName = new JTextField(10);
            panelContent.add(txtName, gc);
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 2;
            gc.gridwidth = 2;
            JButton btn = new JButton("Login");
            panelContent.add(btn, gc);
            panelContent.setBackground(Color.GRAY);
            panelContent.setBorder(new LineBorder(Color.WHITE));
            panelBgImg.add(panelContent);
            panelBgImg.setLayout(new FlowLayout(FlowLayout.CENTER, 150, 200));
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args)
            new JBackGroundImageDemo().setVisible(true);
         Please help.
    Regards,
    Anees

    Here's you a little code example, it works, so take a look at it.
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Junk{
      public Junk(){
      public void makeFrame(){
        JFrame j = new JFrame("Junk");
        Toolkit t = Toolkit.getDefaultToolkit();
        MediaTracker mt = new MediaTracker(j);
        Image img = t.getImage("junk.jpg");
        mt.addImage(img, 0);
        try{
          mt.waitForID(0);
        }catch(InterruptedException e){
          System.out.println("Hey, we were too impatient!");
        myPanel p = new myPanel(img);
        p.setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
        j.add(p);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.pack();
        j.setVisible(true);
      public static void main(String[] args){
        new Junk().makeFrame();
      class myPanel extends JPanel{
        Image img;
        myPanel(Image img){
          this.img = img;
        public void paintComponent(Graphics g){
          g.drawImage(img, 0, 0, this);
    }BTW: your image should be in your project folder.

  • Problem with JFrame, it goes blank

    i
    My problem is with JFrame, when it's carrying operation which takes a bit of time, if somethhing goes on
    top of the frame the frame goes blank, all the components vanished and when the operation is completed the components bacome visible. I dont know why this is happening,. The code is below, since my code is very complicated I am sending some code whcih shows the problem I have, when you press the button it execute's a for loop, whcih takes some time. If you minimize the frame and maximize again, you'll see what I mean.
    Please help!!!
    Many Thanks
    Lilylay
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Frame1 extends JFrame {
    JPanel contentPane;
    JButton jButton2 = new JButton();
    /**Construct the frame*/
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(null);
    this.setSize(new Dimension(407, 289));
    this.setTitle("Frame Title");
    contentPane.setBackground(SystemColor.text);
    contentPane.setForeground(Color.lightGray);
    jButton2.setText("Press me!");
    jButton2.setBounds(new Rectangle(107, 111, 143, 48));
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    jButton2_mousePressed(e);
    contentPane.add(jButton2, null);
    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton2_mousePressed(MouseEvent e) {
    for(int i=0; i<256898; i++){
    for(int j=0; j<5656585; j++){
    System.out.println("hello");
    public static void main(String [] args){
    Frame1 frame=new Frame1();
    frame.show();
    }

    The reason this is happening is because your loop is so intensive that your program doesn't have time to refresh its JFrame. There is no great way to get past this stumbling block without decreasing the efficiency of your code. One possible solution is to call repaint() from within your loop, but of course this slows down your loop.
    Hope that helps

  • Is there a problem with JFrame and window listeners?

    As the subject implies, i'm having a problem with my JFrame window and the window listeners. I believe i have implemented it properly (i copied it from another class that works). Anyway, none of the events are caught and i'm not sure why. Here's the code
    package gcas.gui.plan;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.util.Hashtable;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import gcas.plandata.TaskData;
    import gcas.util.GCASProperties;
    import gcas.gui.planlist.MainPanel;
    * MainFrame extends JPanel and is the main class for the plan details window
    public class MainFrame extends JFrame implements WindowListener
         * the container for this window
        private Container contentPane;
         * a string value containing the name of the plan being viewed
        private String labelText;
         * a string value containing the name of the window (GCAS - plan list)
        private static String title;
         * an instance of JDialog class
        private static MainFrame dialog;
         * hashTable that correlates the task name to its id as found in the
         * plan
        private Hashtable taskNameToId = new Hashtable();
         * an instance of taskSetPane.  This is the current instance of taskSetPane
         * being viewed
        private PlanTaskSet currentPane;
         * instance of TaskData class.  Each instance will hold information on
         * an individual task
        private TaskData taskData;
         * hashTable containing instances of the taskSetPane class
        private Hashtable taskSetPanes = new Hashtable();
         * an instance of the OuterPanel class
        OuterPanel mainPanel;
         * an instance of the ButtonPanel class
        ButtonPanel buttonsPanel;
         * an instance of the LeftPanel class
        LeftPanel leftPanel;
         * an instance of the the GCASProperties class
        GCASProperties gcasProps;
        private static MainFrame thisPlanMain = null;
        private MainPanel planListMain;
         * constructor for MainFrame
         * @param frame the parent frame calling this class
         * @param locationComp the location of the component that initiated the opening of the dialog
         * @param labelText the name of the plan that is being viewed
         * @param title title of window
        private MainFrame(JFrame frame, Component locationComp, String labelText,
                String title)
            super(title);
            gcasProps = GCASProperties.getInstance();
            mainPanel = new OuterPanel(labelText, currentPane,
                    taskNameToId, taskSetPanes);
            leftPanel = mainPanel.getLeftPanel();
            System.out.println("LABLE: " + labelText);
            leftPanel.setMainPanelContents();
            buttonsPanel = new ButtonPanel(labelText, taskSetPanes,
                    taskNameToId, leftPanel);
            contentPane = getContentPane();
            contentPane.add(mainPanel, BorderLayout.CENTER);
            contentPane.add(buttonsPanel, BorderLayout.PAGE_END);
            this.addWindowListener(this);
            this.labelText = labelText;
            pack();
            setLocationRelativeTo(locationComp);
            this.setVisible(true);
            planListMain = MainPanel.getInstance();
            planListMain.setVisible(false);
        public static MainFrame getInstance(JFrame frame, Component locationComp, String labelText,
                String title)
            if (thisPlanMain == null)
                thisPlanMain = new MainFrame(frame, locationComp, labelText,
                        title);
            return thisPlanMain;
        public static MainFrame getDialogObject()
        {   //from the location this is called (ButtonPanel), this will never
            //be null
            return thisPlanMain;
        public static void setABMDDialogNull()
            thisPlanMain = null;
         * returns an instance of MainFrame
         * @return MainFrame instance
        public static MainFrame getDialog()
            return dialog;
         * setter for MainFrame
         * @param aDialog a MainFrame instance
        public static void setDialog(MainFrame aDialog)
            dialog = aDialog;
         * window opened event
         * @param windowEvent the window event passed to this method
        public void windowOpened(WindowEvent windowEvent)
         * The window event when a window is closing
         * @param windowEvent the window event passed to this method
        public void windowClosing(WindowEvent windowEvent)
            gcasProps.storeProperties("PlanList");
            MainPanel abmd = MainPanel.getInstance();
    //        planMain = this.getDialogObject();
    //        if(planMain != null)
    //            planMain.setVisible(false);
    //            abmd.setVisible(true);
    //            planMain.setABMDDialogNull();
            if(this.getDialogObject()!= null)
                abmd.setVisible(true);
                setVisible(false);
                setABMDDialogNull(); 
         * Invoked when the Window is set to be the active Window
         * @param windowEvent the window event passed to this method
        public void windowActivated(WindowEvent windowEvent)
         * Invoked when a window has been closed as the result of calling dispose on the window
         * @param windowEvent the window event passed to this method
        public void windowClosed(WindowEvent windowEvent)
         * Invoked when a Window is no longer the active Window
         * @param windowEvent the window event passed to this method
        public void windowDeactivated(WindowEvent windowEvent)
            System.out.println("HI");
         * Invoked when a window is changed from a minimized to a normal state
         * @param windowEvent the window event passed to this method
        public  void windowDeiconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
           System.out.println("Invoked when a window is changed from a minimized to a normal state.");
         * Invoked when a window is changed from a normal to a minimized state
         * @param windowEvent the window event passed to this method
        public  void windowIconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
    //        System.out.println("Invoked when a window is changed from a normal to a minimized state.");
    }anyone know whats wrong?

    It turned out that my ide was running the old jar and not updating it, so no matter what code i added, it wasn't being seen. Everything should be fine now.

  • Mutlithreading with GUI problem

    hey guys,
    I was working on some Socket programming assignment and encountered an intersting problem.
    i am using Swing for GUI and Threads to communicate with clients.
    My server GUi has a JButton("Start Server") to trigger the Server. or we can say.. it starts accepting connection( SocketObj = ServerSocketObj.accept() )
    problem:
    as soon as i press the only Button(i.e. StartServer Button) on my Server GUI. whole GUI freezes!
    but Server is working... all updates on GUI are missing.. cant repaint components, etc. neither WindowClosing event , setDefaultCloseOperation()) is working.
    i did some research.. found that swing components are not thread safe,
    also found some close answers,, along the lines of.. Event Dispatch Thread, SwingUtilities.invokeLater(Runnable), SwingWorker class , but neither work or maybe i did not implement them properly..
    Attachment contains my code for:
    Server.java : Server class conatins main()
    ServerGUI.java : gui for server.. called from Server Class
    ClientHandler.java : Thread for handling clients.. also called from Serve class
    Cleint.java : simple client to connect to server at localhost
    Any sort of help would be highly obliged.
    thanks in advance.
    - Ravi

    here is the code...
    Server.java
    import java.net.*;
    import java.io.*;
    public class Server {
        private ServerSocket ss;
        private Socket sc;
        public ServerSocket getSs() {
            return ss;
        public void setSs(ServerSocket ss) {
            this.ss = ss;
        public Socket getSc() {
            return sc;
        public void setSc(Socket sc) {
            this.sc = sc;
        public Server() {
            try{
            ss = new ServerSocket(4000);
            }catch(IOException e){e.printStackTrace();}
            startGUI();
        public void startGUI()
            new ServerGUI(this);
        public void getConnection()
            int i = 1;
            try {
                Socket sc = getSc();
                while (true) {
                    sc = getSs().accept();
                    Thread t = new Thread(new ClientHandler(sc,i));
                    t.start();
                    System.out.println("got client " + i);
                    i++;
            } catch (IOException e) {
                e.printStackTrace();
        public static void main(String[] args) {
            new Server();
    }ServerGUI.java
    import java.net.*;
    import java.io.*;
    public class ServerGUI extends javax.swing.JFrame {
         private javax.swing.JButton jButton1;
        Server m;
        public ServerGUI(Server m) {
            initComponents();
            this.m=m;
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(178, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addGap(147, 147, 147))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(93, 93, 93)
                    .addComponent(jButton1)
                    .addContainerGap(184, Short.MAX_VALUE))
            pack();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            m.getConnection();
    }ClientHandler.java
    import java.net.*;
    public class ClientHandler implements Runnable {
        Socket sock;
        int n;
        public ClientHandler(Socket s, int n) {
            sock = s;
            this.n = n;
        public void run() {
            while (true) {
                System.out.println("Client Thread: " + n);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
    }Client.java
    import java.net.*;
    import java.io.*;
    public class Client {
        Socket sc;
        public Client() {
            try{
            sc=new Socket("127.0.0.1",4000);
            System.out.println("got server");
            }catch(UnknownHostException e){e.printStackTrace();}
            catch(IOException e){e.printStackTrace();}
        public static void main(String args[])
            new Client();
    }

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

  • Serious problem with TitledBorder(jPanel)

    I have a serious problem with TitledBorder(jPanel)
    Here, I have two class the first it contains a jTabbedPane ( class_jTabbedPane)qui call the second which contains a jPanel (Ptableau) which contains a jTable in a jPanel with TitledBorder
    The problem that one I carry out the jPanel with the title does not post
    Thank you! of your assistance.
    The source of the example is as follows:
    package jtabbedpane_titledborder;
    import java.awt.*;
    import javax.swing.*;
    public class class_jTabbedPane extends JFrame {
    PTableau PT = new PTableau();
    private JPanel jPanel1 = new JPanel();
    private JPanel jPanel2 = new JPanel();
    private JLabel jLabel3 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private JTabbedPane jTabbedPane1 = new JTabbedPane();
    public class_jTabbedPane() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    this.setSize(new Dimension(540, 515));
    jPanel1.setBackground(Color.lightGray);
    jPanel1.setBorder(BorderFactory.createEtchedBorder());
    jPanel1.setLayout(null);
    jPanel2.setBackground(new Color(27, 85, 135));
    jPanel2.setBorder(BorderFactory.createEtchedBorder());
    jPanel2.setBounds(new Rectangle(8, 7, 515, 47));
    jPanel2.setLayout(null);
    jLabel3.setFont(new java.awt.Font("Serif", 1, 25));
    jLabel3.setText("Consultation circuits");
    jLabel3.setBounds(new Rectangle(12, 12, 280, 27));
    jLabel2.setFont(new java.awt.Font("Serif", 1, 25));
    jLabel2.setForeground(SystemColor.activeCaptionBorder);
    jLabel2.setText("Consultation circuits");
    jLabel2.setBounds(new Rectangle(15, 5, 260, 32));
    jTabbedPane1.setBounds(new Rectangle(8, 62, 515, 450));
    PT.setLayout(null);
    this.getContentPane().add(jPanel1, BorderLayout.CENTER);
    jPanel1.add(jPanel2, null);
    jPanel2.add(jLabel2, null);
    jPanel2.add(jLabel3, null);
    jPanel1.add(jTabbedPane1, null);
    jTabbedPane1.add(PT,"Tableau");
    //jTabbedPane1.add(PA,"Arborescence");
    public static void main(String[] args) {
    class_jTabbedPane Ct = new class_jTabbedPane();
    Ct.setVisible(true);
    package jtabbedpane_titledborder;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.border.TitledBorder.*;
    public class PTableau extends JPanel {
    private JPanel jPanel9 = new JPanel();
    private JPanel jPanel5 = new JPanel();
    TitledBorder titledBorder5;
    TitledBorder titledBorder4;
    private JPanel jPanel4 = new JPanel();
    private JScrollPane jScrollPane2 = new JScrollPane();
    private JTable jTable1 = new JTable(4, 4 );
    private BorderLayout borderLayout1 = new BorderLayout();
    public PTableau() {
    try {
    jbInit();
    catch(Exception ex) {
    ex.printStackTrace();
    void jbInit() throws Exception {
    jPanel9.setBackground(new Color(27, 85, 135));
    jPanel9.setBorder(BorderFactory.createEtchedBorder());
    jPanel9.setBounds(new Rectangle(1, 1, 540, 350));
    jPanel9.setLayout(null);
    this.setLayout(null);
    jPanel5.setBackground(new Color(27, 85, 135));
    jPanel5.setForeground(Color.white);
    jPanel5.setBorder(BorderFactory.createEtchedBorder());
    jPanel5.setBounds(new Rectangle(12, 88, 501, 183));
    jPanel5.setLayout(borderLayout1);
    jPanel5.setBorder(titledBorder5);
    titledBorder5 = new TitledBorder(" Liste des circuits ");
    titledBorder5.setTitleColor(Color.white);
    jPanel4.setBackground(new Color(27, 85, 135));
    jPanel4.setBorder(BorderFactory.createEtchedBorder());
    jPanel4.setBounds(new Rectangle(211, 3, 291, 44));
    jPanel4.setLayout(null);
    jPanel4.setBorder(titledBorder4);
    titledBorder4 = new TitledBorder(" Liste des circuits ");
    jScrollPane2.getViewport().setBackground(Color.white);
    this.add(jPanel9, null);
    jPanel9.add(jPanel4, null);
    jPanel9.add(jPanel5, null);
    jPanel5.add(jScrollPane2, BorderLayout.CENTER);
    jScrollPane2.getViewport().add(jTable1, null);

    Create your border first, then set the panels border. Do this:
    &#91;code&#93;    titledBorder5 = new TitledBorder(" Liste des circuits ");
        titledBorder5.setTitleColor(Color.white);
        jPanel5.setBorder(titledBorder5);
        jPanel4.setBackground(new Color(27, 85, 135));
    //    jPanel4.setBorder(BorderFactory.createEtchedBorder()); // redundant
        titledBorder4 = new TitledBorder(" Liste des circuits ");
        jPanel4.setBorder(titledBorder4);&#91;/code&#93;
    Not this
    &#91;code&#93;    jPanel5.setBorder(titledBorder5);
        titledBorder5 = new TitledBorder(" Liste des circuits ");
        titledBorder5.setTitleColor(Color.white);
        jPanel4.setBackground(new Color(27, 85, 135));
        jPanel4.setBorder(titledBorder4);
        titledBorder4 = new TitledBorder(" Liste des circuits ");&#91;/code&#93;
    You should also use code tags as I have demonstrated above. It makes you code easier to read for the people you are asking to help you. You can read about them under Formatting Help on the page you post on.

Maybe you are looking for

  • Unable to get external application ID

    Hello, Under edit provider registration connection tab, I try to browse for external applications by click on the notepad icon. I got error in the popup window: error: Invalid SQL Statement passed to LOV (WWC-41233) The system failed to retrieve the

  • Poker sites

    I'm trying to learn to play Texas Holdem and have tried several different free sites but have not been able to complete a query. I type in fulltiltpoker.com or pokerstars.net and nothing happens. Does the Mac not support these sites?

  • Select Data "in background" -- Multi-Tasking

    Hi experts, I've got a selection screen I can choose which data the user wants to display. Problem is, that the selection can take a few seconds...so I have this idea: while user enters his selection, SAP should fill a internal table "in the backgrou

  • Hue/Saturation adjustment layer questions

    1. When selecting the  channel, like red and then boosting the saturation, does this mean that it is only boosting saturation to the reds in the image and there is no possibility of it boosting the saturation of greens or yellows that may reside in t

  • Re MRP Views of Materail

    Hi All, Actually we are trying to download all view details of material from MM03 T-code. We need to fetch the value of the fields Planning Materail (<b>PRGRP</b>) and the Planning Plant (<b>PRWRK</b>) for the MRP view in the MM03 Transaction. We tri