JButton Position

Hi guys. I am very new to Java and I am working on my assignment...
I am trying to set the location of a JButton but it seems that the setLocation Method doesnt work...
this is my code...
import java.awt.*;
import java.awt.geom.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.awt.Polygon;
import javax.imageio.ImageIO;
import javax.swing.*;
* @author Donna Ng Wing Yu
public class MP3 {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
MyFrame frame = new MyFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//A frame that contains a panel with drawings
class MyFrame extends JFrame {
public MyFrame() {
setTitle("My First Game in Java!");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
GameComponent component = new GameComponent();
// add panel to frame
add(component);
public static final int DEFAULT_WIDTH = 531;
public static final int DEFAULT_HEIGHT = 460;
//A component
class GameComponent extends JPanel {
     public GameComponent(){
          /*Import the background*/
          String filename = "background.jpg";
          try{
               image = ImageIO.read(new File(filename));
          catch (IOException e){
               e.printStackTrace();
          /*this J Component contains lots of Hexagons*/
          Hexagons = new ArrayList<Hexagons>();
          cx = 120; //x-coordinate of the first hexagon of column 1
          cy = 66; //y-coordinate of the first hexagon of column 1
          //Creating the first column of hexagons
          Color lastColor = null;
          for(int i = 0; i < 8;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the second column of hexagons
          cx +=30;
          cy = 48;
          for(int i = 0; i < 9;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the third column of hexagons
          cx +=30;
          cy = 66;
          for(int i = 0; i < 8;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the fourth column of hexagons
          cx +=30;
          cy = 48;
          for(int i = 0; i < 9;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the fifth column of hexagons
          cx +=30;
          cy = 66;
          for(int i = 0; i < 8;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the sixth column of hexagons
          cx +=30;
          cy = 48;
          for(int i = 0; i < 9;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the seventh column of hexagons
          cx +=30;
          cy = 66;
          for(int i = 0; i < 8;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the eigth column of hexagons
          cx +=30;
          cy = 48;
          for(int i = 0; i < 9;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the ninth column of hexagons
          cx +=30;
          cy = 66;
          for(int i = 0; i < 8;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          lastColor = null;
          //Creating the last column of hexagons
          cx +=30;
          cy = 48;
          for(int i = 0; i < 9;i++){
               Color current = this.RandColorGenerator();
               while(current.equals(lastColor)){
                    current = this.RandColorGenerator();
               Hexagons hex = new Hexagons(cx,cy,current);
               Hexagons.add(hex);
               cy += 36;
               lastColor = current;
          System.out.println(Hexagons.size());
          for(Hexagons hex:Hexagons){
               System.out.println("X: "+ hex.getCentre().getX()+",Y: "+hex.getCentre().getY());
          JButton RotationButton = new JButton(new ImageIcon("right_rotate.jpg"));
          add(RotationButton);
public void paintComponent(Graphics g){
     super.paintComponents(g);
     Graphics2D g2 = (Graphics2D) g;
     /*Insert the background Image*/
     g.drawImage(image, 0, 0, null);
     /*Draw all hexagons and fill the hexagons with colours*/
     for(Hexagons hex :Hexagons){
          g2.setPaint(hex.getColor());
          g2.fill(hex);
          g2.setPaint(Color.BLACK);
          g2.draw(hex);
public Color RandColorGenerator(){
     Random numGen = new Random();
     Color LuckyColor;
     Color[] myColors = {Color.RED, Color.BLUE, Color.ORANGE, Color.GREEN,new Color(186,11,195)};
     return myColors[numGen.nextInt(5)];
private ArrayList<Hexagons> Hexagons;
private Image image;
private int cx ;
private int cy;
class Hexagons extends Polygon{
     public Hexagons(double x, double y, Color color){
          super();
          this.centre = new Point2D.Double(x,y);
          this.color = color;
          for (int i = 0; i < 6; i++)
               this.addPoint((int) (centre.getX() + 20 * Math.cos(i * 2 * Math.PI / 6)),(int) (centre.getY() + 20 * Math.sin(i * 2 * Math.PI / 6)));
     public Color getColor(){
          return this.color;
     public Point2D getCentre(){
          return centre;
     private static final double radius = 20;
     private Point2D centre;
     private Color color;
}

Read the "Welcome to the new home" posting at the top of the forum to learn how to use the "code tags" when posting code. You can then edit your posting to fix the code. Then maybe someone will look at the code.
But first you should read the section from the Swing tutorial on [url http://download.oracle.com/javase/tutorial/uiswing/layout/index.html]Using Layout Managers. There should be no reason to use the setLocation() method.
For more help create a [url http://sscce.org]SSCCE, that demonstrates the incorrect behaviour.

Similar Messages

  • Positioning JButton in a JFrame

    Hello,
    I am having a problem positioning a JButton in a JFrame. All I want to do is to have a JFrame that contains a JButton at location 100,100. I dont know why I've been having trouble with this. I just want something simple, so if anyone can write a small program that extends JFrame as an example for me that would be much appreciated. Thanks for your time everyone

    For component positioning, Java use LayoutManagers which are placement algorithms.
    By default, all components have a layout manager :
    JPanels have a FlowLayout that layout the sub-components like a text document,
    The contentPane of a JFrame has a BorderLayout which divides the screen in five areas (NORTH, SOUTH,EAST, WEST and CENTER).
    If you want an absolute positioning you have to "remove" this layout manager and replace it by an "hidden" layout manager : AbsoluteLayout.
    To do this use :
    frame.getContentPane().setLayout(null);
    After that you can give absolute positions and size to your components which won't be moved or resized.
    I hope this helps,
    Denis

  • Simple layout issue: positioning text atop a JButton image

    (I apologize for the cross-post; I assumed that this forum was for relatively advanced Swing topics, and therefore initially posted this question in the "New to Java Technology" forum.)
    I've got a newbie Swing problem that I just can't seem to figure out. Basically, I'd like to place text for a JButton in a certain location within the image I'm using for the button. If I use the following code:
    String buttonText = MyStringFactory.getString();
    JButton myButton = new JButton(buttonText, new ImageIcon("myimage.png"));
    myButton.setHorizontalTextPosition(SwingConstants.CENTER);
    myButton.setVerticalTextPosition(SwingConstants.CENTER);The text will display within the button, but it will be exactly centered atop the image. What I'd like is to have the text displayed on top of the image, but to be left-aligned. So, instead of:
    |        Test        |
    ----------------------I want:
    | Test               |
    ----------------------Where the image behind the word "Test" is the image specified when I created the myButton JButton object. The string can be of varying length and must support various fonts (i.e., simply using a monospaced font and padding on the right-side of the string with spaces isn't an option). In more explicit terms, what I want is a way to center the text vertically with respect to the background image, and place it (the text) X pixels from the left-hand side of the background image.
    I've looked at using OverlayLayout to solve this problem, creating a JButton and a JLabel and placing them both within a JPanel. However, when I do this, the JLabel is always rendered behind the JButton, so I can't see it. Is there any way to specify the z-ordering of objects in a JPanel when using OverlayLayout?
    Or is there a much simpler solution to this (seemingly) simple problem?
    Thanks in advance for any assistance!

    hello guy,
    well, you seem to want your text to be in a very specific position since you mention x pixels.
    i don't think you can tell a JButton where exactly to draw the text and icon.
    if you want to do that, you'll have to create you own button.
    something like that:
    class CustomButton extends JButton {
    String text;
    ImageIcon icon;
    public CustomButton(String text, ImageIcon icon) {
    // only use the default constructor of the JButton
    // and save the text and icon separately
    super();
    this.text = text;
    this.icon = icon;
    // set some preferred size so that the layout
    // manager has some idea of how big your button will be
    this.setPreferredSize(new Dimension(
    icon.getIconWidth(),
    2*icon.getIconHeight()));
    // override paintComponent()
    public void paintComponent(Graphics g) {
    // first call this method in the super class
    // this will draw your button color, outline, borders..
    super.paintComponent(g);
    // now draw your icon whereever you want it on
    // your button
    g.drawImage(icon.getImage(),5,
    getHeight()/2-icon.getIconHeight()/2,null,this);
    // and draw your string.
    // using FontMetrics to get the dimensions of your
    // string will allow it to be independent of
    // font type and size
    g.drawString(text, icon.getIconWidth()+10,
    getHeight()/2+g.getFontMetrics().getAscent()/2);
    hope that helps a bit :)
    cheers, alex.

  • JButton text position without an icon

    Hi,
    I'm trying to set the text on my JButtons to be in the top left corner. I've read many of the topics on JButton text position, but they all assume you have an icon with your text. I want to be able to do it without icons (as my buttons don't need them). I tried using the setHorizontalTextPosition and setVerticalTextPosition methods, but the text is still in the same spot.
    Does anyone have any ideas?
    Message was edited by:
    raardvark

    Hi,
    I'm trying to set the text on my JButtons to be in
    the top left corner. I've read many of the topics on
    JButton text position, but they all assume you have
    an icon with your text. I want to be able to do it
    without icons (as my buttons don't need them). I
    tried using the setHorizontalTextPosition and
    setVerticalTextPosition methods, but the text is
    still in the same spot.
    Does anyone have any ideas?
    Message was edited by:
    raardvarkPut a new border on the button that has some space on the bottom and right. Or add insets with the new border.

  • Interchange positions of jbutton inside jpanel

    Hi Friends,
    I'm trying interchange the position of JButtons inside a JPanel and between the Jpanels.
    I'm unable to find the exact releasing positions.
    can anyone help me telling the exact procedure .
    here is the code
    Container con = jb.getParent();     
         con.remove(jb);
    insertPosition2 = con.getComponentZOrder((Container)jb);
    if(con.getComponentCount() == insertPosition2)
                             con.add(jb);
                        else
                             con.add(jb,insertPosition2);
    thanx,
    Sunil.

    I've never tried this myself, but the documentation for Container#getComponentZOrder says:
    The higher a component is in the z-order hierarchy, the lower its index.
    Maybe you could try withinsertPosition2 = con.getComponentZOrder((Container)jb);In any case, the correct approach to this kind of troubleshooting is to insert System.out.println statements in between the lines posted so you can observe whether your assumptions about the values the methods return are correct ones.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    If you require further help, please post a SSCCE
    db

  • Icon Position in JButton

    I have an application wherein I am adding imageicons to Jbuttons dynamically. By defualt the icon is shown after the button text. How do i set it in such a way that the Icon appears befire the jbutton text

    The icons appear to the left of the text for me by default. This would be for the default left to right orientation.
    If you want to change the alignment, then read the API. There is a method that allows you to determine the horizontal placement of the text with respect to the icon.

  • JButton help, icon +text position

    Hi, is it possible to have JButton with icon on far left and text between the icon and far right hand side?

    Yo can do it by using the setHorizontalTextPosition() method.
    here is one example
    import java.awt.*;//Frame
    import javax.swing.*;
    public class Test extends JFrame
         public Test()//Constructer. Creates the frame
              JButton bt = new JButton("Done", new ImageIcon("image.gif"));
              bt.setHorizontalTextPosition(AbstractButton.LEFT);
              setBounds(300,300,300,300);
              getContentPane().setLayout(new FlowLayout());
              getContentPane().add(bt);
              setVisible(true);//shows on the screen
         public static void main(String[] args)
              new Test();//Creates a new Instance of our class
    }

  • How do i use jbutton for mutiple frames(2frames)???

    im an creating a movie database program and i have a problem with the jButtons on my second frame i dont know how to make them work when clicked on. i managed to make the jButtons work on my first frame but not on the second....
    here is that code so far----
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    * real2.java
    * Created on December 7, 2007, 9:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author J
    public class real2 extends JPanel  implements ActionListener{
        private JButton addnew;
        private JButton help;
        private JButton exit;
        private JFrame frame1;
        private JButton save;
        private JButton cancel;
        private JButton save2;
        private JLabel moviename;
        private JTextField moviename2;
        private JLabel director;
        private JTextField director2;
        private JLabel year;
        private JTextField year2;
        private JLabel genre;
        private JTextField genre2;
        private JLabel plot;
        private JTextField plot2;
        private JLabel rating;
        private JTextField rating2;
        /** Creates a new instance of real2 */
        public real2() {
            super(new GridBagLayout());
            //Create the Buttons.
            addnew = new JButton("Add New");
            addnew.addActionListener(this);
            addnew.setMnemonic(KeyEvent.VK_E);
            addnew.setActionCommand("Add New");
            help = new JButton("Help");
            help.addActionListener(this);
            help.setActionCommand("Help");
            exit = new JButton("Exit");
            exit.addActionListener(this);
            exit.setActionCommand("Exit");
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(600, 100));
            table.setFillsViewportHeight(true);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 1;
            c.gridx = 0;
            c.gridy = 1;
            add(addnew, c);
            c.gridx = 0;
            c.gridy = 2;
            add(help, c);
            c.gridx = 0;
            c.gridy = 3;
            add(exit, c);
        public static void addComponentsToPane(Container pane){
            pane.setLayout(null);
            //creating the components for the new frame
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            JButton cancel = new JButton("Cancel");
            JLabel moviename= new JLabel("Movie Name");
            JTextField moviename2 = new JTextField(8);
            JLabel director = new JLabel("Director");
            JTextField director2 = new JTextField(8);
            JLabel genre = new JLabel("Genre");
            JTextField genre2 = new JTextField(8);
            JLabel year = new JLabel("year");
            JTextField year2 = new JTextField(8);
            JLabel plot = new JLabel("Plot");
            JTextField plot2 = new JTextField(8);
            JLabel rating = new JLabel("Rating(of 10)");
            JTextField rating2 = new JTextField(8);
            //adding components to new frame
            pane.add(save);
            pane.add(save2);
            pane.add(cancel);
            pane.add(moviename);
            pane.add(moviename2);
            pane.add(director);
            pane.add(director2);
            pane.add(genre);
            pane.add(genre2);
            pane.add(year);
            pane.add(year2);
            pane.add(plot);
            pane.add(plot2);
            pane.add(rating);
            pane.add(rating2);
            //setting positions of components for new frame
                Insets insets = pane.getInsets();
                Dimension size = save.getPreferredSize();
                save.setBounds(100 , 50 ,
                         size.width, size.height);
                 size = save2.getPreferredSize();
                save2.setBounds(200 , 50 ,
                         size.width, size.height);
                 size = cancel.getPreferredSize();
                cancel.setBounds(400 , 50 ,
                         size.width, size.height);
                 size = moviename.getPreferredSize();
                moviename.setBounds(100 , 100 ,
                         size.width, size.height);
                size = moviename2.getPreferredSize();
                moviename2.setBounds(200 , 100 ,
                         size.width, size.height);
                 size = director.getPreferredSize();
                director.setBounds(100, 150 ,
                         size.width, size.height);
                 size = director2.getPreferredSize();
                director2.setBounds(200 , 150 ,
                         size.width, size.height);
                size = genre.getPreferredSize();
                genre.setBounds(100 , 200 ,
                         size.width, size.height);
                 size = genre2.getPreferredSize();
                genre2.setBounds(200 , 200 ,
                         size.width, size.height);
                 size = year.getPreferredSize();
                year.setBounds(100 , 250 ,
                         size.width, size.height);
                size = year2.getPreferredSize();
                year2.setBounds(200 , 250 ,
                         size.width, size.height);
                 size = plot.getPreferredSize();
                plot.setBounds(100 , 300 ,
                         size.width, size.height);
                 size = plot2.getPreferredSize();
                plot2.setBounds(200 , 300 ,
                         size.width, size.height);
                size = rating.getPreferredSize();
                rating.setBounds(100 , 350 ,
                         size.width, size.height);
                 size = rating2.getPreferredSize();
                rating2.setBounds(200 , 350 ,
                         size.width, size.height);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            frame.add(new real2());
            //Display the window.
            frame.setSize(600, 360);
            frame.setVisible(true);
            frame.pack();
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void actionPerformed(ActionEvent e) {
            if ("Add New".equals(e.getActionCommand())){
               frame1 = new JFrame("add");
               frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
               addComponentsToPane(frame1.getContentPane());
               frame1.setSize(600, 500);
               frame1.setVisible(true);
                //disableing first frame etc:-
                if (frame1.isShowing()){
                addnew.setEnabled(false);
                help.setEnabled(false);
                exit.setEnabled(true);
                frame1.setVisible(true);
               }else{
                addnew.setEnabled(true);
                help.setEnabled(true);
                exit.setEnabled(true);           
            if ("Exit".equals(e.getActionCommand())){
                System.exit(0);
            if ("Save".equals(e.getActionCommand())){
                // whatever i ask it to do it wont for example---
                help.setEnabled(true);
            if ("Save" == e.getSource()) {
                //i tried this way too but it dint work here either
                help.setEnabled(true);
    }so if someone could help me by either telling me what to type or by replacing what iv done wrong that would be great thanks...

    (1)Java class name should begin with a capital letter. See: http://java.sun.com/docs/codeconv/
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            // ... etc. ...(2)Don't redeclare class members in a method as its local variable. Your class members become eternally null, a hellish null.
    how to make them work when clicked on(3)Add action listener to them.

  • IMAGE NOT DISPLAYED OVER JButton ON JDialog

    Hi,
    I am trying to display an image over a JButton inside a JDialog(pops up on button click from an applet). But it is invisible. But I am sure that it is drawn on the ContentPane since when i click partially/half at the position
    of the JButton I could see the JButton with the image. Actualy I am resizing the JDialog since I have two buttons, one to minimise and the other two maximise the size of the JDailog.
    All the buttons are in place but not visible neither at the first place nor when the JDialog is resized.
    The code is as follows:
    package com.dataworld.gis;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class PrintThisPolygon extends JDialog {
         protected Image image;
         protected JButton print;
         protected JButton resize;
         protected JButton desize;
         private int pX=0, pY=0, pWidth=0, pHeight=0;
         public PrintThisPolygon(JFrame parent, Viewer viewer) {
              super(parent, "Print Polygon", true);
              this.setModal(false);
              getContentPane().setLayout(null);
              image = this.viewer.getScreenBuffer();
              pane = new Panel();
              print = new JButton("print", new ImageIcon("images/print.gif"));
              print.setBounds(0,5,50,20);
              print.setEnabled(true);
              print.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        print();
              resize = new JButton("+", new ImageIcon("images/print.gif"));
              resize.setBounds(55,5,50, 20);
              resize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizePlus();
              desize = new JButton("-", new ImageIcon("images/print.gif"));
              desize.setBounds(105,5,50, 20);
              desize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizeMinus();
              getContentPane().add(print);
              getContentPane().add(resize);
              getContentPane().add(desize);
    public String getAppletInfo() {
         return "Identify Polygon\n"
    public void paint(Graphics g){
         System.out.println("Paint : pX " + pX + " pY :" + pY);
         g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
    protected void print() {
         ImagePrint sp = new ImagePrint(this.viewer);
    public void resizeMinus(){
         repaint();
    public void resizePlus(){
         repaint();
    Can anybody has any clue. Can anybody help me out.
    Thanx

    I added resize code for those buttons and ended up with repaint problems too. When you manually resized the window everything was fine again. After a bit of digging around I found you need to call validate on the dialog and then things work.
    IL,
    There is the new scaling version of the code I modified above:package forum.com.dataworld.gis;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class PanelPaintFrame extends JFrame {
         public static void main(String[] args) {
              PanelPaintFrame frame = new PanelPaintFrame ();
              frame.setVisible (true);
         public PanelPaintFrame ()  {
              setBounds (100, 100, 600, 600);
              setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JButton showPrintDialogButton = new JButton ("Show Print Dialog...");
              JPanel buttonPanel = new JPanel ();
              buttonPanel.add (showPrintDialogButton);
              getContentPane ().add (buttonPanel);
              showPrintDialogButton.addActionListener (new ActionListener ()  {
                   public void actionPerformed (ActionEvent e)  {
                        PrintThisPolygon printDialog = new PrintThisPolygon (PanelPaintFrame.this);
                        printDialog.show();
              pack ();
         public class PrintThisPolygon extends JDialog {
              protected ImageIcon myOrigonalImage = null;
              protected Image image;
              protected JButton print;
              protected JButton resize;
              protected JButton desize;
              private int pX=0, pY=0, pWidth=0, pHeight=0;
              JPanel pane = null;
              public PrintThisPolygon(JFrame parent/*, Viewer viewer*/) {
                   super(parent, "Print Polygon", true);
    //               this.setModal(false);
                   getContentPane().setLayout(null);
                   //  Substitute my own image
                   myOrigonalImage = new ImageIcon (PrintThisPolygon.class.getResource ("images/MyCoolImage.jpg"));
                   //  Start off full size
                   pWidth = myOrigonalImage.getIconWidth();
                   pHeight = myOrigonalImage.getIconHeight();
                   image = myOrigonalImage.getImage ().getScaledInstance(pWidth, pHeight, Image.SCALE_DEFAULT);
    //               image = this.viewer.getScreenBuffer();
    //               pane = new Panel();
                   //  Create a JPanel to draw the image
                   pane = new JPanel(){
                        protected void paintComponent(Graphics g)  {
                             System.out.println("Paint : pX " + pX + " pY :" + pY);
                             g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
                   pane.setBounds (0, 0, pWidth, pHeight);
                   //  Load the button image using a URL
                   print = new JButton("print", new ImageIcon(PrintThisPolygon.class.getResource ("images/print.gif")));
    //               print = new JButton("print", new ImageIcon("images/print.gif"));
                   print.setBounds(0,5,55,20);
                   print.setEnabled(true);
                   print.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             print();
                   resize = new JButton("+", new ImageIcon("images/print.gif"));
                   resize.setBounds(55,5,50, 20);
                   resize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizePlus();
                   desize = new JButton("-", new ImageIcon("images/print.gif"));
                   desize.setBounds(105,5,50, 20);
                   desize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizeMinus();
                   //  Setup a transparent glass panel with no layout manager
                   JPanel glassPanel = new JPanel ();
                   glassPanel.setLayout (null);
                   glassPanel.setOpaque (false);
                   //  Add the image panel to the dialog
                   getContentPane().add(pane);
                   //  Add the buttons to the glass panel
                   glassPanel.add(print);
                   glassPanel.add(resize);
                   glassPanel.add(desize);
                   //  Set our created panel as the glass panel and turn it on
                   setGlassPane (glassPanel);
                   glassPanel.setVisible (true);
                   setBounds (100, 100, pWidth, pHeight);
    //               setBounds (100, 100, 500, 300);
              public String getAppletInfo() {
                   return "Identify Polygon\n";
    //          public void paint(Graphics g){
    //          protected void paintComponent(Graphics g)  {
    //               System.out.println("Paint : pX " + pX + " pY :" + pY);
    //               g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
              protected void print() {
                   //  Pretend to print
    //               ImagePrint sp = new ImagePrint(this.viewer);
                   System.out.println ("Print view...");
              public void resizeMinus(){
                   //  Scale the image down 10%
                   int scaledWidth = pWidth - (int)(pWidth * 0.1);
                   int scaledHeight = pHeight - (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              public void resizePlus(){
                   //  Scale the image up 10%
                   int scaledWidth = pWidth + (int)(pWidth * 0.1);
                   int scaledHeight = pHeight + (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              private void scaleImage (int scaledWidth, int scaledHeight)  {
                   //  Create a new icon for drawing and retrieve its actuall size
                   image = myOrigonalImage.getImage ().getScaledInstance (scaledWidth, scaledHeight, Image.SCALE_DEFAULT);
                   pWidth = scaledWidth;
                   pHeight = scaledHeight;
                   //  Resize
                   setSize (pWidth, pHeight);
                   pane.setSize (pWidth, pHeight);
                   validate();
    }

  • Custom JButton displays properly on Win2K, not under Solaris

    We have an applet that creates a panel of custom JButtons, each of which has a set of associated icons, two of which are "active" and "inactive" (there are also disabled, rollover, etc. icons). At runtime, when a button is clicked, its icon property is set to the "active" one. If another button in the panel is clicked, the first button has its icon property set to the "inactive" one.
    This displays fine when the applet is running on a Win2k machine (with the Java 1.3 plugin under either Netscape 6.2 or IE 5.5, but when we run it on a SunRay connected to a Sun Ultra80 running Solaris 8 with Netscape 6.2 and the Java 1.3 plugin, the "inactive" icon for one particular button is blank - we get a white rectangle - but when we click on the rectangle (or mouseover it), the appropriate icon appears as it should.
    When I specify a different icon to be used (reusing the .gif file from one of the other buttons)I get the same behaviour. When I reorder the buttons in the panel, the same button (now in a different position) still behaves improperly.
    Any thoughts?
    Thanks,

    No solution, but for what it's worth.
    As part of my "diagnosis by trying things out" (NOT "debugging by..." - or at least I don't admit to that :) I created a second instance of the problem button and stuck it in the panel.
    Lo! the new instance had the problem, BUT THE FIRST WAS FINE. I did a few more experiments, and the first-created instance was the one to have problems, while the second is fine, so the current work-around is to make an instance, ignore it (just leave it as a field of the class that builds the panel, but don't add it to the panel), make another instance and use that in the panel.
    My boss is happy, our client is happy (they have a demo using the a group of Sunrays), but I really wish I knew what was going on. I don't THINK that the problem button was the first instance of its class to be created (I'm at home and the thought just came to me) but it's possible and raises some more hypotheses to test.

  • Can I change the Default Position of a JColorChooser Dialog Box???

    I am working on a drawing application where I am using a button that launches a JColorChooser dialog to allow a user to select a color which. I have tied this button to the JColorChooser using the source code below to reset the color based on the user's selection. This all works fine. However, when the JColorChooser comes up, the dialog comes up right in the middle of the drawing area and erases any portion of the drawing that the dialog box overlaps with, which having my luck is more or less right in the middle of the JPanel where I am doing the drawing. My question is can I tell the JColorChooser to come up somewhere else in the user interface by offsetting it from the actual application somehow? I am using a JFrame to add all of these components to (the color choose button and the drawing area) and wonder if there is a way to tell the JColorChooser dialog not to come in the default location. Any help that anybody could provide would be greatly appreciated. Thanks!
    Kevin
    pickColor = new JButton( "Choose Color" );
    pickColor.addActionListener(
    new ActionListener() {
    public void actionPerformed(ActionEvent event)
    color = JColorChooser.showDialog(
    ColorPicker.this, "Choose a color", color);
    if ( color == null )
    currentColor = Color.RED;
    else
    currentColor = color;
    );

    JColorChooser has a method createDialog() that lets you create (rather than
    merely show) a dialog containing your colour chooser.
    If you use this method you can position the dialog wherever you want. The
    dialog inherits the Window methods for positioning - eg
    setLocationRelativeTo(Component c).

  • Why do I get Illegal Component position when I say FlowLayout.CENTER

    The code runs fine if you replace the line
    Jp7.add(submitButton, FlowLayout.CENTER);
    with
    Jp7.add(submitButton);
    I know FlowLayout's default location is CENTER. But when I explicitly say to center the button, it crashes during runtime but compiles fine.
    Whats the reason for this? Is this a bug?
    I am using 1.4.0_03.
    I getthe following error.
    Exception in thread "main" java.lang.IllegalArgumentException: illegal component
    position
    at java.awt.Container.addImpl(Container.java:568)
    at java.awt.Container.add(Container.java:327)
    at Mon2.main(Mon2.java:114)
    ALSO CAN I DO THE SAME WITHOUT USING SO MANY JPANELS?????????????????? I AM NOT NEW TO PROGRAMMING BUT I AM NEW TO GUI PROGRAMMING.
    Thanks in advance.
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Mon2 extends JFrame{
    static long i =0;
    static int jobid = 0;
    static String StartTime = "";
    static String LastReport = "";
    static String FinishTime = "";
    static String Description = "";
    static String job_position = "";
    static String desc ="";
    public static String database = "";
    public static String user = "";
    public static String password = "";
    static int counter = 1;
    static boolean valuesEntered = false;
      JButton jButton1 = new JButton();
      JButton jButton2 = new JButton();
      JButton jButton3 = new JButton();
      BorderLayout borderLayout1 = new BorderLayout();
      JLabel jLabel1 = new JLabel();
    JTextPane jTextArea1 = new JTextPane();
    static JTextField userArea = new JTextField();
    static JPasswordField passArea = new JPasswordField();
    static JTextField databaseArea = new JTextField();     
    static JFrame f = new JFrame();
    static JLabel us = new JLabel ("UserName: ");
    static JLabel pa = new JLabel ("Password: ");
    static JLabel da = new JLabel ("Database: ");
      BorderLayout borderLayout2 = new BorderLayout();
      JPanel jPanel1 = new JPanel();
      JLabel jLabel2 = new JLabel();
         public Mon2() {
        try  {
          jbInit();
        catch (Exception e) {
          e.printStackTrace();
         public static void main(String args[]) {
              System.out.println("Starting Mon2...");
        f.setSize(300,200);
        f.setTitle("Login");
        f.setLocation(250,250);
        f.setResizable(false);
        Panel Jp1 = new Panel (new BorderLayout());
        Panel Jp3 = new Panel (new BorderLayout());
        Jp3.add(us, BorderLayout.NORTH);
        Jp3.add(pa, BorderLayout.CENTER);
        Jp3.add(da, BorderLayout.SOUTH);
        userArea.setEditable(true);
        userArea.setSize(20,20);
        passArea.setEditable(true);
        databaseArea.setEditable(true);
        JButton submitButton = new JButton("Submit");
        JPanel Jp2 = new JPanel (new BorderLayout());
        JPanel Jp4 = new JPanel (new FlowLayout());
        userArea.setPreferredSize(new Dimension(200,21));
        Jp4.add(userArea, FlowLayout.LEFT);
        Jp4.add(us, FlowLayout.LEFT);
        JPanel Jp5 = new JPanel (new FlowLayout());
        passArea.setPreferredSize(new Dimension(200,21));
        Jp5.add(passArea,FlowLayout.LEFT);
        Jp5.add(pa, FlowLayout.LEFT);
        JPanel Jp6 = new JPanel (new FlowLayout());
        databaseArea.setPreferredSize(new Dimension(200,21));
        databaseArea.setText("DWPROD");
        Jp6.add(databaseArea,FlowLayout.LEFT);
        Jp6.add(da, FlowLayout.LEFT);
        Jp1.add(Jp4, BorderLayout.NORTH);
        Jp1.add(Jp5, BorderLayout.CENTER);
        Jp2.add(Jp6, BorderLayout.NORTH);
       JPanel Jp7 = new JPanel(new FlowLayout());
    ///////////////////////////This is  the line//////////////////
    //If you remove the ,FlowLayout.CENTER it works fine.
    //If you leave it like as it is, it will compile but then give runtime error
        Jp7.add(submitButton, FlowLayout.CENTER);
        Jp2.add(Jp7, BorderLayout.SOUTH);
        Jp1.add(Jp2, BorderLayout.SOUTH);
        f.getContentPane().add(Jp1);
        Image img = Toolkit.getDefaultToolkit().getImage("c:\\appletHeader.gif");
        f.setIconImage(img);
        f.setDefaultCloseOperation(3);
        f.setVisible(true);
        f.pack();
         submitButton.resize(75, 30);
        submitButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(ActionEvent e) {
        user = userArea.getText();
        password = passArea.getText();
        database = databaseArea.getText();
        if((user.equals(null) || password.equals(null) || database.equals(null) || user.equals("") || password.equals("") || database.equals(""))){
        valuesEntered = false;
        else{
             valuesEntered = true;
        if(valuesEntered == true){
        f.setVisible(false);
              Mon2 mainFrame = new Mon2();
              mainFrame.setSize(600, 400);
              mainFrame.setTitle("Monitor");
        mainFrame.setLocation(100,200);
        mainFrame.setResizable(false);
        desc = "ERROR! or there are no locked jobs.";
              mainFrame.setVisible(true);
        else{
        JOptionPane.showMessageDialog(null,"Must enter values for UserName, Password and Database", "Value Required",JOptionPane.INFORMATION_MESSAGE);
    //    System.exit(0);
      private void jbInit() throws Exception {
        this.setDefaultCloseOperation(3);
        jButton1.setText("Refresh");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
          jButton1_actionPerformed(e);
        jButton2.setText(" Exit ");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            System.exit(0);
        this.getContentPane().setLayout(borderLayout1);
        jButton3.setText("Clear");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jTextArea1.setText("Click on Refresh to update screen.");
        Panel p = new Panel(new FlowLayout());
        Panel p2 = new Panel (new BorderLayout());
        jLabel1.setText("Monitor for current Job");
        jTextArea1.setPreferredSize(new Dimension(8, 50));
        jTextArea1.setContentType("text/html");
        jTextArea1.setText("");
        jTextArea1.setEditable(false);
        f.setResizable(false);
        f.setTitle("Login");
        jLabel2.setHorizontalTextPosition(SwingConstants.LEFT);
        jLabel2.setText("jLabel2");
        jLabel2.setHorizontalAlignment(SwingConstants.LEFT);
        f.getContentPane().setLayout(borderLayout2);
        jTextArea1.setSize(100,10);
        p.add(jButton1);
        p.add(jButton3);
        p.add(jButton2);
        this.getContentPane().add(jLabel1, BorderLayout.NORTH);
        this.getContentPane().add(jTextArea1, BorderLayout.CENTER);
        p2.add(p, BorderLayout.CENTER);
        this.getContentPane().add(p2, BorderLayout.SOUTH);
        pack();
        f.getContentPane().add(jPanel1, BorderLayout.CENTER);
        jPanel1.add(jLabel2, null);
      void jButton1_actionPerformed(ActionEvent e){
            jTextArea1.setText("Refreshing...");
            long i = 0;
         try{
              jTextArea1.setText("In side try block");
                    Thread.sleep(1000);
                   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                   jTextArea1.setText("DriverManager");
                  Connection conn=
                   DriverManager.getConnection("jdbc:oracle:thin:@machine:1234:"+ database, user, password);
                                                                          jTextArea1.setText("Got COnnection");
                   Statement stmt = conn.createStatement();
                   jTextArea1.setText("Statement Created");
                   ResultSet rs =
                   stmt.executeQuery("select 1, sysdate, sysdate, sysdate, sysdate, sysdate from dual ");
                   jTextArea1.setText("Query Executed");
                   while(rs.next()){
          jobid = rs.getInt(1);
          StartTime = rs.getString(2);
          LastReport = rs.getString(3);
          FinishTime = rs.getString(4);
          Description = rs.getString(5);
          job_position = rs.getString(6);
          desc = "<b>Count: </b>" + counter + "" +
                     "<p><table border = '1'><tr><td><b>JOB ID:      </b></td><td>" + jobid + "</td></tr>" +
                 "<tr><td><b>Start Time:  </b></td><td>" + StartTime + "</td></tr>" +
                 "<tr><td><b>Last Report: </b></td><td>" + LastReport + "</td></tr>" +
                 "<tr><td><b>FinishTime:  </b></td><td>" + FinishTime + "</td></tr>" +
                 "<tr><td><b>Description: </b></td><td>" + Description + "</td></tr>" +
                 "<tr><td><b>Position:    </b></td><td>" + job_position + "</td></tr></table>";
                  counter = counter + 1;
                     rs.close();
                   conn.close();
                    jTextArea1.setText("Sleeping");
                    jTextArea1.setText(desc);
                    desc = "";
              catch (SQLException se){
              jTextArea1.setText(desc + se);
           catch(Exception ee){
                jTextArea1.setText("Exception occured\n\n" + ee);
    }

    Get your basics checked.
    Go to:
    http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/shortcourse.html#whatAreLMs
    And find the heading: FlowLayout Variations
    FlowLayout can be customized at construction time by passing the
    constructor an alignment setting:
    FlowLayout.CENTER (the default)
    FlowLayout.RIGHT
    FlowLayout.LEFT

  • JButtons in JToolbar don't work with JApplet- why?

    I made a JApplet which has a toolbar, populated with burrons that manipulate data from text files. The programs works perfectly when it is not a JApplet. However, once I converted it to a JApplet it does nothing. The code was exactly the same, but, pressing buttons does nothing when it is an applet. here is the complete code;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class CSE extends JApplet implements ActionListener, ItemListener
    //GUI COMPONENTS
    //ToolBar components
    JToolBar mainSelect = new JToolBar("Materials");
    JButton materials;
    String materialNames[] = {"Fur Square", "Bolt of Linen", "Bolt of Damask", "Bolt of Silk", "Glob of Ectoplasm", "Steel Ingot", "Deldrimor Steel Ingot", "Monstrous Claw", "Monstrous Eye", "Monstrous Fang", "Ruby", "Lump of Charcoal", "Obsidian Shard", "Tempered Glass Vial", "Leather Square", "Elonian Leather Square", "Vial of Ink", "Roll of Parchment", "Roll of Vellum", "Spiritwood Plank", "Amber Chunk", "Jadeite Shard"};
    ImageIcon materialIcons;
    //Graphic components
    JDesktopPane mainGraph = new JDesktopPane();
    JPanel dailyGraph = new JPanel();
    JPanel weeklyGraph = new JPanel();
    JPanel finalPrices = new JPanel();
    Box graphs = Box.createHorizontalBox();
    //The Console
    JFrame CSEFrame = new JFrame();
    JSplitPane mainConsoleBackdrop = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    JSplitPane dataOut = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    JTextArea prediction = new JTextArea(10,10);
    JScrollPane predictionScroll;
    Box finalPricesLabels = Box.createVerticalBox();
    Box finalPricesLay = Box.createVerticalBox();
    JLabel finalBuy = new JLabel("Net Buy Price Change: 0.00");
    JLabel finalSell = new JLabel("Net Sell Price Change: 0.00");
    JLabel buySell = new JLabel("We recommend you: N/A");
    JTextArea priceUpdate = new JTextArea(10, 10);
    JTextArea priceUpdateWeekly = new JTextArea(10, 10);
    JScrollPane priceUScrollW;
    JScrollPane priceUScroll;
    JCheckBox weeklySelect = new JCheckBox("To show weekly price changes.", false);
    JCheckBox dailySelect = new JCheckBox("To show daily price changes.", true);
    ButtonGroup dataToShow = new ButtonGroup();
    //COMPONENTS FOR DATE; OBTAINING CORRECT FOLDER
    String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    Calendar calSource = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    int day = calSource.get(Calendar.DAY_OF_MONTH);
    int month = calSource.get(Calendar.MONTH);
    int year = calSource.get(Calendar.YEAR);
    int monthCheck [] = {Calendar.JANUARY, Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL, Calendar.MAY, Calendar.JUNE, Calendar.JULY, Calendar.AUGUST, Calendar.SEPTEMBER, Calendar.OCTOBER, Calendar.NOVEMBER, Calendar.DECEMBER};
    int dayS = day;
    int monthS = month;
    int yearS = year;
    //if there is file found
    boolean proceed = false;
    //int data for analysis
    int buyPrice;
    int currentBuyPrice;
    int sellPrice;
    int currentSellPrice;
    boolean weekly = false;
    //tools for parsing and decoding input
    String inputS = null;
    String s = null;
    Scanner [] week = new Scanner[7];
    Scanner scanner;
    int position = 0;
    //weekly tools
    String weekPos[] = {"Seventh", "Sixth", "Fifth", "Fourth", "Third", "Second", "First"};
    int dayOfWeek = 0; //0 = 7    1 = 6...
                    public JButton getToolBarButton(String s)
                        String imgLoc = "TBar Icons/" +s +".gif";
                        java.net.URL imgURL = CSE.class.getResource(imgLoc);
                        JButton button = new JButton();
                        button.setActionCommand(s);
                        button.setToolTipText(s);
                        button.addActionListener(this);
                        if(imgURL != null)
                            button.setIcon(new ImageIcon(imgURL, s));
                        else
                            button.setText(s);
                            System.err.println("Couldn't find; " +imgLoc);
                        return button;
                        public CSE()
                                   // super("Test CSE");
                                    //CSEFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                    for(int x=0; x<materialNames.length; x++)
                                        materials = getToolBarButton(materialNames[x]);
                                        mainSelect.add(materials);
                                    //checkBoxes
                                    dataToShow.add(weeklySelect);
                                    dataToShow.add(dailySelect);
                                    weeklySelect.addItemListener(this);
                                    dailySelect.addItemListener(this);
                                    // sizes
                                    setSize(850, 850);
                                    //colors and fonts
                                    weeklyGraph.setBackground(new Color(250, 30, 40));
                                    dailyGraph.setBackground(new Color(100, 40, 200));
                                    //text Manip.
                                    prediction.setLineWrap(true);
                                    priceUpdate.setLineWrap(true);
                                    //scrolling
                                    predictionScroll = new JScrollPane(prediction, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    priceUScroll = new JScrollPane(priceUpdate, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    priceUScrollW = new JScrollPane(priceUpdateWeekly, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    //main splitpane config.
                                    mainConsoleBackdrop.setOneTouchExpandable(true);
                                    mainConsoleBackdrop.setResizeWeight(.85);
                                    //placement and Layout
                                    //GraphLayout
                                    graphs.add(Box.createHorizontalStrut(10));
                                    graphs.add(dailyGraph);
                                    graphs.add(Box.createHorizontalStrut(10));
                                    graphs.add(weeklyGraph);
                                    graphs.add(Box.createHorizontalStrut(10));
                                    dataOut.setRightComponent(predictionScroll);
                                    //consoleData layout
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(finalBuy);
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(finalSell);
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(buySell);
                                    finalPricesLay.add(finalPricesLabels);
                                    finalPricesLay.add(Box.createVerticalStrut(10));
                                    finalPricesLay.add(weeklySelect);
                                    finalPricesLay.add(dailySelect);
                                    finalPricesLay.add(priceUScroll);
                                    dataOut.setLeftComponent(finalPricesLay);
                                    mainConsoleBackdrop.setTopComponent(graphs);
                                    mainConsoleBackdrop.setBottomComponent(dataOut);
                                    getContentPane().add(mainConsoleBackdrop);
                                    getContentPane().add(mainSelect, BorderLayout.NORTH);
                                    //visibility
                                   // CSEFrame.setVisible(true);
                                    //return(CSEFrame);
                                        public void actionPerformed(ActionEvent e)
                                            getMonth();
                                            inputS = e.getActionCommand();
                                            FileReader newRead = null;
                                                    try {
                                                           newRead = new FileReader(monthS +"-" +dayS +"-" +yearS +"/" +inputS +".dat");
                                                           proceed = true;
                                                        catch(FileNotFoundException f)
                                                           System.out.println("File not found");
                                                           proceed = false;
                                          if(proceed)
                                          BufferedReader bufferedReader = new BufferedReader(newRead);
                                          scanner  = new Scanner(bufferedReader);
                                          scanner.useDelimiter("\n");
                                         //starts daily analysis
                                          getPrice(scanner);
                                        //starts weekly analysis
                                          weekly(inputS);
                                    public void itemStateChanged(ItemEvent e)
                                        if(weeklySelect.isSelected())
                                        priceUpdateWeekly.setText("");
                                        finalPricesLay.remove(priceUScroll);
                                        finalPricesLay.add(priceUScrollW);
                                        finalPrices.updateUI();
                                        else
                                            priceUpdate.setText("");
                                            finalPricesLay.remove(priceUScrollW);
                                            finalPricesLay.add(priceUScroll);
                                            finalPrices.updateUI();
                                    public void weekly(String inputS)
                                        weekly = true;
                                        for(int x = 0; x < 7; x++)
                                           dateToUse(month, day, year, (x+1));
                                            try
                                                    FileReader weeklySource = new FileReader(monthS +"-" +dayS +"-" +year +"/" +inputS +".dat");
                                                    BufferedReader weeklyBuffer = new BufferedReader(weeklySource);
                                                    week[x] = new Scanner(weeklyBuffer);
                                                    week[x].useDelimiter("\n");
                                                    getPrice(week[x]);
                                             catch(FileNotFoundException f)
                                                JOptionPane.showMessageDialog(this, "No such weekly files- going back;" +(x+1) +"days");
                                        weekly = false;
                                        dateReset();
                                    public void getPrice(Scanner scanner)
                                        while(scanner.hasNextLine())
                                            //puts into string the next scan token
                                            String s = scanner.next();
                                            //takes the scan toke above and puts it into an editable enviroment
                                            String [] data = s.split("\\s");
                                            for(position = 0; position < data.length; position++)
                                                        //Scanner test to make sure loop can finish, otherwise "no such line" error
                                                        if(scanner.hasNextLine()==false)
                                                        scanner.close();
                                                        break;
                                                           /*Starts data orignazation by reading from each perspective field
                                                            * 1 = day
                                                            * 2 = day of month
                                                            * 3 = month
                                                            * 4 = year
                                                           if(position == 0 && weekly == false)
                                                               String dayFromFile = data[position];
                                                                int dayNum = Integer.parseInt(dayFromFile);
                                                              priceUpdate.append(days[dayNum-1] +" ");
                                                           else if(position == 1  && weekly == false )
                                                              priceUpdate.append(data[position] + "/");
                                                           else if(position == 2 && weekly == false)
                                                              priceUpdate.append(data[position] + "/");
                                                            else if(position == 3 && weekly == false)
                                                                priceUpdate.append(data[position] +"\n");
                                                           //if it is in [buy] area, it prints and computes
                                                            else if(position == 7)
                                                                //obtains string for buy price and stores it, then prints it
                                                                String buy = data[position];
                                                            if(weekly == false)
                                                            priceUpdate.append("Buy: " +buy +"\n" );
                                                             //converts buy to string
                                                            currentBuyPrice = Integer.parseInt(buy);
                                                            //eliminates problems caused by no data from server- makes the price 0
                                                            if(currentBuyPrice < 0)
                                                                currentBuyPrice = 0;
                                                            //if it is greater it adds
                                                            if(currentBuyPrice > buyPrice)
                                                                     buyPrice += currentBuyPrice;
                                                            //if it is equal [there is no change] then it does nothing    
                                                            if(currentBuyPrice == buyPrice)
                                                                buyPrice +=0;
                                                            //if there is a drop, it subtracts
                                                               else
                                                                   buyPrice -= currentBuyPrice;
                                                            //if it is in [sell] area, it prints, and resets the position to zero because line is over
                                                            else if(position == 8)
                                                                //puts sell data into string and prints it
                                                                String sell = data[position];
                                                                if(weekly == false)
                                                                priceUpdate.append("Sell: " + sell +"\n");
                                                                //turns sell data into int.
                                                              currentSellPrice = Integer.valueOf(sell).intValue();;
                                                            //gets rid of problems caused by no data on server side- makes it 0 
                                                            if(currentSellPrice < 0)
                                                                currentSellPrice = 0;
                                                            //adds if there is an increase
                                                            if(currentSellPrice > sellPrice)
                                                                     sellPrice += currentSellPrice;
                                                            //does nothing if it is the same    
                                                            if(currentSellPrice == sellPrice)
                                                                sellPrice +=0;
                                                            //subtracts if there is drop
                                                               else
                                                                   sellPrice -= currentSellPrice;
                                                                //further protection against "No such line" and moves it down
                                                               if(scanner.hasNextLine() == true)
                                                                scanner.nextLine();
                                                                //if scanner is finished, prints out all lines
                                                               if(scanner.hasNextLine() == false && weekly == false)
                                                                finalBuy.setText("Net Buy Price Change: "+buyPrice);
                                                                finalSell.setText("Net Sell Price Change: " +sellPrice);
                                                                buyPrice = 0;
                                                                sellPrice = 0;
                                                                position = data.length;
                                                               else if(scanner.hasNextLine() == false && weekly == true)
                                                                   priceUpdateWeekly.append("\n" +weekPos[dayOfWeek] +" day of the week ended with; \nBuy Price;" +buyPrice +"\nSell Price;" +sellPrice);
                                                                   buyPrice = 0;
                                                                   sellPrice = 0;
                                                                   position = data.length;
                                                                   dayOfWeek++;
                                                                   if(dayOfWeek > 6)
                                                                   dayOfWeek = 0;
                                public void getMonth()
                                    for(int x=0; x < monthCheck.length; x++)
                                        if(month == monthCheck[x])
                                              monthS = (x+1);
                                              x = monthCheck.length;
                                 public void dateToUse(int month, int day, int year, int increment)
                                 //set day of source
                                  dayS = (day - increment);
                                //if day of source is less then O then we have moved to another month 
                                if(dayS <= 0)
                                        //checks the difference between how much we have incremented and the day we have started; this tells us how far into the new month we are
                                        int incrementDay = increment - day;
                                        //decrements month
                                        monthS--;
                                        //if month is less then zero, then we have moved into another year and month has become 12
                                        if(monthS <= 0)
                                            yearS--;
                                            monthS = 12;
                                        //the following looks at the current month and if it goes below it assigns the day to the proper ammount of days of the month before minus the days into the month
                                           if(month == 3)
                                               dayS = 28 - incrementDay;
                                           else if(month == 5 || month == 7)
                                               dayS = 29 - incrementDay;
                                           else if(month == 2 || month == 4 || month == 6 || month == 9 || month == 11)
                                               dayS = 31 - incrementDay;
                                            else
                                                dayS = 30 - incrementDay;
                               //resets the source date to the current date once data from the week has been reached
                                public void dateReset()
                                    dayS = day;
                                    monthS = month;
                                    yearS = year;
                     public void init()
                         //JFrame frame = new CSEFrameSet();
                        // this.setContentPane(CSEFrameSet());
                        CSE aCSE = new CSE();
    public static void main(String [] args)
    CSE cs = new CSE();
    }I have tried uploading it to a server, running it from appletviewer, and locally using the .HTML file. The GUI works fine, everything is there, however, pressing the buttons does nothing.
    Can you not use the Scanners and such with JApplets?
    Yes, the directories are good.
    EDIT EDIT EDIT; OK, it works with appletviewer, but still doesn't work when it is published.
    Message wa

    I can't seem to edit the post anymore, here it is again;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class CSE extends JApplet implements ActionListener, ItemListener
    //GUI COMPONENTS
    //ToolBar components
    JToolBar mainSelect = new JToolBar("Materials");
    JButton materials;
    String materialNames[] = {"Fur Square", "Bolt of Linen", "Bolt of Damask", "Bolt of Silk", "Glob of Ectoplasm", "Steel Ingot", "Deldrimor Steel Ingot", "Monstrous Claw", "Monstrous Eye", "Monstrous Fang", "Ruby", "Lump of Charcoal", "Obsidian Shard", "Tempered Glass Vial", "Leather Square", "Elonian Leather Square", "Vial of Ink", "Roll of Parchment", "Roll of Vellum", "Spiritwood Plank", "Amber Chunk", "Jadeite Shard"};
    ImageIcon materialIcons;
    //Graphic components
    JDesktopPane mainGraph = new JDesktopPane();
    JPanel dailyGraph = new JPanel();
    JPanel weeklyGraph = new JPanel();
    JPanel finalPrices = new JPanel();
    Box graphs = Box.createHorizontalBox();
    //The Console
    JFrame CSEFrame = new JFrame();
    JSplitPane mainConsoleBackdrop = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    JSplitPane dataOut = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    JTextArea prediction = new JTextArea(10,10);
    JScrollPane predictionScroll;
    Box finalPricesLabels = Box.createVerticalBox();
    Box finalPricesLay = Box.createVerticalBox();
    JLabel finalBuy = new JLabel("Net Buy Price Change: 0.00");
    JLabel finalSell = new JLabel("Net Sell Price Change: 0.00");
    JLabel buySell = new JLabel("We recommend you: N/A");
    JTextArea priceUpdate = new JTextArea(10, 10);
    JTextArea priceUpdateWeekly = new JTextArea(10, 10);
    JScrollPane priceUScrollW;
    JScrollPane priceUScroll;
    JCheckBox weeklySelect = new JCheckBox("To show weekly price changes.", false);
    JCheckBox dailySelect = new JCheckBox("To show daily price changes.", true);
    ButtonGroup dataToShow = new ButtonGroup();
    //COMPONENTS FOR DATE; OBTAINING CORRECT FOLDER
    String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    Calendar calSource = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    int day = calSource.get(Calendar.DAY_OF_MONTH);
    int month = calSource.get(Calendar.MONTH);
    int year = calSource.get(Calendar.YEAR);
    int monthCheck [] = {Calendar.JANUARY, Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL, Calendar.MAY, Calendar.JUNE, Calendar.JULY, Calendar.AUGUST, Calendar.SEPTEMBER, Calendar.OCTOBER, Calendar.NOVEMBER, Calendar.DECEMBER};
    int dayS = day;
    int monthS = month;
    int yearS = year;
    //if there is file found
    boolean proceed = false;
    //int data for analysis
    int buyPrice;
    int currentBuyPrice;
    int sellPrice;
    int currentSellPrice;
    boolean weekly = false;
    //tools for parsing and decoding input
    String inputS = null;
    String s = null;
    Scanner [] week = new Scanner[7];
    Scanner scanner;
    int position = 0;
    //weekly tools
    String weekPos[] = {"Seventh", "Sixth", "Fifth", "Fourth", "Third", "Second", "First"};
    int dayOfWeek = 0; //0 = 7 1 = 6...
    public JButton getToolBarButton(String s)
    String imgLoc = "TBar Icons/" +s +".gif";
    java.net.URL imgURL = CSE.class.getResource(imgLoc);
    JButton button = new JButton();
    button.setActionCommand(s);
    button.setToolTipText(s);
    button.addActionListener(this);
    if(imgURL != null)
    button.setIcon(new ImageIcon(imgURL, s));
    else
    button.setText(s);
    System.err.println("Couldn't find; " +imgLoc);
    return button;
    public CSE()
    // super("Test CSE");
    //CSEFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    for(int x=0; x<materialNames.length; x++)
    materials = getToolBarButton(materialNames[x]);
    mainSelect.add(materials);
    //checkBoxes
    dataToShow.add(weeklySelect);
    dataToShow.add(dailySelect);
    weeklySelect.addItemListener(this);
    dailySelect.addItemListener(this);
    // sizes
    setSize(850, 850);
    //colors and fonts
    weeklyGraph.setBackground(new Color(250, 30, 40));
    dailyGraph.setBackground(new Color(100, 40, 200));
    //text Manip.
    prediction.setLineWrap(true);
    priceUpdate.setLineWrap(true);
    //scrolling
    predictionScroll = new JScrollPane(prediction, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    priceUScroll = new JScrollPane(priceUpdate, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    priceUScrollW = new JScrollPane(priceUpdateWeekly, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    //main splitpane config.
    mainConsoleBackdrop.setOneTouchExpandable(true);
    mainConsoleBackdrop.setResizeWeight(.85);
    //placement and Layout
    //GraphLayout
    graphs.add(Box.createHorizontalStrut(10));
    graphs.add(dailyGraph);
    graphs.add(Box.createHorizontalStrut(10));
    graphs.add(weeklyGraph);
    graphs.add(Box.createHorizontalStrut(10));
    dataOut.setRightComponent(predictionScroll);
    //consoleData layout
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(finalBuy);
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(finalSell);
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(buySell);
    finalPricesLay.add(finalPricesLabels);
    finalPricesLay.add(Box.createVerticalStrut(10));
    finalPricesLay.add(weeklySelect);
    finalPricesLay.add(dailySelect);
    finalPricesLay.add(priceUScroll);
    dataOut.setLeftComponent(finalPricesLay);
    mainConsoleBackdrop.setTopComponent(graphs);
    mainConsoleBackdrop.setBottomComponent(dataOut);
    getContentPane().add(mainConsoleBackdrop);
    getContentPane().add(mainSelect, BorderLayout.NORTH);
    //visibility
    // CSEFrame.setVisible(true);
    //return(CSEFrame);
    public void actionPerformed(ActionEvent e)
    getMonth();
    inputS = e.getActionCommand();
    FileReader newRead = null;
    try {
    newRead = new FileReader(monthS +"-" +dayS +"-" +yearS +"/" +inputS +".dat");
    proceed = true;
    catch(FileNotFoundException f)
    System.out.println("File not found");
    proceed = false;
    if(proceed)
    BufferedReader bufferedReader = new BufferedReader(newRead);
    scanner = new Scanner(bufferedReader);
    scanner.useDelimiter("\n");
    //starts daily analysis
    getPrice(scanner);
    //starts weekly analysis
    weekly(inputS);
    public void itemStateChanged(ItemEvent e)
    if(weeklySelect.isSelected())
    priceUpdateWeekly.setText("");
    finalPricesLay.remove(priceUScroll);
    finalPricesLay.add(priceUScrollW);
    finalPrices.updateUI();
    else
    priceUpdate.setText("");
    finalPricesLay.remove(priceUScrollW);
    finalPricesLay.add(priceUScroll);
    finalPrices.updateUI();
    public void weekly(String inputS)
    weekly = true;
    for(int x = 0; x >< 7; x++)
    dateToUse(month, day, year, (x+1));
    try
    FileReader weeklySource = new FileReader(monthS +"-" +dayS +"-" +year +"/" +inputS +".dat");
    BufferedReader weeklyBuffer = new BufferedReader(weeklySource);
    week[x] = new Scanner(weeklyBuffer);
    week[x].useDelimiter("\n");
    getPrice(week[x]);
    catch(FileNotFoundException f)
    JOptionPane.showMessageDialog(this, "No such weekly files- going back;" +(x+1) +"days");
    weekly = false;
    dateReset();
    public void getPrice(Scanner scanner)
    while(scanner.hasNextLine())
    //puts into string the next scan token
    String s = scanner.next();
    //takes the scan toke above and puts it into an editable enviroment
    String [] data = s.split("\\s");
    for(position = 0; position < data.length; position++)
    //Scanner test to make sure loop can finish, otherwise "no such line" error
    if(scanner.hasNextLine()==false)
    scanner.close();
    break;
    /*Starts data orignazation by reading from each perspective field
    * 1 = day
    * 2 = day of month
    * 3 = month
    * 4 = year
    if(position == 0 && weekly == false)
    String dayFromFile = data[position];
    int dayNum = Integer.parseInt(dayFromFile);
    priceUpdate.append(days[dayNum-1] +" ");
    else if(position == 1 && weekly == false )
    priceUpdate.append(data[position] + "/");
    else if(position == 2 && weekly == false)
    priceUpdate.append(data[position] + "/");
    else if(position == 3 && weekly == false)
    priceUpdate.append(data[position] +"\n");
    //if it is in [buy] area, it prints and computes
    else if(position == 7)
    //obtains string for buy price and stores it, then prints it
    String buy = data[position];
    if(weekly == false)
    priceUpdate.append("Buy: " +buy +"\n" );
    //converts buy to string
    currentBuyPrice = Integer.parseInt(buy);
    //eliminates problems caused by no data from server- makes the price 0
    if(currentBuyPrice < 0)
    currentBuyPrice = 0;
    //if it is greater it adds
    if(currentBuyPrice > buyPrice)
    buyPrice += currentBuyPrice;
    //if it is equal [there is no change] then it does nothing
    if(currentBuyPrice == buyPrice)
    buyPrice +=0;
    //if there is a drop, it subtracts
    else
    buyPrice -= currentBuyPrice;
    //if it is in [sell] area, it prints, and resets the position to zero because line is over
    else if(position == 8)
    //puts sell data into string and prints it
    String sell = data[position];
    if(weekly == false)
    priceUpdate.append("Sell: " + sell +"\n");
    //turns sell data into int.
    currentSellPrice = Integer.valueOf(sell).intValue();;
    //gets rid of problems caused by no data on server side- makes it 0
    if(currentSellPrice < 0)
    currentSellPrice = 0;
    //adds if there is an increase
    if(currentSellPrice > sellPrice)
    sellPrice += currentSellPrice;
    //does nothing if it is the same
    if(currentSellPrice == sellPrice)
    sellPrice +=0;
    //subtracts if there is drop
    else
    sellPrice -= currentSellPrice;
    //further protection against "No such line" and moves it down
    if(scanner.hasNextLine() == true)
    scanner.nextLine();
    //if scanner is finished, prints out all lines
    if(scanner.hasNextLine() == false && weekly == false)
    finalBuy.setText("Net Buy Price Change: "+buyPrice);
    finalSell.setText("Net Sell Price Change: " +sellPrice);
    buyPrice = 0;
    sellPrice = 0;
    position = data.length;
    else if(scanner.hasNextLine() == false && weekly == true)
    priceUpdateWeekly.append("\n" +weekPos[dayOfWeek] +" day of the week ended with; \nBuy Price;" +buyPrice +"\nSell Price;" +sellPrice);
    buyPrice = 0;
    sellPrice = 0;
    position = data.length;
    dayOfWeek++;
    if(dayOfWeek > 6)
    dayOfWeek = 0;
    public void getMonth()
    for(int x=0; x < monthCheck.length; x++)
    if(month == monthCheck[x])
    monthS = (x+1);
    x = monthCheck.length;
    public void dateToUse(int month, int day, int year, int increment)
    //set day of source
    dayS = (day - increment);
    //if day of source is less then O then we have moved to another month
    if(dayS <= 0)
    //checks the difference between how much we have incremented and the day we have started; this tells us how far into the new month we are
    int incrementDay = increment - day;
    //decrements month
    monthS--;
    //if month is less then zero, then we have moved into another year and month has become 12
    if(monthS <= 0)
    yearS--;
    monthS = 12;
    //the following looks at the current month and if it goes below it assigns the day to the proper ammount of days of the month before minus the days into the month
    if(month == 3)
    dayS = 28 - incrementDay;
    else if(month == 5 || month == 7)
    dayS = 29 - incrementDay;
    else if(month == 2 || month == 4 || month == 6 || month == 9 || month == 11)
    dayS = 31 - incrementDay;
    else
    dayS = 30 - incrementDay;
    //resets the source date to the current date once data from the week has been reached
    public void dateReset()
    dayS = day;
    monthS = month;
    yearS = year;
    public void init()
    //JFrame frame = new CSEFrameSet();
    // this.setContentPane(CSEFrameSet());
    CSE aCSE = new CSE();
    public static void main(String [] args)
    CSE cs = new CSE();
    }Message was edited by:
    Cybergasm

  • How do I position to panels in a single frame?

    Hi,
    Can someone tell me how i can position two panels in a single frame using the BorderLayout class.
    I have included my code below. When it is run it shows two JPanels positioned at the top and the bottom, a text area to the right, a panel in the center and a panel on the left. I want to get the panel on the left - the yellow panel - to be positioned in the lower third of the center panel. I have tried to use the BorderLayout.SOUTH statement - but this positions the panel across the very bottom which causes the bottom JPanel and part of the text area to disappear.
    Can anyone help with this please???
    Many thanks
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Panels extends JFrame implements ActionListener
         private TopPanel topPanel;
         private BottomPanel bottomPanel;
         private JButton open;
         private JButton close;
         private JButton connect;
         boolean openClicked = false;
         boolean closeClicked = false;
         public Panels()
              super("Panels");
              setSize(1000,600);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              Container contentArea = getContentPane();
              topPanel = new TopPanel();
              bottomPanel = new BottomPanel();
              JTextArea textArea = new JTextArea("Text Area",20,20);
              JScrollPane textScroller = new JScrollPane(textArea);
              open = new JButton("Open");
              open.addActionListener(this);
              close = new JButton("Close");
              close.addActionListener(this);
              connect = new JButton("Connect");
              connect.addActionListener(this);
              JPanel topBar = new JPanel();
              topBar.setBackground(Color.red);
              topBar.add(open);
              topBar.add(close);
              JPanel lowerBar = new JPanel();
              lowerBar.setBackground(Color.red);
              lowerBar.add(connect);
              bottomPanel.setPreferredSize(new Dimension(100,100));
              contentArea.add(topPanel);
         contentArea.add(bottomPanel,BorderLayout.WEST);
              contentArea.add(textScroller,BorderLayout.EAST);
              contentArea.add(lowerBar,BorderLayout.SOUTH);
              contentArea.add(topBar,BorderLayout.NORTH);
              setContentPane(contentArea);
    public void actionPerformed(ActionEvent e)
         if(e.getSource() == open)
         openClicked = true;
         topPanel.repaint();
         if(e.getSource() == close)
         {closeClicked = true;
         bottomPanel.repaint();
    class TopPanel extends JPanel
         public TopPanel()
         public void paintComponent(Graphics painter)
              super.paintComponent(painter);
              painter.setColor(Color.white);
              painter.fillRect(0,0,getSize().width,getSize().height);
              if (openClicked == true)
              drawTopMessage(painter);
         public void drawTopMessage(Graphics painter)
              painter.setColor(Color.black);
              painter.drawString("This is the top panel", 20,20);
    class BottomPanel extends JPanel
         public BottomPanel()
         public void paintComponent(Graphics painter)
              super.paintComponent(painter);
              painter.setColor(Color.yellow);
              painter.fillRect(0,0,getSize().width,getSize().height);
              if (closeClicked == true)
              drawBottomMessage(painter);
         public void drawBottomMessage(Graphics painter)
              painter.setColor(Color.black);
              painter.drawString("This is the bottom panel", 20,20);
    public static void main(String[] args)
         Panels example = new Panels();

    One solution would be to create a new panel, bothPanels and adding the two panels that you need to this panel.
    Once you have done that, you can add bothPanels to contentArea.add( bothPanels, BorderLayout.CENTER)
    hth

  • Need a little help with a Jbutton not working out the way I planned

    The following code is to fulfill an assignment I am working on. The problem I am having is with the btnCalc. For some reason when the button is used, the results I get is from another button. I think the variables are set right for the program to function properly but I am really hung up on this. Do anyone have any suggestions?
    import java.awt.*;                     //Contains classes for creating GUI
    import java.awt.event.*;                //For listener events
    import javax.swing.*;                     // Imports the Main Swing Package
    import javax.swing.event.*;
    import javax.swing.text.*;           // Positions text box
    import java.text.NumberFormat;          // For number format such as currency
    import java.text.*;                     // Imports the Main Text Package
    import java.util.*;                     // Utility Package
    public class MPC extends JFrame implements ActionListener           //Creates Class for MPC
    //double dblLoanAmount, dblInterestRate, dblMonthlyPayment;
    TextField txtTotalMort;
         //JButton fixRates = new JButton("Choose Fixed Rates");
         JLabel lblTotalMort = new JLabel("How much is the loan?"); // Label for dblLoanAmount amount
         JTextField txtYears = new JTextField(10);
         JLabel lblPayment = new JLabel("Your monthly payment is "); // Label for Payment
         JTextField txtPayment = new JTextField(10);
         JLabel lblYears = new JLabel("How many years?");
                             // add(lblYears);
                   JTextField txtYearsInput = new JTextField(10);
                             //a dd(txtYears);
         JLabel lblInterestRate = new JLabel("What is the interest rate?");
                             //add(lblInterestRate);
                   JTextField txtInterestRate = new JTextField(10);
                             //add(txtInterestRate);
         //JLabel lblPayment = new JLabel("Your monthly payment is:");
                             //add(lblPayment);
                   //JTextField txtPayment = new JTextField(10);
                             //txtPayment.setEditable(false);
                                  //add(txtPayment);
         JButton btnCalc = new JButton("Calculate");
                             //add(btnCalc);
                             //btnCalc.addActionListener(this);
    JButton year7InterestRateBtn = new JButton("7 years at 5.35%");     // Mortgage Term and Interest Rate
    JButton year15InterestRateBtn = new JButton("15 years at 5.50%");
    JButton year30InterestRateBtn = new JButton("30 years at 5.75%");
    JButton reset = new JButton("Clear All");
    JTextArea boxSpace = new JTextArea(100,200);          // Morgtage table size
    JScrollPane scroll = new JScrollPane(boxSpace);     // ScrollPane
              public MPC()     // Method
         super("MPC");     // Frame Title
              JMenuBar mb = new JMenuBar();     // Menu Bar
    setJMenuBar(mb);
                        setSize(325, 500);          // Frame Size
                        JPanel pane = new JPanel();
                        pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); //Grid box configuration
                        Container grid = getContentPane();
                        grid.setLayout(new GridLayout(8,2,8,8));     // Grid Layout
                        pane.add(grid);                                        // Adds grid
                        pane.add(scroll);                                   // Adds scrollPane
                   grid.setBackground(Color.white);
                        Setting color of text and backgrounds
                   txtYears.setBackground(Color.white);
              txtYears.setForeground(Color.black);
                   txtYears.setFont(new Font("Arial", Font.PLAIN, 10));
                        txtPayment.setBackground(Color.white);
                   txtPayment.setForeground(Color.black);
              txtPayment.setFont(new Font("Arial", Font.PLAIN, 10));
                   boxSpace.setBackground(Color.white);
                   boxSpace.setForeground(Color.black);
                   boxSpace.setFont(new Font("Arial", Font.PLAIN, 10));
              grid.add(lblYears);
              grid.add(txtYearsInput);
              grid.add(lblInterestRate);
              grid.add (txtInterestRate);
              grid.add(lblTotalMort);          // Adds the Mortgage Amount Label
              grid.add(txtYears);               // Adds the Mortgage Amount Text Field
              grid.add(lblPayment);           // Adds the Payment Label
              grid.add(txtPayment);           // Adds the Monthly Payment Text Field
                   txtPayment.setEditable(false);          // Disables editing in this Text Field
              grid.add(btnCalc);
         grid.add(year7InterestRateBtn);               // Adds 1st Loan and Rate Button
              grid.add(year15InterestRateBtn);          // Adds 2nd Loan and Rate Button
              grid.add(year30InterestRateBtn);          // Adds the Exit Button
              grid.add(reset);                               // Adds the New Calc Button
              setContentPane(pane);                          // Enables the Content Pane
              setVisible(true);                               // Sets JPanel to be Visable
              reset.addActionListener(this);                          // Adds Action Listener to the New Calc Button
              txtYearsInput.addActionListener(this);
              txtInterestRate.addActionListener(this);
              btnCalc.addActionListener(this);
         year7InterestRateBtn.addActionListener(this);                              // Adds Action Listener to the 1st loan Button
              year15InterestRateBtn.addActionListener(this);                              // Adds Action Listener to the 2nd loan Button
              year30InterestRateBtn.addActionListener(this);                               // Adds Action Listener to the 3rd loan Button
              txtYears.addActionListener(this);                              // Adds Action Listener to the Mortgage Amount Text Field
              txtPayment.addActionListener(this);                              // Adds Action Listener to the Monthly payment Text Field
              public void actionPerformed(ActionEvent e)                               // Tests to Verify Which Button is Pressed
         Object command = e.getSource(); // Enables command to get data
         int intYears = 0;          // Declares intYears
                   double dblLoanAmount, dblInterestRate, interestRate, intRate;
         if (command == year7InterestRateBtn)                                   // Activates the 1st Loan Button
    intYears = 0;                                        // Sets 1st value of Array
         if (command == year15InterestRateBtn)                                   // Activates the 2nd Loan Button
         intYears = 1;                                        // Sets 2nd value of Array
              if (command == year30InterestRateBtn)                                   // Activates the 3rd Loan Button
                   intYears = 2;                                        // Sets 3rd value of Array
                   if (command == btnCalc)
                        //dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
                        //interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
                        intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
                        //int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
                        int months = Integer.parseInt(txtYearsInput.getText() )* 12;
    dblLoanAmount = 0;                                   // Declares and Initializes dblLoanAmount
                   dblInterestRate = 0;                                        // Declares and Initializes dblInterestRate
              double [][] dblTrmLoanRate = {{7, 5.35}, {15, 5.50}, {30, 5.75},};           // Array Data for Calculation
    try
    dblLoanAmount = Double.parseDouble(txtYears.getText()); // Gets user input from txtYears Text Field
    catch (NumberFormatException nfe)                          // Checks for correct user input
                             JOptionPane.showMessageDialog(null, "You must enter a valid number.", "MPC", JOptionPane.INFORMATION_MESSAGE);
    return;
              interestRate = dblTrmLoanRate [intYears][1];
                   //dblInterestRate=interestRate;
                   intRate = (interestRate / 100) / 12;                         // Calculates Interst Rate
         double intYearsMonths = dblTrmLoanRate [intYears] [0];                    // Calculates Loan Term in Months
    int months = (int)intYearsMonths * 12;                          // Devides by months
    double interestRateMonthly = (intRate / 12); // Devides Rate
              double payment = dblLoanAmount * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculates monthly payment
         double dblRmnLoan = dblLoanAmount;                              //Left over balance
         double txtPaymentInterest = 0;                                   // Payment
         double txtPaymentPrincipal = 0;                                   // Payment of principal
    NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US); // Curreny format
         txtPayment.setText(currency.format(payment));
              boxSpace.setText("Month\tPrincipal\tInterest\tBalance Left\n");
              for (;months > 0 ; months -- )
              txtPaymentInterest = (dblRmnLoan * intRate);
                        txtPaymentPrincipal = (payment - txtPaymentInterest);          // Calculates monthly payment
                   dblRmnLoan = (dblRmnLoan - txtPaymentPrincipal);
                        boxSpace.setCaret (new DefaultCaret());                    // Scroll position
                        boxSpace.append(String.valueOf(months) + "\t" +               // Table data
                        currency.format(txtPaymentPrincipal) + "\t" +
                   currency.format(txtPaymentInterest) + "\t" +
                   currency.format(dblRmnLoan) + "\n");
    if(command == reset)
                             Clears fields
                        txtYearsInput.setText(null);
                        txtInterestRate.setText(null);
              txtYears.setText(null);
                        txtPayment.setText(null);
         boxSpace.setText(null);
                        public static void main(String[] args)                               //This is the signature of the entry point of all the desktop apps
              new MPC();
    }

    This portion to be exact. All the buttons work for me except this one. I need to calculate user input and also use the fixed data that can be found in the dblTrmLoanRate array. When I choos to use user input instead, the program either crashes or for some reason uses the year7InterestRateBtn instead.
                   if (command == btnCalc)
                        //dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
                        //interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
                        intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
                        //int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
                        int months = Integer.parseInt(txtYearsInput.getText() )* 12;
    I was going to leave out the remed portion but thought it might help you with the navigation. I am sorry I did not use code tags, but I am going to go find out what those are and use them in the future.

Maybe you are looking for