Question on jpanel

im making my own panel in which im going to extend JPanel, and have it be able to display different images when a button has been clicked on. my question is, is it possible to display gifs on a panel and call repaint() to have it appear? or what images am i allowed to display on a JPanel? Thanks in advance

Here is a better, at least IMHO, solution:
Add a JLabel to your JPanel. When you want to display an image on the panel simply call myLabel.setIcon(image). Here's a demo.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class LabelImageTest extends JFrame{
    JLabel imageLabel;
    ImageIcon imageIcon;
    Image imageOne;
    Image imageTwo;
    Image imageThree;
    public LabelImageTest() {
        initImages();
        buildGui();
    private void initImages() {
        imageOne = Toolkit.getDefaultToolkit().getImage("images/About24.gif");
        imageTwo = Toolkit.getDefaultToolkit().getImage("images/Add24.gif");
        imageThree = Toolkit.getDefaultToolkit().getImage("images/Bean24.gif");
    private void buildGui() {
        JPanel mainPanel = (JPanel) getContentPane();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(buildCenterPanel(), BorderLayout.CENTER);
        mainPanel.add(buildButtonPanel(),BorderLayout.SOUTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    private void setImage(Image image){
       imageLabel.setIcon(new ImageIcon(image));
    private JPanel buildButtonPanel() {
        JPanel retPanel = new JPanel();
        JPanel innerPanel = new JPanel(new GridLayout(0,3,5,5));
        JButton buttonOne = new JButton("Image one");
        buttonOne.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               setImage(imageOne);
        JButton buttonTwo = new JButton("Image two");
        buttonTwo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setImage(imageTwo);
        JButton buttonThree = new JButton("Image Three");
        buttonThree.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setImage(imageThree);
        innerPanel.add(buttonOne);
        innerPanel.add(buttonTwo);
        innerPanel.add(buttonThree);
        retPanel.add(innerPanel);
        return retPanel;
    private JPanel buildCenterPanel() {
        JPanel retPanel = new JPanel();
        retPanel.setPreferredSize(new Dimension(50,50));
        imageLabel = new JLabel();
        imageIcon = new ImageIcon();
        imageLabel.setIcon(imageIcon);
        retPanel.add(imageLabel);
        return retPanel;
    public static void main(String[] args) {
        new LabelImageTest();
}Of course, you'll have to supply path to your own images. The nice thing about this is that you can pass in images from files or a self created image you've drawn.
Cheers
DB

Similar Messages

  • Question on JPanels

    I have a JFrame with three JPanels on. One at the top, one in the middle and one at the bottom. The bottom JPanel has a login and register button. If the user chooses login, a login dialog comes up. My question is to see whether it is possible to do this. If the user logs in correctly, is there any code i can write which will dispose of everything on my orginal JFrames panels, and replace them with new components? e.g. the login button turns into a JTextArea on successful login.

    Read the API. You can add/remove components from any panel. The trick is to revalidate() the panel after adding or removing components.
    Or better yet, read the Swing tutorial on [How to Use Card Layout|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]

  • Jpanel overlap Forms Component

    Hi all,
    I'm using forms 11g, now i try to add one JPanel (Swing) to DrawPanel (Oracle forms DrawPanel), I add the panel first after that I add other Forms component such as VTextField, VBUtton, after that I change Z-order of JPanel to last index (because i want Jpanel will be overlapped by other forms components) .
    But the result always show the JPanel overlap Form Component.
    For more detail you can view this link : [http://stackoverflow.com/questions/7764532/jpanel-overlap-other-components]
    Thanks in advance
    Best regards,
    Edited by: 891733 on 21:05 16-10-2011

    Hi,
    When i change JPanel to Forms DrawnPanel, i still got this problem,
    And i've already added this post to Java Programming Thread
    jpanel overlap Forms Component

  • JRadioButton Question

    Hi,
    I have the following code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ShowCardLayout extends JApplet implements ActionListener
         private CardLayout cardLayout = new CardLayout(20, 10);
         private JPanel cardPanel = new JPanel(cardLayout);
         JButton previous, next;
         public ShowCardLayout()
              cardPanel.setBorder(new javax.swing.border.LineBorder(Color.black));
              for(int i = 1; i <= 8; i++)
                   JPanel subPanel = new JPanel(new BorderLayout());
                   JLabel label = new JLabel("Question #" + i);
                   JPanel buttonPanel = new JPanel();
                   JRadioButton button1 = new JRadioButton("Excellent");
                   JRadioButton button2 = new JRadioButton("Good");
                   JRadioButton button3 = new JRadioButton("Fair");
                   JRadioButton button4 = new JRadioButton("Poor");
                   ButtonGroup answers = new ButtonGroup();
                   buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS ));
                   buttonPanel.add(button1);
                   buttonPanel.add(button2);
                   buttonPanel.add(button3);
                   buttonPanel.add(button4);
                   subPanel.add(label, BorderLayout.NORTH);
                   subPanel.add(buttonPanel, BorderLayout.WEST);
                   cardPanel.add(subPanel, String.valueOf(i));
              JPanel p = new JPanel();
              p.add(previous = new JButton("Previous"));
              p.add(next = new JButton("Next"));
              getContentPane().add(cardPanel, BorderLayout.CENTER);
              getContentPane().add(p, BorderLayout.SOUTH);
              previous.addActionListener(this);
              next.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              String actionCommand = e.getActionCommand();
              if(e.getSource() instanceof JButton)
                   if("Previous".equals(actionCommand))
                        cardLayout.previous(cardPanel);
                   else if("Next".equals(actionCommand))
                        cardLayout.next(cardPanel);
         public static void main(String[] args)
              ShowCardLayout applet = new ShowCardLayout();
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(3);
              frame.setTitle("ShowCardLayout");
              frame.getContentPane().add(applet, BorderLayout.CENTER);
              applet.init();
              applet.start();
              frame.setSize(570, 220);
              frame.setVisible(true);
    }How can I capture button selection from each question?

    a simple demo
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      final int MAX_PANELS = 5;
      CardLayout cl = new CardLayout();
      JPanel clPanel = new JPanel(cl);
      int currentPanel = 0;
      public Testing()
        setSize(300,200);
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        for(int x = 0; x < MAX_PANELS; x++)
          JPanel p = new JPanel();
          p.add(new JLabel("Panel "+ x));
          clPanel.add(""+x,p);
        final JButton btnPrev = new JButton("Previous");
        final JButton btnNext = new JButton("Next");
        JPanel p = new JPanel(new GridLayout(1,2,25,0));
        p.add(btnPrev);
        p.add(btnNext);
        JPanel p1 = new JPanel();
        p1.add(p);
        getContentPane().add(clPanel,BorderLayout.CENTER);
        getContentPane().add(p1,BorderLayout.SOUTH);
        btnPrev.setEnabled(false);
        btnPrev.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            cl.previous(clPanel);
            currentPanel--;
            btnNext.setEnabled(true);
            if(currentPanel == 0) btnPrev.setEnabled(false);}});
        btnNext.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            cl.next(clPanel);
            currentPanel++;
            btnPrev.setEnabled(true);
            if(currentPanel == MAX_PANELS-1) btnNext.setEnabled(false);}});
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Swapping JPanels?

    I have a question regarding JPanels in a JFrame. What I'm wondering if the source of the JPanel can be changed on an action event. For example say I have two instances of a JPanel, is it possible to switch between the two in the same JFrame on a button event?
    Thanks for your time.

    Uhm...consider that when dealing with something like a JFrame, the contentPane is the second top-most layer (sits below the glassPane). So simply doing JFrame.add() will not be enough. You can however, call JFrame.getContentPane() and then issue an add() method to the container returned; for example JFrame.getContentPane().add(your panel);However you wind up with an extra layer since what you have is a container (the content pane) that contains a panel (panel1). In reality, panel1 is meant to hold the actual content, so setting it as the contentPane reduces the number of layers. It also removes the need to remember to remove(oldPanel) before calling add(newPanel).
    So rather than having to replace via myFrame.getContentPane().remove(panel1);
    myFrame.getContentPane.add(panel2);You'd simply do it viamyFrame.setContentPane(panel2);//the previous contentPane is de-referrenced

  • Gridbag layout continues to confound me...

    I am having problems with the gridx and gridy constraints when trying to use gridbag layout. They seem to have no effect when I use them. The button always appears in the top left of the panel. Other constraints seem to work as expected.
    For example: c2.fill = GridBagConstraints.BOTH; will fill up the entire panel with my button.
    Any advice on what I am doing wrong this time?
    Thanks
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Question
         public JPanel test()
              JPanel testPanel = new JPanel(new GridBagLayout());
              GridBagConstraints c2 = new GridBagConstraints();
              c2.insets = new Insets(5,5,5,5);
              c2.weightx = 1.0;
              c2.weighty = 1.0;
              c2.anchor = c2.NORTHWEST;
              JButton redButton = new JButton("Button");
              c2.gridx = 2;
              c2.gridy = 2;
              //c2.fill = GridBagConstraints.BOTH;//this works as expected
              testPanel.add(redButton,c2);
              return testPanel;
         public Container createContentPane()
              //Create the content-pane-to-be.
              JPanel contentPane = new JPanel(new BorderLayout());
              contentPane.setOpaque(true);
              return contentPane;
         private static void createAndShowGUI()
              //Create and set up the window.
              JFrame frame = new JFrame("question");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Create and set up the content pane.
              Question demo = new Question();
              frame.setContentPane(demo.createContentPane());
              frame.add(demo.test());
              //Display the window.
              frame.setSize(400, 400);
              frame.setVisible(true);
        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();
        }//end main
    }//end Question

    GridBagLayout keeps zero width/height grid for non-existant component for the grid.
    You could override this behavior by using GBL's four arrays as shown below.
    However, in order to get the desired layout effect, using other layout manager, e.g. BoxLayout and/or Box, is much easier and flexible as camickr, a GBL hater, suggests.
    Anyway, however, before using a complex API class as GBL, you shoud read the documentation closely.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Question{
      // you may adjust these values for your taste
      static final int rowHeight    = 100;
      static final int colWidth     = 100;
      static final double rowWeight = 1.0;
      static final double colWeight = 1.0;
      public JPanel test(){
        GridBagLayout gb = new GridBagLayout();
        gb = keepAllRowsAndColumns(gb, 3, 3);
        JPanel testPanel = new JPanel(gb);
        GridBagConstraints c2 = new GridBagConstraints();
        c2.insets = new Insets(5,5,5,5);
        c2.weightx = 1.0;
        c2.weighty = 1.0;
        c2.anchor = c2.NORTHWEST;
        JButton redButton = new JButton("Button");
        c2.gridx = 2;
        c2.gridy = 2;
        // c2.fill = GridBagConstraints.BOTH;//this works as expected
        testPanel.add(redButton,c2);
        return testPanel;
      GridBagLayout keepAllRowsAndColumns(GridBagLayout g, int rn, int cn){
        g.rowHeights = new int[rn];
        g.columnWidths = new int[cn];
        g.rowWeights = new double[rn];
        g.columnWeights = new double[cn];
        for (int i = 0; i < rn; ++i){
          g.rowHeights[i] = rowHeight;
          g.rowWeights[i] = rowWeight;
        for (int i = 0; i < cn; ++i){
          g.columnWidths[i] = colWidth;
          g.columnWeights[i] = colWeight;
        return g;
      private static void createAndShowGUI(){
        JFrame frame = new JFrame("question");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Question demo = new Question();
        frame.getContentPane().add(demo.test(), BorderLayout.CENTER);
        frame.setSize(400, 400);
        frame.setVisible(true);
      public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            createAndShowGUI();
    }

  • Swing for http

    Hello I want to ask how to know the difference on what I can do with Swing for http and Swing for desktop. I am programming an application in NetBeans for http and I don't know if all what I do work with http too or if there is some differences between desktop and http.
    Someone can tell me please?
    thanks

    GonzaloP wrote:
    Encephalopathic can you show me an example of this? I am begginer in java.Sure. But sorry if it's too long.
    The first class, MyAppPanel.java, creates a JPanel on demand: if you call getMainPanel() on a MyAppPanel object, you'll get its JPanel. This JPanel doesn't do anything except draw some components on the screen for demonstration purposes:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSeparator;
    import javax.swing.JTextField;
    public class MyAppPanel
      private static final String[] LABEL_STRINGS =
        "What is your Quest?", "What is your Favorite Color?", "What is the Capital of Assyria?",
        "What is the Air-Speed Velocity?"
      private static final String TITLE = "Bridge Questions";
      private JPanel mainPanel = new JPanel();
      public MyAppPanel()
        JPanel titlePanel = createTitlePanel(TITLE);
        JPanel dataPanel = createCenterPanel(LABEL_STRINGS);
        JPanel btnPanel = createButtonPanel();
        int eb = 10;
        mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
        mainPanel.setBackground(Color.lightGray);
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
        mainPanel.add(titlePanel);
        mainPanel.add(createMySeparator(15));
        mainPanel.add(dataPanel);
        mainPanel.add(createMySeparator(15));
        mainPanel.add(btnPanel);
      private JPanel createMySeparator(int vs)
        JPanel mySeparator = new JPanel();
        mySeparator.setOpaque(false);
        mySeparator.setLayout(new BoxLayout(mySeparator, BoxLayout.PAGE_AXIS));
        mySeparator.add(Box.createVerticalStrut(vs));
        mySeparator.add(new JSeparator());
        mySeparator.add(Box.createVerticalStrut(vs));
        //mySeparator.setBorder(BorderFactory.createLineBorder(Color.blue));
        JPanel outerPanel = new JPanel(new BorderLayout());
        outerPanel.setOpaque(false);
        outerPanel.add(mySeparator);
        return outerPanel;
      private JPanel createButtonPanel()
        JPanel btnPanel = new JPanel(new GridLayout(1, 0, 20, 0));
        btnPanel.setOpaque(false);
        JButton saveBtn = new JButton("Save");
        JButton cancelBtn = new JButton("Cancel");
        btnPanel.add(saveBtn);
        btnPanel.add(cancelBtn);
        return btnPanel;
      private JPanel createCenterPanel(String[] labelStrings)
        JPanel westPanel = new JPanel(new GridLayout(0, 1, 0, 5));
        JPanel centrPanel = new JPanel(new GridLayout(0, 1, 0, 5));
        westPanel.setOpaque(false);
        centrPanel.setOpaque(false);
        for (int i = 0; i < labelStrings.length; i++)
          JLabel label = new JLabel(labelStrings);
    westPanel.add(label);
    centrPanel.add(new JTextField(12));
    JPanel dataPanel = new JPanel();
    dataPanel.setOpaque(false);
    dataPanel.setLayout(new BorderLayout(10, 10));
    dataPanel.add(westPanel, BorderLayout.WEST);
    dataPanel.add(centrPanel, BorderLayout.CENTER);
    return dataPanel;
    private JPanel createTitlePanel(String text)
    JPanel titlePanel = new JPanel();
    titlePanel.setOpaque(false);
    JLabel label = new JLabel(text);
    label.setFont(label.getFont().deriveFont(Font.BOLD, 32));
    titlePanel.add(label);
    return titlePanel;
    public JPanel getMainPanel()
    return mainPanel;
    Now if I want to use the produced JPanel in a stand-alone program, all I need to do is create a JFrame, place the JPanel in the JFrame's contentPane, pack and set the JFrame to visible, and I'm done. This next class, MyAppJFrame, does just that:
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class MyAppJFrame
      private static void createAndShowUI()
        MyAppPanel myappPanel = new MyAppPanel();  //create a myappPanel object
        JPanel panel = myappPanel.getMainPanel();  // get its JPanel
        JFrame frame = new JFrame("MyAppPanel"); // create the JFrame 
        frame.getContentPane().add(panel);   // and add the JPanel to the contentPane
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }Now if I want to create a JApplet, I do the exact same thing, only this time place the JPanel into a JApplet's content frame, as this class MyAppApplet demonstrates:
    import java.awt.Dimension;
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class MyAppJApplet extends JApplet
      @Override
      public void init()
        try
          SwingUtilities.invokeAndWait(new Runnable()
            public void run()
              MyAppPanel myAppPanel = new MyAppPanel();
              JPanel myPanel = myAppPanel.getMainPanel();  // get the JPanel from the MyAppPanel object
              getContentPane().add(myPanel); // place it in the JApplet just like we did for the JFrame
              setSize(new Dimension(myPanel.getPreferredSize()));
        catch (InterruptedException e)
          e.printStackTrace();
        catch (InvocationTargetException e)
          e.printStackTrace();

  • Info for Info Course

    Sorry, if this post is not useful to you.
    It will only be active for a week or so.
    I accidently took this Java course. I thought it would be a more web page building type course. I never foresee myself ever using Java. I don't know why I can't program for shit. It sucks. I'm supposed to be smart but why can't I program?
    Teacher says we can use java.sun.com for the practical portion of an exam. So I'm posting some useful code ( to me).
    When I'm done, just let this forum die to the bottom of the list.
    But in the meantime, if you need info on elementary Java stuff like GUI's, JDBC, Multithreading, etc., here it is.
    Cheers

    import javax.swing.*;
    import java.awt.*;
    // Generates the first application frame of the program.
    public class CareerAdvisor
    public static void main(String[] args)
         // Create application frame for User and Administrator JButton selections.
    StartFrame f = new StartFrame();
    f.setSize(350,300);
    f.setLocation(340,210);
    f.setVisible(true);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    /* Loads the question panel and contains the buttons for the navigation
    through the 5 question panels. */
    public class CareerAdvisorFrame extends JFrame
         Connection con;
         Statement stmt;
         ResultSet rs;     
         // Accesses the previous question.
         JButton jbPrevious = new JButton("Previous");
         // The user clicks the 'Done' button when she has completed all questions.
         JButton jbDone = new JButton("Done");
         // Accesses the next question.
         JButton jbNext = new JButton("Next");
         int currentQuestion;
         /* There are 5 questions for the user to answer. Each question has its own
         question panel. */
         QuestionPanel[] qP = new QuestionPanel[5];
         /* The CareerAdvisorFrame GUI needs to be put into a container, which is
         activated.*/
         Container c = this.getContentPane();
         // The center panel contains the question.
         JPanel pCenter = new JPanel();
         // The south panel contains the 3 navigation buttons.
         JPanel pSouth = new JPanel();
         JFrame thisFrame;          
         String messageA = "";
         // GUI created.
         public CareerAdvisorFrame()
                   thisFrame = this;
                   currentQuestion = 1;
                   // For each question, a question panel is generated.
                   for (int i = 0; i<5; i++)
                        qP= new QuestionPanel(i+1);
                   /* Specifying Border Layout for the container and the center panel. This
                   is because     the question panel is created in its own class using the Grid
                   Layout for the GUI construction. The south panel is constructed in this
                   class and Grid Layout is used because 1 row of 3 columns is needed for
                   the 3 navigation buttons. */
                   c.setLayout(new BorderLayout());
                   pCenter.setLayout(new BorderLayout());
                   pSouth.setLayout(new GridLayout(1,3));
                   // The 3 navigation buttons are added to the south panel.
                   pSouth.add(jbPrevious);
                   pSouth.add(jbDone);
                   pSouth.add(jbNext);
                   // The question panel is added to the center panel.
                   pCenter.add(qP[0], BorderLayout.CENTER);
                   // The south panel and center panels are added to the container.
                   c.add(pSouth, BorderLayout.SOUTH);
                   c.add(pCenter, BorderLayout.CENTER);
                   /* To listen for mouse clicks on the 3 navigation buttons, action
                   listeners must be added. Then, action handler parameters are passed. */
                   ActionHandler actH = new ActionHandler();
                   jbDone.addActionListener(actH);
                   jbPrevious.addActionListener(actH);
                   jbNext.addActionListener(actH);
         /* The location of the mouseclick is determined. Each of the 3 buttons have
         a specific function to accomplish and so methods are called. */
         public class ActionHandler implements ActionListener
              // The button source of the click is stored in ActionEvent e.
              public void actionPerformed(ActionEvent e)
                   /* If the user clicks 'Next' the next() method is accessed. Different
                   methods are accessed for the 'Previous' and 'Done' buttons. */
                   if (e.getSource() == jbNext)
                        next();
                   else if (e.getSource() == jbPrevious)
                        previous();
                   else if (e.getSource() == jbDone)
                        done();
         /* The current question advances and the next question panel is put into the
         frame with the next question. When question 5 is reached, the 'Next' button
         is disabled because there are no further questions for the user to access.
         The button is enabled for the first 4 questions. The 'Previous' button is
         enabled at start up, even for the first question. This is to give a uniform
         appearance for the user when she first sees the Career Advisor Frame. The
         'Previous' button is also enabled if the current question does not equal 5.*/
         private void next()
              if (currentQuestion < 5)
                   currentQuestion++;
                   if (currentQuestion == 5)
                        jbNext.setEnabled(false);
                        // The panel is being refreshed with the new information.
                        pCenter.validate();
                   else
                        jbPrevious.setEnabled(true);
                        pCenter.validate();
                   // The current question is removed to add the next question.     
                   pCenter.removeAll();
                   pCenter.add(qP[currentQuestion - 1], BorderLayout.CENTER);
                   pCenter.validate();
                   // The next question is physically repainted onto the panel.
                   repaint();
         /* After the current question decreases by one, the previous question panel
         is put into the frame with the previous question. When question 1 is
         reached, the 'Previous' button is disabled, since there is no question
         before the first one. The 'Next' button is enabled, when the current
         question is not equal to 1. */
         private void previous()
              if (currentQuestion > 1)
                   currentQuestion--;
                   if (currentQuestion == 1)
                        jbPrevious.setEnabled(false);
                        pCenter.validate();
                   else
                        jbNext.setEnabled(true);
                        pCenter.validate();
                   // The current question is removed to add the previous question.     
                   pCenter.removeAll();
                   pCenter.add(qP[currentQuestion - 1], BorderLayout.CENTER);
                   pCenter.validate();
                   repaint();
         /* The user's name is being stored in the Career database after the user
         provides it and then the career result is displayed. */
         private void done()
              // The 'Done' button is disabled after the user clicks it once
              jbDone.setEnabled(false);     
              String userName = "";
              /* The user enters his name in the input dialog. If he presses cancel, the
              program will exit. If he enters his name, he will be allowed to view his
              career result.*/
              do
                   userName = JOptionPane.showInputDialog(
                        null,"Please enter your name:", "Career Result Access", 1);
                   if (userName == null)
                        System.exit(0);
              }while (userName.equals(""));
         updateDataBase(userName);
    ColoredJOptionPane c = new ColoredJOptionPane(new Color(255,236,139));
              c.showMessageDialog(null,message, "Career Result", 1);
              // The Career Advisor Frame dies after the user hits 'ok' on the dialog.     
              this.setVisible(false);                    
         // The user's answers and user's name are updated in the Career database.
         private void updateDataBase(String userName)
              String sourceURL = "jdbc:odbc:career";
              String query1 = "SELECT * FROM UserRecord";
              try
                   /* The Microsoft Access Driver is loaded. The program is
                        connecting to the database. The stament object executes SQL
                        statements. */
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con = DriverManager.getConnection(sourceURL);
         stmt = con.createStatement(     ResultSet.TYPE_SCROLL_SENSITIVE,
                                                                                    ResultSet.CONCUR_UPDATABLE);
         /* Querying the UserRecord table of the Career database and storing the
         statement in result set. */                                                                                     
                        rs = stmt.executeQuery(query1);
                        // The result set is moving to insert a row into the table.
                        rs.moveToInsertRow();
              /* Each column, 1-7, of the table is being updated with the user's name
              and each of his 5 answers to the questions. The 7th column is updated
              with the career title, messageA, that was outputted to the user in the
              dialog with the career result. The row is appended at the end of the
              table for these strings to be loaded into. */
              rs.updateString(1, userName);     
              rs.updateString(2, qP[0].getAnswer());
              rs.updateString(3, qP[1].getAnswer());
              rs.updateString(4, qP[2].getAnswer());
              rs.updateString(5, qP[3].getAnswer());
              rs.updateString(6, qP[4].getAnswer());          
              rs.updateString(7, messageA);     
              rs.insertRow();
              // The result set, statement, and database connection are closed.
         rs.close();
         stmt.close();
         con.close();                                                                                
              // Exceptions are declared.
              catch(SQLException sqle)
                   System.err.println("Error creating connection");
         catch(ClassNotFoundException cnfe)
                   System.err.println(cnfe.toString());
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    // A question panel is created. It connects to a database.
    class QuestionPanel extends JPanel
         int questionNumber;
         String answer;
         int numberOfAnswers;
         // The background of the question panel is stored in SwimTiled.jpg.
         ImageIcon icon = new ImageIcon ("SwimTiled.jpg");
         JRadioButton[] rbAnswer = new JRadioButton[12];
         Connection con;
    Statement stmt;
    ResultSet rs;
    /* The question panel reads each of 5 questions stored in the Career
    database. There are 5 queries made for 5 tables, Q1 through Q5. Each question
    has it's own table. */
    public QuestionPanel(int qNum)
              questionNumber = qNum;
              /* Creating a button group allows only one radio button to be clicked per
              question. */
              ButtonGroup bg = new ButtonGroup();
              /* There are 14 rows created for the grid layout. One row is taken up by
              the question, one row for a blank space, and up to 12 rows for 12 radio
              button lines of text. The first question has the maximum number of radio
              buttons, named from 'a' to 'l'. The other questions require less than 12
              radio buttons.*/
              this.setLayout(new GridLayout(14,1));
              String sourceURL = "jdbc:odbc:career";
         String query1 = "SELECT * FROM Q1";
         String query2 = "SELECT * FROM Q2";
         String query3 = "SELECT * FROM Q3";
         String query4 = "SELECT * FROM Q4";
         String query5 = "SELECT * FROM Q5";
              try
              /* The Microsoft Access Driver is loaded. The program is
              connecting to the database. The stament object executes SQL
              statements. */
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con = DriverManager.getConnection(sourceURL);
         stmt = con.createStatement(     ResultSet.TYPE_SCROLL_SENSITIVE,
                                                                               ResultSet.CONCUR_UPDATABLE);
         /* When the qNum, or question number, equals 1, then Q1 is loaded into
         the result set as per query 1. This occurs for queries 2-5 as well.*/                    
              switch (qNum)
                        case 1:
                        rs = stmt.executeQuery(query1);break;
                        case 2:
                             rs = stmt.executeQuery(query2);break;
                        case 3:
                             rs = stmt.executeQuery(query3);break;
                        case 4:
                             rs = stmt.executeQuery(query4);break;
                        case 5:
                             rs = stmt.executeQuery(query5);break;
         // Exception handling
         catch(SQLException sqle)
              System.err.println("Error creating connection");
         catch(ClassNotFoundException cnfe)
              System.err.println(cnfe.toString());
         try
              // The result set proceeds to the next row.
              rs.next();
              /* The first part of the question, the non-radio button part is read
              from the 1st column of the corresponding question table in the
              database and put into a JLabel on the question panel. */
              this.add(new JLabel(rs.getString(1)));
              // This dummy JLabel creates a blank row in the question panel.
              this.add(new JLabel(""));
              // Action Handler created to handle actions on the radio buttons.
              ActionHandler actH = new ActionHandler();
              int k = 0;
              while(rs.next())
                   /* The result set cycles through one of the question tables, Q1-Q5,
                   and reads the radio button parts of the question into the button
                   group and then the question panel until rs.next reveals no new data.
                   These radio button parts are all in column 1 of the database table.
                   An action listener with an action handling parameter is added to the
                   rbAnswer array. */
                   rbAnswer[k] = new JRadioButton(rs.getString(1));
                   bg.add(rbAnswer[k]);
                   this.add( rbAnswer[k]);
                   rbAnswer[k].addActionListener(actH);
                   /* The radio button array is kept visible to see the writing,
                   despite the background. */
                   rbAnswer[k].setOpaque( false );
                   k++;
              numberOfAnswers = k;
         catch(SQLException sqle)
                   System.err.println("Error in read next");
                   /* Allows only some of the question panel to be painted with the
                   background file, not the radio buttons in this case. */
                   this.setOpaque( false );     
         // Returns one of the answers listed in the switch statement below.
         public String getAnswer()
              return answer;
         /* Listening for which radio button is clicked and getting the source of the
         radio button or answer that is clicked. The choice of radio buttons for a
         given question is between 1 and the amount stored in 'numberOfAnswers'.
         The switch statement assigns a particular radio button to a particular
         answer. */
         public class ActionHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   for (int i=0; i < numberOfAnswers; i++)
                        if (e.getSource() == rbAnswer[i])
                                  switch (i)
                                       case 0: answer = "a"; break;
                                       case 1: answer = "b"; break;
                                       case 2: answer = "c"; break;
                                       case 3: answer = "d"; break;
                                       case 4: answer = "e"; break;
                                       case 5: answer = "f"; break;
                                       case 6: answer = "g"; break;
                                       case 7: answer = "h"; break;
                                       case 8: answer = "i"; break;
                                       case 9: answer = "j"; break;
                                       case 10: answer = "k"; break;
                                       case 11: answer = "l"; break;
         // Background image is being painted onto question panel.
         protected void paintComponent(Graphics g)
              // Scale image to size of component.
              Dimension d = getSize();
              g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
              super.paintComponent(g);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    /* StartFrame and StartFramePanel used to be one class upon initial design.
    Separating them out allows the Panel to be painted with a background icon.
    The container is created and made with border layout. The StartFramePanel
    is put into the StartFrame. */
    public class StartFrame extends JFrame
    Container c = this.getContentPane();
    public StartFrame()
              c.setLayout(new BorderLayout());
              StartFramePanel p = new StartFramePanel();
              // The StartFramePanel is centered in the container with a border layout.
              c.add(p, BorderLayout.CENTER);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    // This class tracks the number of users and their individual data.
    class AdminList extends JFrame
         Connection con;
    Statement stmt;
    ResultSet rs;
    Container c = this.getContentPane();
         /* The information displayed in a frame that is used by the Administrator. The
         information is read from the UserRecord Table in the Career database. */
         public AdminList()
              /* There are 45 rows in the container with a grid layout so that at least
              43 new records can be added to the administrator list. The 1st row contains
              the titles of each column and the 2nd row is a blank line.*/
              c.setLayout(new GridLayout(45,1));
              String sourceURL = "jdbc:odbc:career";
         String query = "SELECT * FROM UserRecord";               
         /* The Microsoft Access Driver is loaded. The program is
    connecting to the database. The stament object executes SQL
    statements. */
              try
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con = DriverManager.getConnection(sourceURL);
         stmt = con.createStatement(     ResultSet.TYPE_SCROLL_SENSITIVE,
                                                                               ResultSet.CONCUR_UPDATABLE);
                   rs = stmt.executeQuery(query);
         // Exception statements
         catch(SQLException sqle)
              System.err.println("Error creating connection");
         catch(ClassNotFoundException cnfe)
              System.err.println(cnfe.toString());
              // Adding titles to the 7 columns of the admin list.
              c.add(new JLabel("Name"));
              c.add(new JLabel("Question 1"));
              c.add(new JLabel("Question 2"));
              c.add(new JLabel("Question 3"));
              c.add(new JLabel("Question 4"));
              c.add(new JLabel("Question 5"));
              c.add(new JLabel("Advice"));
              // Create a blank row of 7 empty string columns.
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              try
              int count = 0;
              /* Each row of the UserName table is being read by the result set. The
              1-7 represent the columns being read from the database. */
              while(rs.next())
              count ++;
              c.add(new JLabel(rs.getString(1)));
              c.add(new JLabel(rs.getString(2)));
              c.add(new JLabel(rs.getString(3)));
              c.add(new JLabel(rs.getString(4)));
              c.add(new JLabel(rs.getString(5)));
              c.add(new JLabel(rs.getString(6)));
              c.add(new JLabel(rs.getString(7)));
         /* When the last row of data is reached, rs.next stops. For the
         remaining rows, the for loop uses the counter to add blank lines to the
         Admin List with dummy JLabels. */
         for (int i = count+1; i <= 43; i++)
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
              c.add(new JLabel(""));
         // Exception statements.
         catch(SQLException sqle)
                   System.err.println("Error in read next");
    import java.awt.*;
    import javax.swing.*;
    // Used to color dialog boxes in other classes.
    class ColoredJOptionPane extends JOptionPane
    public ColoredJOptionPane(){}
    public ColoredJOptionPane(Color c)
         // Controls the color of the panel and option pane background in the dialog.
    UIManager.put("OptionPane.background",c);
    UIManager.put("Panel.background",c);
    /* The following line would only be used if we wanted to change the color of
    the buttons in the dialog. */
    // UIManager.put("Button.background",c);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    /* The start frame is the first frame that comes up for the user. Here, he can
    select whether to use the Career Advisor program by clicking the 'User' button
    or see the results of other users by clicking the 'Administrator' button.
    This panel is put into the start frame. */
    class StartFramePanel extends JPanel
         JButton jbUser = new JButton("User");
         JButton jbAdministrator = new JButton("Administrator");
         // This image is placed in the background of the 2 buttons.
         ImageIcon icon = new ImageIcon ("RoseTiled.jpg");     
         /* The frame for the StartFramePanel is created in the CareerAdvisorFrame
         class.*/
    public StartFramePanel()
         /* Since there are only 2 JButtons, the rest of the spaces are made dummy
         labels. There are 5 rows of 3 columns in the grid layout. No container is
         used since a JPanel is used rather than a frame. */
         this.setLayout(new GridLayout(5,3));
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(jbUser);
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(jbAdministrator);
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(new JLabel());
              this.add(new JLabel());
              /* Allows only some of the panel to be painted with the
              background file, not the JButtons in this case. */
              this.setOpaque( false );
              /* An ActionListener is being added to the 2 JButtons, with the action
              handler actH as a parameter being passed.     */
              ActionHandler actH = new ActionHandler();
              jbUser.addActionListener(actH);
              jbAdministrator.addActionListener(actH);
    /* After getting the source of the JButton click event, it is determined
    whether it is the jbUser or the jbAdministrator. In the former case,
    the user() method is called and in the latter, the administrator()
    method is called.*/
    public class ActionHandler implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        if (e.getSource() == jbUser)
                        user();
                        else if (e.getSource() == jbAdministrator)
                        administrator();
              // This method enables the administrator to view the Admin List.
              private void administrator()
                   // Initializing string
                   String password = null;
                   /* A default color of white is used in the dialog. This is denoted by
                   the numbers 255,255,255. */
                   ColoredJOptionPane c = new ColoredJOptionPane(new Color( 255,255,255));
              int count = 0;
              /* If after prompting the individual for the password 4 times, he
              doesn't get it right, then he is shown a message dialog and then
              exited out of the program. */
                   do{
                             if (count>3)
                                  JOptionPane.showMessageDialog(
                                       null, "You have been timed out.", "Incorrect Password", 1);
                                  System.exit(0);
                             /* The administrator is prompted for the correct password
                             in an input dialog. The password is "dcba".*/
                             password =
                                  JOptionPane.showInputDialog(null,"Password:", "Login Screen", 1);
                             // Allows the individual to click 'Cancel' in the dialog.                         
                        if (password == null)
                                  return;
                             count++;
                        }while (!password.equals("dcba"));
                   /* The AdminList Frame is created with specificed size and location,
                   and then made visible. */
                   AdminList f = new AdminList();
    f.setSize(900,650);
    f.setLocation(20,20);
         f.setVisible(true);
              /* This method allows the user to see the Welcome Message and take the
              Career Advisor questionaire. It has the same features of the
              administrator() method. */
              private void user()
                   String password = null;
                   ColoredJOptionPane c = new ColoredJOptionPane(new Color( 255,255,255));
                   int count =0;
                   do
                        if (count>3)
                             JOptionPane.showMessageDialog(
                                  null, "You have been timed out.", "Incorrect Password", 1);
                             System.exit(0);
                        password =
                             JOptionPane.showInputDialog(null,"Password:", "Login Screen", 1);
                        if (password == null)
                             return;     
                        count ++;
                   }while ( !password.equals("abcd") );
         String welcome = "Welcome ";
         // A sky blue color is the background of the dialog.
                   ColoredJOptionPane d = new ColoredJOptionPane(new Color( 176,226,255));
                   /* The string 'welcome' is put into a message dialog. The title on the
                   dialog is 'Career Advising Service'. */
                   JOptionPane.showMessageDialog
                        (null,welcome,"Career Advising Service", 1);
    // The CareerAdvisor frame with the question panel is shown.
    CareerAdvisorFrame frame = new CareerAdvisorFrame();
    frame.setSize(850,400);
    frame.setLocation(55,180);
    frame.setVisible(true);
         // Background image is being painted onto the start panel.
         protected void paintComponent(Graphics g)
              // Scale image to size of component
              Dimension d = getSize();
              g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
              super.paintComponent(g);

  • Illegal start of expression and cannot resolve symbol HELP

    Can someone pls help me?
    These are the two problems:
    --------------------Configuration: j2sdk1.4.1_02 <Default>--------------------
    C:\Documents and Settings\Laila\My Documents\CMT2080\Coursework\Game\Mindboggler.java:291: illegal start of expression
    public void inputJButtonActionPerformed( ActionEvent event )
    ^
    C:\Documents and Settings\Laila\My Documents\CMT2080\Coursework\Game\Mindboggler.java:285: cannot resolve symbol
    symbol: method inputJButtonActionPerformed (java.awt.event.ActionEvent)
                   inputJButtonActionPerformed( event);
    Here is my code :
    //Mind boggler quiz
    //Marcelyn Samson
    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.lang.*;
    public class Mindboggler extends JFrame
              // JPanel for welcome window
              private JPanel welcomeJPanel;
              private JPanel presetJPanel;
         private JLabel titleJLabel;
         private JLabel quizJLabel;
         private JLabel girlJLabel, headJLabel;
         private JLabel introJLabel;
         private JButton startJButton;
         // JPanel for questionone window
         private JPanel questiononeJPanel;
         private JLabel textJLabel;
         private JPanel becksJPanel;
         private JButton oneJButton, twoJButton, threeJButton, fourJButton, nextJButton;
              //JPanel for questiontwo window
              private JPanel questiontwoJPanel;
              private JPanel orlandoJPanel;
              private JLabel q2JLabel;
              private JCheckBox lordJCheckBox;
              private JCheckBox faceJCheckBox;
              private JCheckBox piratesJCheckBox;
              private JButton next2JButton;
         private JButton inputJButton;
         //JPanel for questionthree
         private JPanel questionthreeJPanel;
         private JPanel howmuchJPanel;
         private JLabel howmuchJLabel;
         private JLabel nameJLabel;
         private JTextField nameJTextField;
         private JLabel moneyJLabel;
         private JTextField moneyJTextField;
         private JButton next3JButton;
         //Publics
         public JPanel welcomeJFrame, questionJFrame, questiontwoJFrame, questionthreeJFrame;
         //contentPane
              public Container contentPane;
              //no argument constructor
              public Mindboggler()
                   createUserInterface();
              //create and position components
              private void createUserInterface()/////////////////////////; semo colon do not edit copy paste
                   //get contentPane and set layout to null
                   contentPane = getContentPane();
                   contentPane.setLayout ( null );
                   welcome();
                   //set properties of applications window
                   setTitle( "Mindboggler" ); // set JFrame's title bar string
              setSize( 600, 400 ); // set width and height of JFrame
              setVisible( true ); // display JFrame on screen
              } // end method createUserInterface
              public void welcome(){
                        // set up welcomeJPanel
                   welcomeJPanel = new JPanel();
                   welcomeJPanel.setLayout( null );
                   welcomeJPanel.setBounds(0, 0, 600, 400);
                   welcomeJPanel.setBackground( Color.GREEN );
                   // set up textJLabel
                   titleJLabel = new JLabel();
                   titleJLabel.setText( "Mind Boggler" );
                   titleJLabel.setLocation( 30, 10);
                   titleJLabel.setSize( 550, 70);
                   titleJLabel.setFont( new Font( "SansSerif", Font.PLAIN, 30 ) );
                   titleJLabel.setHorizontalAlignment( JLabel.CENTER );
                   welcomeJPanel.add( titleJLabel );
                   // set up presetJPanel
                   presetJPanel = new JPanel();
                   presetJPanel.setLayout( null );
                   presetJPanel.setBounds( 150, 10, 300, 80 );
                   presetJPanel.setBackground( Color.GRAY );
                   welcomeJPanel.add( presetJPanel );
                   //setup Intro JLabel
                   introJLabel = new JLabel();
                   introJLabel.setText( "Think, think, think. Can you get all the questions right?" );
                   introJLabel.setBounds( 40, 100, 500, 200 );
                   introJLabel.setFont( new Font( "SansSerif", Font.PLAIN, 18 ) );
                   introJLabel.setHorizontalAlignment( JLabel.CENTER );
                   welcomeJPanel.add(introJLabel);
                   //set up head JLabel
                   headJLabel = new JLabel();
                   headJLabel.setIcon( new ImageIcon( "head.jpeg") );
                   headJLabel.setBounds( 540, 5, 40, 160 );
                   headJLabel.setHorizontalAlignment( JLabel.CENTER );
                   welcomeJPanel.add(headJLabel);
                        //setup girlJLabel
                   girlJLabel = new JLabel();
                   girlJLabel.setIcon( new ImageIcon( "girl.Jjpeg") );
                   girlJLabel.setBounds( 5, 10, 60, 100 );
                   girlJLabel.setHorizontalAlignment( JLabel.CENTER );
                   welcomeJPanel.add(girlJLabel);
                        //set up startJbutton
                   startJButton = new JButton();
                   startJButton.setText( "Start" );
                   startJButton.setBounds(250, 300, 100, 30);
                   startJButton.setFont( new Font( "SansSerif", Font.BOLD, 14) );
                   welcomeJPanel.add(startJButton);
                   contentPane.add(welcomeJPanel);
                   startJButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed(ActionEvent e){
                                  question();
              public void question()
                   //set up question one JPanel
                   welcomeJPanel.setVisible(false);
                   questiononeJPanel = new JPanel();
         questiononeJPanel.setLayout( null );
              questiononeJPanel.setBounds(0, 0, 600,400);
              questiononeJPanel.setBackground( Color.GREEN );
              // set up textJLabel
              textJLabel = new JLabel();
              textJLabel.setText( "Who did Beckham supposedly cheat with?" );
              textJLabel.setLocation( 20, 20);
              textJLabel.setSize( 550, 70);
              textJLabel.setFont( new Font( "SansSerif", Font.BOLD, 20 ) );
              textJLabel.setHorizontalAlignment( JLabel.CENTER );
              questiononeJPanel.add( textJLabel );
                   // set up presetJPanel
              becksJPanel = new JPanel();
              becksJPanel.setLayout( null );
              becksJPanel.setBorder( new TitledBorder(
         "Question 1" ) );
              becksJPanel.setBounds( 10, 10, 570, 80 );
              becksJPanel.setBackground( Color.GRAY );
              questiononeJPanel.add( becksJPanel );
                   // set up oneJButton
              oneJButton = new JButton();
              oneJButton.setBounds( 10, 120, 300, 40 );
              oneJButton.setText( "Britney Spears" );
              oneJButton.setBackground( Color.ORANGE );
              questiononeJPanel.add( oneJButton );
              // set up twoJButton
              twoJButton = new JButton();
              twoJButton.setBounds( 10, 180, 300, 40 );
              twoJButton.setText( "Meg Ryan" );
              twoJButton.setBackground( Color.ORANGE );
              questiononeJPanel.add( twoJButton );
              // set up threeJButton
              threeJButton = new JButton();
              threeJButton.setBounds( 10, 240, 300, 40 );
              threeJButton.setText( "Rebecca Loos" );
              threeJButton.setBackground( Color.ORANGE );
              questiononeJPanel.add( threeJButton );
              // set up fourJButton
              fourJButton = new JButton();
              fourJButton.setBounds( 10, 300, 300, 40 );
              fourJButton.setText( "Angelina Jolie" );
              fourJButton.setBackground( Color.ORANGE );
              questiononeJPanel.add( fourJButton );
                   // set up nextJButton
                   nextJButton = new JButton();
                   nextJButton.setBounds ( 375, 300, 150, 40 );
                   nextJButton.setText("Next");
                   nextJButton.setBackground( Color.GRAY );
                   questiononeJPanel.add( nextJButton );
                   contentPane.add(questiononeJPanel);
              nextJButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed(ActionEvent e){
                                  questiontwo();
              public void questiontwo()
                   //set up question two JPanel
                   questiononeJPanel.setVisible(false);
                   questiontwoJPanel=new JPanel();
                   questiontwoJPanel.setLayout(null);
                   questiontwoJPanel.setBounds(0, 0, 600, 400);
                   questiontwoJPanel.setBackground( Color.GREEN );
                   // set up q2JLabel
              q2JLabel = new JLabel();
              q2JLabel.setBounds( 20, 20, 550, 70 );
              q2JLabel.setText( "What films has Orlando Bloom starred in?" );
              q2JLabel.setFont(new Font( "SansSerif", Font.BOLD, 20 ) );
         q2JLabel.setHorizontalAlignment( JLabel.CENTER );
    questiontwoJPanel.add(q2JLabel);
    //set up orlandoJPanel
    orlandoJPanel = new JPanel();
    orlandoJPanel.setLayout(null);
    orlandoJPanel.setBorder( new TitledBorder("Question 2"));
    orlandoJPanel.setBounds( 10, 10, 570, 80);
    orlandoJPanel.setBackground(Color.GRAY);
    questiontwoJPanel.add(orlandoJPanel);
    // set up lordJCheckBox
              lordJCheckBox = new JCheckBox();
              lordJCheckBox.setBounds( 16, 112, 200, 24 );
              lordJCheckBox.setText( "1. Lord of The Rings" );
              questiontwoJPanel.add( lordJCheckBox );
                   // set up faceJCheckBox
              faceJCheckBox = new JCheckBox();
              faceJCheckBox.setBounds( 16, 159, 200, 24 );
              faceJCheckBox.setText( "2. Face Off" );
              questiontwoJPanel.add( faceJCheckBox );
              // set up piratesJCheckBox
              piratesJCheckBox = new JCheckBox();
              piratesJCheckBox.setBounds( 16, 206, 200, 24 );
              piratesJCheckBox.setText( "3. Pirates of The Caribean" );
              questiontwoJPanel.add( piratesJCheckBox );
              // set up inputJButton
              inputJButton = new JButton();
              inputJButton.setBounds(20, 256, 200, 21 );
              inputJButton.setText( "Input answer" );
              questiontwoJPanel.add( inputJButton );
    inputJButton.addActionListener(
         new ActionListener()
              //event handler called when user clicks inputJButton
              public void actionPerformed( ActionEvent event )
                   inputJButtonActionPerformed( event);
    //show JOptionMessages when user clicks on JCheckBoxes and inputJButton
    public void inputJButtonActionPerformed( ActionEvent event )
         //display error message if no JCheckBoxes is checked
         if ( ( !lordJCheckBox.isSelected() && !faceJCheckBox.isSelected() && !piratesJCheckBox.isSelected() ) )
              //display error message
              JOptionPane.showMessageDialog( null, "Please check two boxes", JOptionPane.ERROR_MESSAGE );
         // if lordjcheckbox and pirates is selected = right
         else
              if ( ( lordJCheckBox.isSelected() && piratesJCheckBox.isSelected() ))
                   JOptionPane.showMessageDialog(null, "Thats RIGHT!");
              //if others are selected = wrong
              else
                   if ( (lordJCheckBox.isSelected() && faceJCheckBox.isSelected() ))
                        JOptionPane.showMessageDialog(null, "Thats WRONG");
                   else
                        ( (faceJCheckBox.isSelected() && piratesJCheckBox.isSelected() ))
                             JOptionPane.showMessageDialog(null, "Thats WRONG");
    // set up nest2JButton
              next2JButton = new JButton();
              next2JButton.setBounds( 155, 296, 94, 24 );
              next2JButton.setText( "Next" );
              questiontwoJPanel.add( next2JButton );
    contentPane.add(questiontwoJPanel);
    next2JButton.addActionListener(
         new ActionListener(){
              public void actionPerformed(ActionEvent e){
                   questionthree();
    } // end questiontwo
    public void questionthree()
         //setup questionthree JPanel
         questiontwoJPanel.setVisible(false);
         questionthreeJPanel = new JPanel();
         questionthreeJPanel.setLayout(null);
         questionthreeJPanel.setBounds(0, 0, 600, 400);
         questionthreeJPanel.setBackground( Color.GREEN);
              // main method
              public static void main( String[] args )
              Mindboggler application = new Mindboggler();
              application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              } // end method main
    }// end class
    WOULD BE VERY GEATFUL

    Just want to say thank you by the way for trying to help. Ive moved public void inputJButtonActionPerformed( ActionEvent event ) outside of brackets. Now i have a different problem on it. Sorry about this.
    PROBLEM: --------------------Configuration: <Default>--------------------
    C:\Documents and Settings\Laila\My Documents\CMT2080\Coursework\Game\Mindboggler.java:353: 'else' without 'if'
    else ( ( !lordJCheckBox.isSelected() && !faceJCheckBox.isSelected && !piratesJCheckBox.isSelected() ) )
    ^
    1 error
    Process completed.
    MY CODE:
    //Mind boggler quiz
    //Marcelyn Samson
    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.lang.*;
    public class Mindboggler extends JFrame
              // JPanel for welcome window
              private JPanel welcomeJPanel;
              private JPanel presetJPanel;
         private JLabel titleJLabel;
         private JLabel quizJLabel;
         private JLabel girlJLabel, headJLabel;
         private JLabel introJLabel;
         private JButton startJButton;
         // JPanel for questionone window
         private JPanel questiononeJPanel;
         private JLabel textJLabel;
         private JPanel becksJPanel;
         private JButton oneJButton, twoJButton, threeJButton, fourJButton, nextJButton;
              //JPanel for questiontwo window
              private JPanel questiontwoJPanel;
              private JPanel orlandoJPanel;
              private JLabel q2JLabel;
              private JCheckBox lordJCheckBox;
              private JCheckBox faceJCheckBox;
              private JCheckBox piratesJCheckBox;
              private JButton next2JButton;
         private JButton inputJButton;
         //JPanel for questionthree
         private JPanel questionthreeJPanel;
         private JPanel howmuchJPanel;
         private JLabel howmuchJLabel;
         private JLabel nameJLabel;
         private JTextField nameJTextField;
         private JLabel moneyJLabel;
         private JTextField moneyJTextField;
         private JButton next3JButton;
         //Publics
         public JPanel welcomeJFrame, questionJFrame, questiontwoJFrame, questionthreeJFrame;
         //contentPane
              public Container contentPane;
              //no argument constructor
              public Mindboggler()
                   createUserInterface();
              //create and position components
              private void createUserInterface()/////////////////////////; semo colon do not edit copy paste
                   //get contentPane and set layout to null
                   contentPane = getContentPane();
                   contentPane.setLayout ( null );
                   welcome();
                   //set properties of applications window
                   setTitle( "Mindboggler" ); // set JFrame's title bar string
              setSize( 600, 400 ); // set width and height of JFrame
              setVisible( true ); // display JFrame on screen
              } // end method createUserInterface
              public void welcome(){
                        // set up welcomeJPanel
                   welcomeJPanel = new JPanel();
                   welcomeJPanel.setLayout( null );
                   welcomeJPanel.setBounds(0, 0, 600, 400);
                   welcomeJPanel.setBackground( Color.GREEN );
                   // set up textJLabel
                   titleJLabel = new JLabel();
                   titleJLabel.setText( "Mind Boggler" );
                   titleJLabel.setLocation( 30, 10);
                   titleJLabel.setSize( 550, 70);
                   titleJLabel.setFont( new Font( "SansSerif", Font.PLAIN, 30 ) );
                   titleJLabel.setHorizontalAlignment( JLabel.CENTER );
                   welcomeJPanel.add( titleJLabel );
                   // set up presetJPanel
                   presetJPanel = new JPanel();
                   presetJPanel.setLayout( null );
                   presetJPanel.setBounds( 150, 10, 300, 80 );
                   presetJPanel.setBackground( Color.GRAY );
                   welcomeJPanel.add( presetJPanel );
                   //setup Intro JLabel
                   introJLabel = new JLabel();
                   introJLabel.setText( "Think, think, think. Can you get all the questions right?" );
                   introJLabel.setBounds( 40, 100, 500, 200 );
                   introJLabel.setFont( new Font( "SansSerif", Font.PLAIN, 18 ) );
                   introJLabel.setHorizontalAlignment( JLabel.CENTER );
                   welcomeJPanel.add(introJLabel);
                   //set up head JLabel
                   headJLabel = new JLabel();
                   headJLabel.setIcon( new ImageIcon( "head.jpeg") );
                   headJLabel.setBounds( 540, 5, 40, 160 );
                   headJLabel.setHorizontalAlignment( JLabel.CENTER );
                   welcomeJPanel.add(headJLabel);
                        //setup girlJLabel
                   girlJLabel = new JLabel();
                   girlJLabel.setIcon( new ImageIcon( "girl.Jjpeg") );
                   girlJLabel.setBounds( 5, 10, 60, 100 );
                   girlJLabel.setHorizontalAlignment( JLabel.CENTER );
                   welcomeJPanel.add(girlJLabel);
                        //set up startJbutton
                   startJButton = new JButton();
                   startJButton.setText( "Start" );
                   startJButton.setBounds(250, 300, 100, 30);
                   startJButton.setFont( new Font( "SansSerif", Font.BOLD, 14) );
                   welcomeJPanel.add(startJButton);
                   contentPane.add(welcomeJPanel);
                   startJButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed(ActionEvent e){
                                  question();
              public void question()
                   //set up question one JPanel
                   welcomeJPanel.setVisible(false);
                   questiononeJPanel = new JPanel();
         questiononeJPanel.setLayout( null );
              questiononeJPanel.setBounds(0, 0, 600,400);
              questiononeJPanel.setBackground( Color.GREEN );
              // set up textJLabel
              textJLabel = new JLabel();
              textJLabel.setText( "Who did Beckham supposedly cheat with?" );
              textJLabel.setLocation( 20, 20);
              textJLabel.setSize( 550, 70);
              textJLabel.setFont( new Font( "SansSerif", Font.BOLD, 20 ) );
              textJLabel.setHorizontalAlignment( JLabel.CENTER );
              questiononeJPanel.add( textJLabel );
                   // set up presetJPanel
              becksJPanel = new JPanel();
              becksJPanel.setLayout( null );
              becksJPanel.setBorder( new TitledBorder(
         "Question 1" ) );
              becksJPanel.setBounds( 10, 10, 570, 80 );
              becksJPanel.setBackground( Color.GRAY );
              questiononeJPanel.add( becksJPanel );
                   // set up oneJButton
              oneJButton = new JButton();
              oneJButton.setBounds( 10, 120, 300, 40 );
              oneJButton.setText( "Britney Spears" );
              oneJButton.setBackground( Color.ORANGE );
              questiononeJPanel.add( oneJButton );
              // set up twoJButton
              twoJButton = new JButton();
              twoJButton.setBounds( 10, 180, 300, 40 );
              twoJButton.setText( "Meg Ryan" );
              twoJButton.setBackground( Color.ORANGE );
              questiononeJPanel.add( twoJButton );
              // set up threeJButton
              threeJButton = new JButton();
              threeJButton.setBounds( 10, 240, 300, 40 );
              threeJButton.setText( "Rebecca Loos" );
              threeJButton.setBackground( Color.ORANGE );
              questiononeJPanel.add( threeJButton );
              // set up fourJButton
              fourJButton = new JButton();
              fourJButton.setBounds( 10, 300, 300, 40 );
              fourJButton.setText( "Angelina Jolie" );
              fourJButton.setBackground( Color.ORANGE );
              questiononeJPanel.add( fourJButton );
                   // set up nextJButton
                   nextJButton = new JButton();
                   nextJButton.setBounds ( 375, 300, 150, 40 );
                   nextJButton.setText("Next");
                   nextJButton.setBackground( Color.GRAY );
                   questiononeJPanel.add( nextJButton );
                   contentPane.add(questiononeJPanel);
              nextJButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed(ActionEvent e){
                                  questiontwo();
              public void questiontwo()
                   //set up question two JPanel
                   questiononeJPanel.setVisible(false);
                   questiontwoJPanel=new JPanel();
                   questiontwoJPanel.setLayout(null);
                   questiontwoJPanel.setBounds(0, 0, 600, 400);
                   questiontwoJPanel.setBackground( Color.GREEN );
                   // set up q2JLabel
              q2JLabel = new JLabel();
              q2JLabel.setBounds( 20, 20, 550, 70 );
              q2JLabel.setText( "What films has Orlando Bloom starred in?" );
              q2JLabel.setFont(new Font( "SansSerif", Font.BOLD, 20 ) );
         q2JLabel.setHorizontalAlignment( JLabel.CENTER );
    questiontwoJPanel.add(q2JLabel);
    //set up orlandoJPanel
    orlandoJPanel = new JPanel();
    orlandoJPanel.setLayout(null);
    orlandoJPanel.setBorder( new TitledBorder("Question 2"));
    orlandoJPanel.setBounds( 10, 10, 570, 80);
    orlandoJPanel.setBackground(Color.GRAY);
    questiontwoJPanel.add(orlandoJPanel);
    // set up lordJCheckBox
              lordJCheckBox = new JCheckBox();
              lordJCheckBox.setBounds( 16, 112, 200, 24 );
              lordJCheckBox.setText( "1. Lord of The Rings" );
              questiontwoJPanel.add( lordJCheckBox );
                   // set up faceJCheckBox
              faceJCheckBox = new JCheckBox();
              faceJCheckBox.setBounds( 16, 159, 200, 24 );
              faceJCheckBox.setText( "2. Face Off" );
              questiontwoJPanel.add( faceJCheckBox );
              // set up piratesJCheckBox
              piratesJCheckBox = new JCheckBox();
              piratesJCheckBox.setBounds( 16, 206, 200, 24 );
              piratesJCheckBox.setText( "3. Pirates of The Caribean" );
              questiontwoJPanel.add( piratesJCheckBox );
              // set up inputJButton
              inputJButton = new JButton();
              inputJButton.setBounds(20, 256, 200, 21 );
              inputJButton.setText( "Input answer" );
              questiontwoJPanel.add( inputJButton );
    inputJButton.addActionListener(
         new ActionListener()
              //event handler called when user clicks inputJButton
              public void actionPerformed( ActionEvent event )
                   inputJButtonActionPerformed( event);
    // set up nest2JButton
              next2JButton = new JButton();
              next2JButton.setBounds( 155, 296, 94, 24 );
              next2JButton.setText( "Next" );
              questiontwoJPanel.add( next2JButton );
    contentPane.add(questiontwoJPanel);
    next2JButton.addActionListener(
         new ActionListener(){
              public void actionPerformed(ActionEvent e){
                   questionthree();
    } // end questiontwo
    public void questionthree()
         //setup questionthree JPanel
         questiontwoJPanel.setVisible(false);
         questionthreeJPanel = new JPanel();
         questionthreeJPanel.setLayout(null);
         questionthreeJPanel.setBounds(0, 0, 600, 400);
         questionthreeJPanel.setBackground( Color.GREEN);
         //setup howmuchJLabel
         howmuchJLabel = new JLabel();
         howmuchJLabel.setText("I'm a student and would be very greatful if you could donate some money as it would help me very much.");
         howmuchJLabel.setBounds(20, 20, 550, 70);
         howmuchJLabel.setFont(new Font("SansSerif",Font.BOLD,14));
         howmuchJLabel.setHorizontalAlignment(JLabel.CENTER);
         questionthreeJPanel.add(howmuchJLabel);
         //setup howmuchJPanel
         howmuchJPanel = new JPanel();
         howmuchJPanel.setLayout(null);
         howmuchJPanel.setBorder( new TitledBorder("Question 3"));
         howmuchJPanel.setBounds(10, 10, 570, 80);
         howmuchJPanel.setBackground( Color.GRAY);
         questionthreeJPanel.add(howmuchJPanel);
         //setup nameJLabel
         nameJLabel = new JLabel();
         nameJLabel.setText("Name");
         nameJLabel.setBounds(10, 160, 150, 24);
         nameJLabel.setFont(new Font("SansSerif",Font.BOLD,12));
         questionthreeJPanel.add(nameJLabel);
         //setup nameJTextField
         nameJTextField = new JTextField();
         nameJTextField.setBounds(125, 160, 200, 24 );
         questionthreeJPanel.add(nameJTextField);
         contentPane.add(questionthreeJPanel);
         //show JOptionMessages when user clicks on JCheckBoxes and inputJButton
    public void inputJButtonActionPerformed( ActionEvent event )
         //display error message if no JCheckBoxes is checked
         else ( ( !lordJCheckBox.isSelected() && !faceJCheckBox.isSelected && !piratesJCheckBox.isSelected() ) )
              //display error message
              JOptionPane.showMessageDialog( null, "Please check two boxes", JOptionPane.ERROR_MESSAGE );
         // if lordjcheckbox and pirates is selected = right
         else
              if ( ( lordJCheckBox.isSelected() && piratesJCheckBox.isSelected() ))
                   JOptionPane.showMessageDialog(null, "Thats RIGHT!");
              //if others are selected = wrong
              else
                   if ( (lordJCheckBox.isSelected() && faceJCheckBox.isSelected() ))
                        JOptionPane.showMessageDialog(null, "Thats WRONG");
                   else
                        ( (faceJCheckBox.isSelected() && piratesJCheckBox.isSelected() ))
                             JOptionPane.showMessageDialog(null, "Thats WRONG");
              // main method
              public static void main( String[] args )
              Mindboggler application = new Mindboggler();
              application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              } // end method main
    }// end class

  • Beginners Questions about Multiple JPanels in JFrame and event handling

    I am a newbie with SWING, and even a newerbie in Event Handling. So here goes.
    I am writing a maze program. I am placing a maze JPanel (MazePanel) at the center of a JFrame, and a JPanel of buttons (ButtonPanel) on the SOUTH pane. I want the buttons to be able to re-randomize the maze, solve the maze, and also ouput statistics (for percolation theory purposes). I have the backbone all done already, I am just creating the GUI now. I am just figuring out EventHandlers and such through the tutorials, but I have a question. I am adding an ActionListener to the buttons which are on the ButtonPanel which are on JFrame (SOUTH) Panel. But who do I make the ActionListener--Basically the one doing the work when the button is pressed. Do I make the JFrame the ActionListener or the MazePanel the ActionListener. I need something which has access to the maze data (the backbone), and which can call the Maze.randomize() function. I'm trying to make a good design and not just slop too.
    Also I was wondering if I do this
    JButton.addActionListener(MazePanel), and lets say public MazePanel implments ActionListenerdoesn't adding this whole big object to another object (namely the button actionlistener) seem really inefficient? And how does something that is nested in a JPanel on JFrame x get information from something nested in another JPanel on a JFrame x.
    Basically how is the Buttons going to talk to the maze when the maze is so far away?

    I'm not an expert, but here's what I'd do....
    You already have your business logic (the Maze classes), you said. I'm assuming you have some kind of public interface to this business logic. I would create a new class like "MazeGui" that extends JFrame, and then create the GUI using this class. Add buttons and panels as needed to get it to look the way you want. Then for each button that does a specific thing, add an anonymous ActionListener class to it and put whatever code you need inside the ActionListener that accesses the business logic classes and does what it needs to.
    This is the idea, though my code is totally unchecked and won't compile:
    import deadseasquirrels.mazestuff.*;
    public class MazeGui extends JFrame {
      JPanel buttonPanel = new JPanel();
      JPanel mazePanel = new JPanel();
      JButton randomizeB = new JButton();
      JButton solveB = new JButton();
      JButton statsB = new JButton();
      // create instanc(es) of your Maze business logic class(es)
      myMaze = new MazeClass();
      // add the components to the MazeGui content pane
      Component cp = getContentPane();
      cp.add(); // this doesn't do anything, but in your code you'd add
                // all of your components to the MazeGui's contentpane
      randomizeB.addActionListener(new ActionListener {
        void actionPerformed() {
          Maze newMaze = myMaze.getRandomMazeLayout();
          mazePanel.setContents(newMaze); // this is not a real method!
                                          // it's just to give you the idea
                                          // of how to manipulate the JPanel
                                          // representing your Maze diagram,
                                          // you will probably be changing a
                                          // subcomponent of the JPanel
      solveB.addActionListener(new ActionListener {
        void actionPerformed() {
          Solution mySolution = myMaze.getSolution();
          mazePanel.setContents(mySolution); // again, this is not a real
                                             // method but it shows you how
                                             // the ActionListener can
                                             // access your GUI
      // repeat with any other buttons you need
      public static void main(String[] args) {
        MazeGui mg = new MazeGui();
        mg.setVisible(true);
        // etc...
    }

  • Simple question I think, add JPanel to JScrollPane

    I would imagine that for anyone with experience with Java this will be a simple problem. Why can't I add a JPanel to a JScrollPane using myScrollPane.Add(myPanel); ?? it seems to get hidden...
    This works correctly:
         //Create a panel
         JPanel panel = new JPanel(new FlowLayout());
         //Make it pink
         panel.setBackground(Color.pink);
         //Make it 400,400
         panel.setPreferredSize(new Dimension(400,400));
         //Create a Scrollpane
         JScrollPane scrollPane = new JScrollPane(panel);
         //Make it 300,300
         scrollPane.setPreferredSize(new Dimension(300,300));
         //Create a JFrame
         JFrame frame = new JFrame("Test Scrollpane");
         frame.setLayout(new FlowLayout());
         //Set close operation
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Set its size
         frame.setSize(600,600);
         //Add Scrollpane to JFrame
         frame.add(scrollPane);
         //Show it
         frame.setVisible(true);
    This doesnt:
         //Create a panel
         JPanel panel = new JPanel(new FlowLayout());
         //Make it pink
         panel.setBackground(Color.pink);
         //Make it 400,400
         panel.setPreferredSize(new Dimension(400,400));
         //Create a Scrollpane
         JScrollPane scrollPane = new JScrollPane();
         scrollPane.add(panel);
         //Make it 300,300
         scrollPane.setPreferredSize(new Dimension(300,300));
         //Create a JFrame
         JFrame frame = new JFrame("Test Scrollpane");
         frame.setLayout(new FlowLayout());
         //Set close operation
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Set its size
         frame.setSize(600,600);
         //Add Scrollpane to JFrame
         frame.add(scrollPane);
         //Show it
         frame.setVisible(true);

    rcfearn wrote:
    I would appreciate it you could read the sample code, I am asking the question as to why I have to do this? For structural reasons I don't want to have to add the JPanel during instatiation of the JScrollPane...Please read the [jscrollpane api.|http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html] To display something in a scroll pane you need to add it not to the scroll pane but to its viewport. If you add the component in the scroll pane's constructor, then it will be automatically added to the viewport. if you don't and add the component later, then you must go out of your way to be sure that it is added to the viewport with:
    JScrollPane myScrollPane = new JScrollPane();
    myScrollPane.getViewport().add(myComponent);

  • Question about relative sizing on JPanels

    Hi,
    My question is about relative sizing on components that are not drawn yet. For example I want to draw a JLabel on the 3rd quarter height of a JPanel. But JPanel's height is 0 as long as it is not drawn on the screen. Here is a sample code:
    JPanel activityPnl = new JPanel();
    private void buildActivityPnl(){
            //setting JPanel's look and feel
            activityPnl.setLayout(null);
            activityPnl.setBackground(Color.WHITE);
            int someValue = 30;  // I use this value to decide the width of my JPanel
            activityPnl.setPreferredSize(new Dimension(someValue, 80));
            //The JLabel's height is 1 pixel and its width is equal to the JPanel's width. I want to draw it on the 3/4 of the JPanel's height
            JLabel timeline = new JLabel();
            timeline.setOpaque(true);
            timeline.setBackground(Color.RED);
            timeline.setBounds(0, (activityPnl.getSize().height * 75) / 100 , someValue , 1);
            activityPnl.add(timeline);
        }Thanks a lot for your help
    SD
    Edited by: swingDeveloper on Feb 24, 2010 11:41 PM

    And use a layout manager. It can adjust automatically for a change in the frame size.
    Read the Swing tutorial on Using Layout Managers for examples of the different layout managers.

  • Ridiculously dumb question about drawing in JPanel

    Howdy everyone,
    I gotta really stupid question that I cant figure out the answer to. How do I draw an image to a JPanel, when my class inherits from JFrame?
    Thanks,
    Rick

    Ok,
    Problem. The image isnt showing up in the Frame I set up for it. Heres my code. Im trying to get this image to show up in a scollable window. Can anyone tell what the problem with this code is??
    JPanel imgPanel= new JPanel(){
    protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(getToolkit().createImage(imstr),imgw,imgh,this);
    imgPanel.setVisible(true);
    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(new JScrollPane(imgPanel));
    this.setVisible(true);
    Any ideas?
    Thanks
    Rick

  • A question about how to change a button in a JPanel during runtime

    I am a beginner of GUI. Now I am trying to change a specific component, a button, when the application is running. For example, I have 3 buttons in a JPanel. Each button has its onw icon. If I click one of them, it will change its icon, but the other two don't change. I don't know if there is any method for changing a specific component during runtime. If any one knows please let me know, I will appreciate that very much!!!

    What you're going to have to do is loop inside the actionlistener but still have accessability to click while its looping. I don't know much about it, but I think you're going to need a thread. Try something like this... (it doesn't work yet, but I have to take off)
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class buttonxdemo extends JFrame implements ActionListener{
      Buttonx mybutton;
      //set it all up, make it look pretty  =]
      public buttonxdemo()
           mybutton = new Buttonx("default");
           getContentPane().add(mybutton.thebutton);
           mybutton.thebutton.addActionListener(this);
           this.setDefaultCloseOperation(3);
           this.setSize(200,200);
      public void actionPerformed(ActionEvent ae){
        if (ae.getSource() == mybutton.thebutton)
             if (mybutton.keepGoing)
               mybutton.keepGoing = false;
                else if (!mybutton.keepGoing)
                     mybutton.keepGoing = true;     
          mybutton = new Buttonx(/*Icon,*/"My Button");
          //getContentPane().remove(mybutton);
          //getContentPane().add(mybutton.thebutton);
          mybutton.startstop();
      }//actionperformed
      static void main(String args[])
           new buttonxdemo().show();
    } //movingicondemo
    class Buttonx extends Thread{
      public boolean keepGoing;
      //public Icon ICx;            //perhaps an array, so you can loop through?
      public String strbuttonx;
      public JButton thebutton;     //may have to extend JFrame?
      public Buttonx(/*Icon IC,*/ String strbutton){
        //ICx = IC;
        strbuttonx = strbutton;
        thebutton = new JButton(strbuttonx);
      public void startstop()
        int i = 0;
        while (keepGoing)
          thebutton.setLabel(strbuttonx.substring(0,i));
          //if an array of Icons ICx
          //thebutton.setIcon(ICx);
    i++;
    if (i > strbuttonx.length() - 1)
    i = 0;
    try
         Thread.sleep(1000);
    catch (InterruptedException ie)
         System.out.println("sleep caught: " + ie);
    }//startstop()
    }//buttonx
    kev

  • JFRAME- JPANEL question

    I have a JFrame that holds a JPanel. If that JPanel needs to contact the JFrame how do I get access to parent? I tried panelname.getParent, when I did I got a
    java.lang.ClassCastException
    Any help would be great.
    Brock

    i think you have to buid your own JPanel class lyke this:
    public class MyJPanel extends JPanel{
    JFrame parent;
    public MyJPanel(JFrame p){
    parent = p;
    // here you have access to the parent JFrame in your JPanel
    public JFrame getParentFrame(){
    return parent;
    // here you return the parent of the JPanel
    so in your JFrame class you add the JPanel like this:
    getContentPane().add(new MyJpanel(this));
    i hope it helps you. :)

Maybe you are looking for

  • Error while transporting table entries to QA

    Hi All, I am working on system 4.6C i have a ztale with 3 key fields. I have added entries in table sucessfully. While imprting to Quality system. key field1   2183 Key field2  A Key field3  CHF It returns an return code with message called 'key of t

  • IDOC-to-JDBC Scenario

    Hi All, We have a scenario where we are sending idocs from SAP to XI and the same is working fine but we are not able to send the acknowledgements back from XI to SAP. Can anyone pls let us know how to get the acknowledgements. Also in the SXMB_MONI

  • (ABAP+JAVA) system is too big to export/import

    We have some NW04s and ECC6 dual stack systems that we want to frequently clone using homogeneous system copy method. However they can be as big as many terabytes. Is there a way to clone they using a way other than export/import? Thanks!

  • CIN : Error in J1iex

    Hi All,   I posted J1iex w.r.t GRN with Quantity 112.But credit availed only for 12 Quantity.Remaining 100 quantity comes under Inventorized duty.Excise invoice Quantity and GRN Quantity is same (112).Please clarify Regards SAP MM

  • Uploading vendor ope items

    Hi In uploading open items for vendor I have tried F_43 but one of the required fields the client require is purchase order no which is not available in F_43. The reference field is used for something else already. Pls is there any other Tcode i can