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

Similar Messages

  • How to force to wait and get input from a jframe-jpanel?

    I would like to use a jframe-jpanel to get user input instead of using JOptionPane.showInputDialog since there will be more than 1 input.
    But I could not do it. The code reads the panel lines and passes to other lines below without waiting for the okay button to be pressed.
    This is the part of code of my main frame;
    jLabel10.setText(dene.toString());
    if (dene == 0) {
    // todo add button input panel
    //String todo_write = JOptionPane.showInputDialog("Please enter a todo item");
    JFrame frameTodoAddInput = new JFrame( "Please input..." );
    TodoAddAsk1JPanel todoaddpanel = new TodoAddAsk1JPanel();
    frameTodoAddInput.add(todoaddpanel);
    frameTodoAddInput.setSize( 600, 200 ); // set frame size
    frameTodoAddInput.setLocation(300, 300);
    //String todo_write = todoaddpanel.getNewTodoItem();
    String todo_write = todoaddpanel.getNewTodoItem();
    jLabel10.setText("Satir 1822 de".concat(todo_write));
    // end of todo add button input panel
    todoTextPane1.setText(todo_write);
    This is the code of input panel;
    * TodoAddAsk1JPanel.java
    * Created on May 6, 2007, 12:03 AM
    package javaa;
    public class TodoAddAsk1JPanel extends javax.swing.JPanel {
    /** Creates new form TodoAddAsk1JPanel */
    public TodoAddAsk1JPanel() {
    initComponents();
    private String NewTodoItem = "";
    public String getNewTodoItem() {
    NewTodoItem = ANewTodoItemTextField.getText();
    return this.NewTodoItem;
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    ANewTodoItemTextField = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    PriorityComboBox = new javax.swing.JComboBox();
    jLabel3 = new javax.swing.JLabel();
    DayValueComboBox = new javax.swing.JComboBox();
    MonthValueComboBox = new javax.swing.JComboBox();
    YearValueComboBox = new javax.swing.JComboBox();
    OkayButton = new javax.swing.JButton();
    CancelButton = new javax.swing.JButton();
    TimeValueComboBox = new javax.swing.JComboBox();
    jLabel1.setText("Please enter a todo item:");
    jLabel2.setText("Please select its priority level:");
    PriorityComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A", "B", "C" }));
    jLabel3.setText("Please select its due date:");
    DayValueComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }));
    MonthValueComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }));
    YearValueComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030", "2031", "2032", "2033", "2034", "2035", "2036", "2037", "2038", "2039", "2040", "2041", "2042", "2043", "2044", "2045", "2046", "2047", "2048", "2049", "2050", "2051", "2052", "2053", "2054", "2055", "2056", "2057", "2058", "2059", "2060", "2061", "2062", "2063", "2064", "2065", "2066", "2067", "2068", "2069", "2070" }));
    OkayButton.setText("OK");
    OkayButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    OkayButtonActionPerformed(evt);
    CancelButton.setText("Cancel");
    TimeValueComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30", "00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00" }));
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(PriorityComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(ANewTodoItemTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(OkayButton, javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
    .addComponent(CancelButton))
    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
    .addComponent(DayValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(MonthValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(YearValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addGap(13, 13, 13)
    .addComponent(TimeValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(42, 42, 42)))
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(ANewTodoItemTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel1))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel2)
    .addComponent(PriorityComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel3)
    .addComponent(DayValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(MonthValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(YearValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(TimeValueComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(OkayButton)
    .addComponent(CancelButton))
    .addContainerGap())
    }// </editor-fold>
    private void OkayButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    NewTodoItem = ANewTodoItemTextField.getText();
    // Variables declaration - do not modify
    private javax.swing.JTextField ANewTodoItemTextField;
    private javax.swing.JButton CancelButton;
    private javax.swing.JComboBox DayValueComboBox;
    private javax.swing.JComboBox MonthValueComboBox;
    private javax.swing.JButton OkayButton;
    private javax.swing.JComboBox PriorityComboBox;
    private javax.swing.JComboBox TimeValueComboBox;
    private javax.swing.JComboBox YearValueComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration
    I want to get the resulted input of "NewTodoItem"
    Thanks in advance for your kind help.
    Guven

    Thank you very much for your help. But I would like
    to get 3 inputs from 1 window at the same time and I
    could not find any example code for JDialog for more
    than 1 input. If any body can show how to write this
    code, it would be appreciated.
    ThanksYou can write your own. A JDialog is a container just look a JFrame is.

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

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

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

  • Design issue using JFrame, JPanel, JLabel

    I have been working on this problems for several months now and I and nearly finished.
    I have a design question I hope others from this forum can provide some incite to the best approach.
    The problem space is a 8 X 8 Chessboard. I have designed a board using JPanels and JLables sitting inside a JFrame. In each square on the chessboard is a JLabel with an image. The "board" sits in the DEFAULT LAYER of a JLayeredPane. As the user clicks a specific square, a queen is placed in the square (8-queens problem). The only thing I do is swap out the image. All this works well--thanks to several of you from this forum. :-)
    When I add a new queen to the board, the application goes through the evaluation of attack positions. Next, the application should display the new chessboard with only the queens not threaten by other queens. I keep up with the chessboard using an boolean array internally. I build a second boolean array for the new or refreshed chessboard.
    What I want to do is build a second chessboard and "swap" it out with the one in the default layered pane. Can someone be so kind and shine some light on this design issue for me?
    Thank you for taking the time to read my post.

    I don't understand this approach. Swing is by default 'double buffered' and will not flicker. You will get this be default since this is one of the things the Swing painting model gives over AWT.
    You should look at just using JComponent and the paintComponent() method for drawing what you need.
    What I've done in the past is have a simple XML JDoM model. Have components that render themselves based on this model.
    Changing the model then I just issues a call to repaint() at the top level container.
    You can also add and remove items from the parent container. Then issue validate() or repaint(). Can't remember now but I think validate() hits the layout manager logic and then repaints.
    I'm pretty sure the Romain guy posted an example of how to easily draw a background chess board in a panel. ;-)
    The tree concept might really prove useful for a 'gaming tree' approach at the AI also.
    If you look at the Java3D API you will see they use a tree to represent what is rendered and the details about it. Really nice until you change something in the tree that cause the renderer to blow up. ;-)
    I guess the moral is always make small simple changes and test.
    Hope this is helpful.

  • JFrame/JPanel background

    How do I set the background of a JPanel or JFrame to a gif instead of just a color
    thanks

    Hi all!
    Hope this helps, it works for me...
    public class BackgroundPanel extends JPanel {
    BufferedImage background = null;
    public BackgroundPanel(String imagepath) {
    setDoubleBuffered(true);
    setBackground(new Color(255,255,255,0));
    try{
    background = ImageIO.read(new File(imagepath));
    catch(java.io.IOException ioe) {
    System.out.println("Shit happens!" + ioe.getMessage());
    public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage(background,0,0, background.getWidth(), background.getHeight(), this);
    super.paint(g);
    }

  • Urgent!!!!!!!! JFrame+JPanel problem

    How can I add a JFrame to a JPanel? What kind of objects can be contained Frames in at all?
    Thanks in advance

    Hi
    You cant add JFrame,JWindow,JApplet,JDialog to any other component.
    These are top level component and can not be added to any other.
    Ashish

  • JPanel Question

    Hello,
    How can i maximize the content in a JPanel to the maximum size of the JFrame, in my case it is a pdf, so in case of it being landscape and portrait it should show the page in the whole JFrame.
    I know that in order to get the size of the screen i can use:
    Toolkit toolkit = Toolkit.getDefaultToolkit();
               Dimension screenSize = toolkit.getScreenSize();Any ideias?

    Hi,
    Thanks for the feedback...
    It is already there...in the center.
    Because i have landscape and portrait pdfs, both are displayed in different ways. So what i want is a method that could resize it allways to a predifined layout.
    What do you think ?
    Regards

  • GUI Problem (Swing JFrame/JPanel). HELP!

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

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

  • SpringLayout in JPanel Question

    Is it possible to use SpringLayout's putConstraint() method in a JPanel? If so, how?

    Alright, well, I'll just throw up both classes that I am using because it looks like I have the same thing as you Joerg22, but the panel is still not showing up. The first class is the main frame which uses the second which is the panel. BTW, I can get this to work with GridLayout and BorderLayout, I just cannot figure out SpringLayout.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import frames1and2.insidePanel;
    public class EclipseFirst extends JFrame implements ActionListener
         private JButton butt;
         private Container c;
         private JLabel lblTest;
         private SpringLayout layout;
         private insidePanel panel;
         private EclipseFirst()
              // create insidePanel
              panel = new insidePanel();
              // create JButton
              butt = new JButton("Open Panel");
              // create JLabel
              lblTest = new JLabel("TEST WORKS");
              // Set Layout
              c = getContentPane();
              layout = new SpringLayout();
              c.setLayout(layout);
              c.add(butt);
              c.add(panel);
              // Place butt
              layout.putConstraint(SpringLayout.WEST, butt,
                                   10,
                             SpringLayout.WEST, c);
             layout.putConstraint(SpringLayout.NORTH, butt,
                             10,
                             SpringLayout.NORTH, c);
             // Place insidePanel
              layout.putConstraint(SpringLayout.WEST, panel,
                                   50,
                             SpringLayout.WEST, c);
             layout.putConstraint(SpringLayout.NORTH, panel,
                             50,
                             SpringLayout.NORTH, c);
             panel.setVisible(false);
             butt.addActionListener(this);
             this.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             System.exit(0);
              setSize(300, 300);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == butt)
                   panel.setVisible(true);
         public static void main (String [] args)
              EclipseFirst prog = new EclipseFirst();
    // Second Class
    package frames1and2;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import frames1and2.insidePanel;
    public class insidePanel extends JPanel
         private JLabel lblTest2;
         private JLabel lblTest3;
         private JLabel lblTest4;
         private SpringLayout layout;
         public insidePanel()
              lblTest2 = new JLabel("TEST 2 WORKS!");
              lblTest3 = new JLabel("TEST 3 WORKS!");
              lblTest4 = new JLabel("TEST 4 WORKS!");
              layout = new SpringLayout();
              setLayout(layout);
              add(lblTest2);
              // Place lblTest2
              layout.putConstraint(SpringLayout.WEST, lblTest2,
                                   5,
                             SpringLayout.WEST, this);
             layout.putConstraint(SpringLayout.NORTH, lblTest2,
                             5,
                             SpringLayout.NORTH, this);
    }

  • Multipule Jpanels question

    hello all,
    I'm createing an applet, and I'm using multipile jpanels. I want the panels to come up one after an other. The Jpanels will do the following. One will be the start frame I'll call it startPanel() it basically will ask the user names for two players, and to select a type of game. The next pane will have the panel of the selected game. The final panel will display the score for the game, and ask the user either to select an other game or quit. So as you see the panels need to wait for each other and the last panel will have to have a loop in that calls either board.
    I'm not sure if I am on the right track, but i think it may use something like this:
    /* I tried this and it doesn't work I really didnt get it(Start is its own class I don't think this one needs an invokeAndWait anyways becuse it is up first but just to try it out....
        try {
            javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
                 add (new Start());
        } catch (Exception e) {
            System.err.println("createGUI didn't successfully complete");
        }I think i may use an setLayeredPane or something to change the JPanels. To make it easier for everyone the other classes for the Jpanels are called game1, game2, and endGame. the panels will go something like this start then when the "go" button is clicked in start it will then goto either game1 or game2 depending one what one is selected(I found an fourm that may help me with returning values from Jframes so there will be different variables carried over to each panel) Then when the game is finished the endGame panel comes up displays some stats about the game and asks the user what type of game they want and either play the games or exit. Thanks

    I'm not 100% sure if this is what you need, but have you had a look at the CardLayout? It lets you swap JPanels as if they were in a deck of cards with one panel of your choosing always showing. I've used it several times, and it's not that hard to use. If this sounds close to what you need, check out the Sun tutorial on this:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html

  • JFrames / JPanels....Am I being stupid here?

    I am creating an application for an assignment. I want the button I click to display another screen in the center panel (displayPanel).
    But, I get nothing. Nothing displayed, no runtime error, nothing returned on the catch & even if I do a System.out.println() I get nothing in the command prompt.
    So, if I am not getting errors etc...where is my display? Any help?
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Toolkit.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Examiner extends JFrame implements ActionListener{
              Screen1 sc=new Screen1();
              StudentScreen ss=new StudentScreen();
              Container content;
              Icon stu_icon=new ImageIcon("../hat.jpeg");
              Icon staff_icon=new ImageIcon("../prof.jpeg");
              Icon course_icon=new ImageIcon("../course.jpeg");
              Icon units_icon=new ImageIcon("../units.jpeg");
              JButton stu=new JButton(stu_icon);
              JButton staff=new JButton(staff_icon);
              JButton course=new JButton(course_icon);
              JButton units=new JButton(units_icon);
              JPanel buttonPanel=new JPanel();
              JPanel menuPanel=new JPanel();
              JPanel displayPanel=new JPanel();
         public Examiner() {
              content=getContentPane();
              content.setLayout(new BorderLayout());
              buttonPanel.setLayout(new GridLayout(6,1));
              buttonPanel.add(stu);
              buttonPanel.add(staff);
              buttonPanel.add(course);
              buttonPanel.add(units);
              content.add("North",menuPanel);
              content.add("West",buttonPanel);
              content.add("Center",displayPanel);          
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        dispose();
                        System.exit(0);
         }// end examiner() constructor
              public void actionPerformed(ActionEvent clicked){
              if(clicked.getSource()==stu){
                   try{
                   test();
              catch(Exception e){e.printStackTrace();
              }// end if
         }//end actionperformed
              public void paint(Graphics g){
                   this.paintComponents(g);      
                   super.paint(g);
         }//end paint
         public void test(){
              displayPanel.add(units);
         public static void main(String args[]) {
              Examiner mainFrame = new Examiner();
              mainFrame.setSize(mainFrame.getToolkit().getScreenSize());
              mainFrame.setTitle("Examiner");
              mainFrame.setVisible(true);
         }// end main
    }//end Examiner classI have tried to get this to work by calling it from another class (StudentScreen) and also as shown above by simply trying to get it to display one of the icons again. Could use some pointers here
    Thanks

    <<<< falls over>>>>
    Now I am really embarrassed. I should have seen that a long time ago. Guess I need to take a break lol
    thanks very much for the help.

  • JFrame Design Question

    Folks,
    I'm creating a Java App using swing and had a quick question. Does it make more sense when creating a frame to extend the JFrame class or to create a new JFrame object in the constructor of the class that will provide the gui? I don't need to extend any other classed by this gui class so I'm not worried about that but rather what makes sense from a strictly OOP design viewpoint? By extending the JFrame class I should be creating a more specific JFrame class. However, I'm not really adding any functionality (technically), I'm just painting some objects. Thanks for your input.
    Andreas

    I can think of a couple options:
    1) Let IconFrame's constructor accept a Test parameter, instead of creating an interface.
    2) Make IconFrame into a modal dialog & have it store the user's selection in a variable. Then when you show the dialog, your action listener will block until the user selects an icon. Then you can call "getSelectedIcon()" to retrieve his/her selection. This would be much like the JOptionPane.showXXX() methods, and probably the cleaner solution.

  • GUI, JFrame, JPanel, ActionListener, simple multi-class applications

    My assignment calls for:
    "Create a Frame class"
    "Create a Panel class which implements ActionListener. Add JLabels, JTextFields, JButtons to the panel"
    most of this is pretty straight forward right out of GUI examples from my textbook
    but I don't have much experience with running multi-class programs, and this one is a bit more complicated b.c we have to use implement and possibly extend modifiers, which are new to me
    any thoughts?
    Edited by: infinitelyLooping on Sep 16, 2008 11:52 AM

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestX extends JFrame {
    MyPanel pnl;
    public TestX() {
    super();
    pnl = new MyPanel();
    getContentPane().add(pnl);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    pack();
    setVisible(true);
    class MyPanel extends JPanel implements ActionListener
    private JLabel lbl;
    private JTextField txt;
    private JButton btn;
    public MyPanel() {
    super();
    lbl = new JLabel();
    txt = new JTextField();
    btn = new JButton("btn");
    btn.addActionListener(this);
    add(lbl);
    add(txt);
    add(btn);
    public void actionPerformed(ActionEvent e) {
    txt.setText("Clicked");
                }

  • Scaling JFrames/JPanels/JInternalFrames

    Hey,
    After having a lot of trouble trying to scale the contents of JFrames/JInternalFrames using mouse events, I decided that I should try using a popup menu to allow me to specify a certain content ratio to scale the container's contents.
    A little history: I wanted to be able to scale JInternalFrames so that the contents (images) maintain their aspect ratio. I modified my code via some suggestions, but the results were not as good as I wanted them to be. If you have any ideas on mouse scaling, I'd really appreciate them. Here's a link to an old forum thread: http://forum.java.sun.com/thread.jsp?forum=57&thread=149864
    Back to the present: Now the problem I'm having using the popup is that, if I scale to a size greater than 100%, the parent window will scale, but the child components will not scale. I've included a copy of the code below. Your suggestions will be greatly appreciated.
    TJDeep.
    Code:
    //ImagePanel.java
    /* This class defines a generic image panel that allows for:
    * - image resizing
    * - image containment
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class ImagePanel extends JPanel
        implements ComponentListener {
        //variables
        JFrame parent;
        ImagePanelPopupMenu popupMenu;
        JPopupMenuShower popupShower;
        Dimension originalDimension;
        boolean originalSet = false;
        public ImagePanel(JFrame parent) {
            this.parent = parent;
            init();
        private void init() {
            popupMenu = new ImagePanelPopupMenu(this);
            popupShower = new JPopupMenuShower(popupMenu);
            addMouseListener(popupShower);
            setLayout(new BorderLayout());
            addComponentListener(this);
        public void setOriginalDimension(Dimension dim) {
            originalDimension = new Dimension(dim);
        public Dimension getOriginalDimension() {
            return new Dimension(originalDimension);
        public void componentHidden(ComponentEvent ce) { }
        public void componentMoved(ComponentEvent ce) { }
        public void componentShown(ComponentEvent ce) { }
        public synchronized void componentResized(ComponentEvent ce) {
            Point parentOrigin = parent.getLocation();
            Dimension parentSize = parent.getSize();
            Dimension parentContentSize = parent.getContentPane().getSize();
            int deltaWidth = parentSize.width - parentContentSize.width;
            int deltaHeight = parentSize.height - parentContentSize.height;
            parent.getContentPane().setSize(getSize());
            parent.setBounds(parentOrigin.x, parentOrigin.y,
                           getSize().width + deltaWidth,
                           getSize().height + deltaHeight);
        public void paint(Graphics g) {
            g.dispose();
            g.setColor(Color.black);
            g.fillRect(0, 0, getSize().width, getSize().height);
            g.setColor(Color.white);
            g.drawRect(5, 5, getSize().width - 10, getSize().height - 10);
        public static void main(String[] args) {
            JFrame frame = new JFrame("Image Panel Test");
            Container contentPane = frame.getContentPane();
            frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent we) {
                        System.exit(0);
            ImagePanel imagePanel = new ImagePanel(frame);
            Dimension dim = new Dimension(200, 200);
            imagePanel.setOriginalDimension(dim);
            Dimension dim2 = new Dimension(500, 500);
            //imagePanel.setMaximumSize(dim2);
            imagePanel.setPreferredSize(dim);
            //imagePanel.setSize(dim);
            contentPane.add(imagePanel, BorderLayout.CENTER);
            frame.pack();
            //frame.setResizable(false);
            frame.setVisible(true);
            contentPane.setSize(imagePanel.getSize());
    class ImagePanelPopupMenu extends JPopupMenu
        implements ActionListener {
        //identification
        ImagePanel parent;
        //Menu items
        JMenuItem z050;
        JMenuItem z075;
        JMenuItem z100;
        JMenuItem z150;
        JMenuItem z200;
        JMenuItem zCustom;
        //Miscellaneous configuration
        Font defaultFont = new Font("Helvetica", Font.PLAIN, 10);
        public ImagePanelPopupMenu(ImagePanel parent) {
            super("ZOOM");
            this.parent = parent;
            setFont(defaultFont);
            //configure the menu elements
            z050 = new JMenuItem("50 %");
            z050.setActionCommand("z050");
            z050.setFont(defaultFont);
            z050.addActionListener(this);
            add(z050);
            z075 = new JMenuItem("75 %");
            z075.setActionCommand("z075");
            z075.setFont(defaultFont);
            z075.addActionListener(this);
            add(z075);
            z100 = new JMenuItem("100 %");
            z100.setActionCommand("z100");
            z100.setFont(defaultFont);
            z100.addActionListener(this);
            add(z100);
            z150 = new JMenuItem("150 %");
            z150.setActionCommand("z150");
            z150.setFont(defaultFont);
            z150.addActionListener(this);
            add(z150);
            z200 = new JMenuItem("200 %");
            z200.setActionCommand("z200");
            z200.setFont(defaultFont);
            z200.addActionListener(this);
            add(z200);
            zCustom = new JMenuItem("Custom...");
            zCustom.setActionCommand("zCustom");
            zCustom.setFont(defaultFont);
            zCustom.addActionListener(this);
            addSeparator();
            add(zCustom);
            pack();
        public void actionPerformed(ActionEvent ae) {
            String item = ae.getActionCommand();
            Dimension dim = new Dimension(parent.getSize());
            if (item.equals("z050")) {
                dim = computeDimension(50);
            else if (item.equals("z075")) {
                dim = computeDimension(75);
            else if (item.equals("z100")) {
                dim = computeDimension(100);
            else if (item.equals("z150")) {
                dim = computeDimension(150);
            else if (item.equals("z200")) {
                dim = computeDimension(200);
            else if (item.equals("zCustom")) {
                String inputString =
                    JOptionPane.showInputDialog(this, "Please enter a view percentage:",
                                                "Custom Zoom", JOptionPane.OK_CANCEL_OPTION);
                if (inputString == null) return;
                try {
                    double inputNumber = Double.parseDouble(inputString);
                    dim = computeDimension(inputNumber);
                } catch (NumberFormatException nfe) { }
            parent.setSize(dim);
            //parent.setBounds(0, 0, dim.width, dim.height);
            //modify for use with custom, and captions.
        public Dimension computeDimension(double percent) {
            double factor = percent/100;
            Dimension dim = parent.getOriginalDimension();
            dim.height *= factor;
            dim.width *= factor;
            return dim;
    class JPopupMenuShower extends MouseAdapter {
        private JPopupMenu popup;
        public JPopupMenuShower(JPopupMenu popup) {
            this.popup = popup;
        private void showIfPopupTrigger(MouseEvent me) {
            if (popup.isPopupTrigger(me))
                popup.show(me.getComponent(), me.getX(), me.getY());
        public void mousePressed(MouseEvent me) {
            showIfPopupTrigger(me);
        public void mouseReleased(MouseEvent me) {
            showIfPopupTrigger(me);
    }

    Isn't there anyone out there who can help me with this problem...
    TJDeep

  • Multiple Components in a JFrame (simple question)

    Hello everyone, I need to put two components in my JFrame, and I have been expieriencing some odd problems. I use this to add my components...
    MyComponent mc=new MyComponent();
    MyOtherComponent me = new MyOtherComponent();
    When I try to access methods they work fine. I can use repaint() in a method and it works. BUT when I try to draw on the component using anything besides paintComponent() It gives me a java.lang.NullPointerException
    here is what I tried.....
    me.draw(getGraphics());
    //later on in the component def..
    draw(Graphics g) {
    } // I get a java.lang.NullPointerException in main
    whenever i use getGraphics() it does'nt work what am I doing wrong?

    Yup I did that and repaint does jack all. When I run the code all I see the contents of the first component. I know that the methods of the second component are being executed, but the paintComponent method is simply not running. I put a System.out.println("hi"); in and it never showed in the console..
    Anyone who can help me gets a duke, here's my second component code..
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    class MyOtherComponent extends JComponent {
    public void paintComponent(Graphics gg) {
    System.out.println("paintComponent executed!!!");
    Graphics2D g2D = (Graphics2D)gg;
    ImageIcon icon = null;
    try {icon = new ImageIcon(new URL("http://images.neopets.com/m.gif")); }
    catch(MalformedURLException e) {
    System.out.println("no"); return;
    resize(icon.getIconWidth(),icon.getIconHeight());
    Image mark = icon.getImage();
    g2D.drawImage(mark,0,0,this);
    g2D.drawString("hello folk",40,40);
    drawe(g2D);
    public void drawe(Graphics2D g2D) {
    g2D.drawLine(50,50,500,500);
    g2D.fillRect(20,20,20,20);
    repaint();
    public void line() {
    System.out.println("Hello, from MyOtherComponent");
    public void re() {
    repaint();
    System.out.println("re");     
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Maybe you are looking for

  • Error message when downloading video from itunes

    It keeps saying that my disk cannot be read or written to. I've already purchased the video (episode of the Office). Does anyone know what I can do to solve this? Thanks.

  • F-03 and fbra

    hi, what is f-03 clear gl account? what is the purpose of this tcode? what is fbra reset clearing? what is the purpose of this tcode? thanks rgds

  • How to view streamed files behind Firewalls through RTSP tunneling?

    Hi: According to the document of Quick Time Streaming Server Modules, there are two methods for server to send data to clients behind firewall. One is the RTSP/RTP over HTTP, and the other is RTP over RTSP. From the QuickTime player, I can issue the

  • Crash when watching movies

    Every time I watched a movie with Vlc, my computer crash. So I deleded Vlc, and use Quick time player instead, thinking the fault came for the application. But, it happens the same problem with QTP. What to do?

  • Kernel26tp_plus on X61- madwifi problems

    I had been running the stock kernel with no real problems, wireless or otherwise, on a new lenovo thinkpad x61.  Then, recently tried kernel26tp_plus package from the AUR to try to get suspend to work.  Everything seems to work except that I've now l