Repost:  JPanel or JFrame Problem?

Hello Everyone,
I am working on a solitaire program. I am able to run and compile the program. Every time I resize the frame, I get small gray squares to the right of my buttons. Also, my cards get changed every time I resize the frame. Any suggestions are appreciated.
Thanks,
E
//SolitaireProject.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SolitaireProject extends JApplet
public SolitaireProject()
this.setContentPane(new SolitaireProjectPanel());
public static void main(String[] args)
JFrame window = new JFrame();
window.setTitle("Solitaire by E");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setContentPane(new SolitaireProjectPanel());
window.pack();
window.show();
//SolitaireProjectPanel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.applet.*;
public class SolitaireProjectPanel extends JPanel
private static final int CARD_WIDTH = 77;
private static final int CARD_HEIGHT = 110;
private final int ACES_DISTANCE_BETWEEN_CARDS = 97;
private final int ACES_DISTANCE_FROM_LEFT = 425;
private final int ACES_DISTANCE_FROM_TOP = 50;
private final int ACES_MAXIMUM = 793;
private final int PLAYCARDS_DISTANCE_FROM_LEFT = 300;
private final int PLAYCARDS_DISTANCE_FROM_TOP = 200;
private final int PLAYCARDS_DISTANCE_BETWEEN_COLUMNS = 87;
private final int PLAYCARDS_DISTANCE_BETWEEN_ROWS_FACEDOWN = 5;
private final int PLAYCARDS_DISTANCE_BETWEEN_ROWS_FACEUP = 30;
private final int PLAYCARDS_MAXIMUM = 899;
private final int PILE_DISTANCE_FROM_LEFT = 75;
private final int PILE_DISTANCE_FROM_TOP = 50;
private final int SHOWCARD_DISTANCE_FROM_LEFT = 75;
private final int SHOWCARD_DISTANCE_FROM_TOP = 200;
private int _initX = 0; // x coord - set from drag
private int _initY = 0; // y coord - set from drag
private Card[] _cardFronts = new Card[52]; //Creates an array of cards
private Card _currentCard = null; //Current draggable card
private Card[] _cardBacks = new Card[52];
public SolitaireProjectPanel()
String suits = "CDHS";
String faces = "A23456789TJQK";
int cardPosition = 0;
int crdBackPosition = 0;
for(int suit = 0; suit < suits.length(); suit++)
for(int face = 0; face<faces.length(); face++)
ImageIcon img = new ImageIcon("card " + faces.charAt(face) + suits.charAt(suit) + ".jpg");
Image image = img.getImage();
Image scaledImage = image.getScaledInstance(77, 110, Image.SCALE_FAST);
img.setImage(scaledImage);
_cardFronts[cardPosition ++] = new Card (img, _initX++, _initY++);
for(int crdBack = 0; crdBack < 52; crdBack++)
ImageIcon img2 = new ImageIcon("cardBack.jpg");
Image image = img2.getImage();
Image scaledImage = image.getScaledInstance(CARD_WIDTH, CARD_HEIGHT, Image.SCALE_FAST);
img2.setImage(scaledImage);
_cardBacks[crdBackPosition ++] = new Card (img2, _initX++, _initY++);
//shuffle();
JPanel setUpPanel = new JPanel();
setPreferredSize(new Dimension(1000, 700));
setBackground(Color.white);
JButton newGameButton = new JButton("New Game");
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(new ExitAction());
newGameButton.addActionListener(new NewGameAction());
this.add(newGameButton);
this.add(exitButton);
class ExitAction implements ActionListener
public void actionPerformed(ActionEvent e)
System.exit(0);
class NewGameAction implements ActionListener
public void actionPerformed(ActionEvent e)
shuffle();
repaint();
public void paintComponent(Graphics g)
shuffle();
JPanel drawAndDealPanel = new JPanel();
super.paintComponent(g);
setBackground(Color.white);
g.drawRect(PILE_DISTANCE_FROM_LEFT, PILE_DISTANCE_FROM_TOP, CARD_WIDTH, CARD_HEIGHT);
g.drawRect(SHOWCARD_DISTANCE_FROM_LEFT, SHOWCARD_DISTANCE_FROM_TOP, CARD_WIDTH, CARD_HEIGHT);
for(int position1 = ACES_DISTANCE_FROM_LEFT; position1 <= ACES_MAXIMUM; position1 += ACES_DISTANCE_BETWEEN_CARDS)
g.drawRect(position1, ACES_DISTANCE_FROM_TOP, CARD_WIDTH, CARD_HEIGHT);
for(int position2 = PLAYCARDS_DISTANCE_FROM_LEFT; position2 <= PLAYCARDS_MAXIMUM; position2 += PLAYCARDS_DISTANCE_BETWEEN_COLUMNS)
g.drawRect(position2, PLAYCARDS_DISTANCE_FROM_TOP, CARD_WIDTH, CARD_HEIGHT);
int crd1 = 1;
int column1 = 300;
int fromTop1 = PLAYCARDS_DISTANCE_FROM_TOP;
Card cf = _cardFronts[crd1];
cf.image.paintIcon(this, g, column1, fromTop1);
crd1 = 2;
column1 = 300 + PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
for(int count = 0; count < 6; count ++)
Card cb = _cardBacks[crd1];
cb.image.paintIcon(this, g, column1, fromTop1);
crd1 ++;
column1 += PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
int crd2 = 8;
int column2 = 387;
int fromTop2 = fromTop1 + PLAYCARDS_DISTANCE_BETWEEN_ROWS_FACEDOWN;
cf = _cardFronts[crd2];
cf.image.paintIcon(this, g, column2, fromTop2);
crd2 = 9;
column2 = 387 + PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
for(int count = 0; count < 5; count ++)
Card cb = _cardBacks[crd2];
cb.image.paintIcon(this, g, column2, fromTop2);
crd2 ++;
column2 += PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
int crd3 = 14;
int column3 = 474;
int fromTop3 = fromTop2 + PLAYCARDS_DISTANCE_BETWEEN_ROWS_FACEDOWN;
cf = _cardFronts[crd3];
cf.image.paintIcon(this, g, column3, fromTop3);
crd3 = 15;
column3 = 474 + PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
for(int count = 0; count < 4; count ++)
Card cb = _cardBacks[crd3];
cb.image.paintIcon(this, g, column3, fromTop3);
crd3 ++;
column3 += PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
int crd4 = 19;
int column4 = 561;
int fromTop4 = fromTop3 + PLAYCARDS_DISTANCE_BETWEEN_ROWS_FACEDOWN;
cf = _cardFronts[crd4];
cf.image.paintIcon(this, g, column4, fromTop4);
crd4 = 20;
column4 = 561 + PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
for(int count = 0; count < 3; count ++)
Card cb = _cardBacks[crd4];
cb.image.paintIcon(this, g, column4, fromTop4);
crd4 ++;
column4 += PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
int crd5 = 23;
int column5 = 648;
int fromTop5 = fromTop4 + PLAYCARDS_DISTANCE_BETWEEN_ROWS_FACEDOWN;
cf = _cardFronts[crd5];
cf.image.paintIcon(this, g, column5, fromTop5);
crd5 = 24;
column5 = 648 + PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
for(int count = 0; count < 2; count ++)
Card cb = _cardBacks[crd5];
cb.image.paintIcon(this, g, column5, fromTop5);
crd5 ++;
column5 += PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
int crd6 = 26;
int column6 = 735;
int fromTop6 = fromTop5 + PLAYCARDS_DISTANCE_BETWEEN_ROWS_FACEDOWN;
cf = _cardFronts[crd6];
cf.image.paintIcon(this, g, column6, fromTop6);
crd6 = 27;
column6 = 735 + PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
for(int count = 0; count < 1; count ++)
Card cb = _cardBacks[crd6];
cb.image.paintIcon(this, g, column6, fromTop6);
crd6 ++;
column6 += PLAYCARDS_DISTANCE_BETWEEN_COLUMNS;
int crd7 = 28;
int column7 = 822;
int fromTop7 = fromTop6 + PLAYCARDS_DISTANCE_BETWEEN_ROWS_FACEDOWN;
cf = _cardFronts[crd7];
cf.image.paintIcon(this, g, column7, fromTop7);
for(int playCard = 29; playCard < 52; playCard ++)
Card cb = _cardBacks[playCard];
cb.image.paintIcon(this, g, PILE_DISTANCE_FROM_LEFT, PILE_DISTANCE_FROM_TOP);
this.add(drawAndDealPanel);
//shuffle
public void shuffle()
Random rgen = new Random();
for (int i=0; i<52; i++)
int randomPosition = rgen.nextInt(52);
Card temp = _cardFronts;
_cardFronts = _cardFronts[randomPosition];
_cardFronts[randomPosition] = temp;
class Card
ImageIcon image;
int x;
int y;
public Card(ImageIcon image, int x, int y)
this.image = image;
this.x = x;
this.y = y;
}

Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.
P.S. Repost your CODE, not a new thread....
&#167;

Similar Messages

  • Problem with JPanel in JFrame

    hai ashrivastava..
    thank u for sending this one..now i got some more problems with that screen .. actually i am added one JPanel to JFrame with BorderLayout at south..the problem is when i am drawing diagram..the part of diagram bellow JPanel is now not visible...and one more problem is ,after adding 6 ro 7 buttons remaing buttons are not vissible..how to increase the size of that JPanel...to add that JPanel i used bellow code
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    f.getContentPane().add(BorderLayout.SOUTH, panel);

    Hi
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    // Add this line to ur code with ur requiredWidth and requiredHeight
    panel.setPreferredSize(new Dimension(requiredWidth,requiredHeight));
    f.getContentPane().add(BorderLayout.SOUTH, panel);
    This should solve ur problem
    Ashish

  • Passing parameter between jpanel and jframe

    Hi guys,
    First time posting, so please be nice! :p
    Basically, the problem i'm having:
    I have created a JFrame class, which adds some JPanels to itself to start with (basic layout stuff).
    This JFrame is created and instantiated in main.java, and just displays the basic stuff that i've added.
    On the JFrame are a number of JButtons, and when you click on the JButton each JButton it adds a custom JPanel to the main JFrame. Basically, it provides an easy way to produce a kind of menu system using the JPanels.
    The problem i have, is that each time a textbox is clicked inside one of the custom JPanels, i want it to pass the name of the textbox and jpanel back to a method setLastTextBox() in the JFrame class.
    I tried:
    private void jTextPane1FocusGained(java.awt.event.FocusEvent evt) {
        super.setLastTextBox()
    }But super. is not the correct call. I'm sure its something pretty simple but i can't think what it is, and i tried googling it to no avail.
    I would be extremely greatful if someone could put me back on the right path!
    Thanks,
    --Mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi, Mark
    I hope I understood you rihgt.
    I think that you should add Focus Listeners to the text boxes, rather than panels and create a method setLastTextBox(String panelName, String textBoxName)
    and just write something like that
    textField1.addFocusListener(new FocusAdapter(){
                public void focusGained(FocusEvent e) {
                    String textFieldName = ((JTextField)e.getSource()).getName();
                    String panelName = ((JTextField)e.getSource()).getParent().getName();
                     setLastTextBox(textFieldName, panelName);
            });    that is if you write this code inside your frame class
    otherwise you can get to your frame, by calling the method getParent() and checking its class until its not YourFrameClass (or JFrame) and then just cast it and call the method.
    I hope I was clear
    Ksenia

  • Embedding PDF File into JPanel or JFrame

    Does anyone know how to embedd a PDF file or document into a JPanel or JFrame.

    I can suggest you ways
    1)pdf to Image
    2)pdf to html
    http://www.verypdf.com/pdf2htm/
    Free online service
    http://www.gohtm.com/

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

  • How can i transform MFC HWND into jpanel or jframe instance

    Hi!
    I want to open a MFC window, then with the HWND , i want to open java subwindow created inside the MFC window with the HWND, i wonder if there is a way. how can i transform the HWND into jpanel or jframe instance.

    Look at the article in CodeProject and read the example in it. The other questions you can send to my email because I cannot give you concrete response in this forum.

  • Embeding PDF file into JPanel or JFrame

    Do any one have an idea on how to embed a PDF file into JPanel or JFrame?

    I can suggest you ways
    1)pdf to Image
    2)pdf to html
    http://www.verypdf.com/pdf2htm/
    Free online service
    http://www.gohtm.com/

  • Help! Read raw Image data from a file and display on the JPanel or JFrame.

    PLEASE HELP, I want to Read Binary(Raw Image)data (16 bit integer) from a file and display on the JPanel or JFrame.

    Hey,
    I need to do the same thing. Did you find a way to do that?
    Could you sent me the code?
    It's urgent, please.
    My e-mail is [email protected]

  • How do you set an image into the background of a JPanel or JFrame?

    How do you set an image into the background of a JPanel or JFrame?

    Something like this, Ive thrown in an ImageIcon on a
    button too for good measure.
    import java.awt.*;
    import javax.swing.*;
    public class JFrameImage extends JFrame {
    public JFrameImage() {
    Container c    = getContentPane();
    JPanel panel = new JPanel(){
                 public void paintComponent(Graphics g)     {
    ImageIcon img = new
    = new ImageIcon("background.jpg");
                      g.drawImage(img.getImage(), 0, 0, null);
                      super.paintComponent(g);
            panel.setOpaque(false);
    ImageIcon icon = new ImageIcon("onButton.jpg");
    JButton button = new JButton(icon);
    panel.add(button);
    c.add(panel);
    public static void main(String[] args) {
    JFrameImage frame = new JFrameImage();
    frame.setSize(200,200);
    frame.setVisible(true);
    Going totally fancy pants
    ImageIcon bigImage = new ImageIcon(bgImage.getImage().getScaledInstance(getWidth(), getHeight(),Image.SCALE_REPLICATE));
    g.drawImage(bigImage.getImage(), 0, 0, this); Will scale the image to the size of the panel
    whereas
    for (int y = 0; y  < getHeight(); y = y + image.getHeight(null))
    for (int x = 0; x< getWidth(); x = x + image.getWidth(null))
    g.drawImage(image, x, y, this); Will give a tiled effect
    Try tiling with an animated gif and bring your processor to a standstill.

  • Weird problem with jpanel vs jframe

    I'm using jmathplot.jar from JMathTools which lets me do 3d plotting. I used a JFrame to get some code to work and it worked fine. Here's the code that worked for a JFrame:
    public class View extends JFrame
        private Model myModel;
        private Plot3DPanel myPanel;
        // ... Components
        public View(Model m)
            myModel = m; 
            // ... Initialize components
            myPanel = new Plot3DPanel("SOUTH");
            myPanel.addGridPlot("Test",myModel.getXRange(),myModel.getYRange(),myModel.getZValues());
            setSize(600, 600);
            setContentPane(myPanel);
            setVisible(true);
    }Here's the class that starts everything:
    public class TestApplet extends JApplet
        public void init()
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        createGUI();
            catch (Exception e)
                e.printStackTrace();
        private void createGUI()
            System.out.println("Creating GUI");
            Model model = new Model();
            View view = new View(model);
    }And here's the Model:
    public class Model
        private double[] myXRange,myYRange;
        private double[][] myZValues;
        public Model()
            createDataSet();
        public double[] getXRange()
            return myXRange;
        public double[] getYRange()
            return myYRange;
        public double[][] getZValues()
            return myZValues;
        private void createDataSet()
            myXRange = new double[10];
            myYRange = new double[10];
            myZValues = new double[10][10];
            for(double i=0;i<10;i++)
                for(double j=0;j<10;j++)
                    double x = i/10;
                    double y = j/10;
                    myXRange[(int) i] = x;
                    myYRange[(int) j] = y;
                    myZValues[(int) i][(int) j]= Math.cos(x*Math.PI)*Math.sin(y*Math.PI);
    }However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and changed:
    setSize(600, 600);
    setContentPane(myPanel);
    setVisible(true);to
    this.add(myPanel);and added these two lines to createGUI():
            view.setOpaque(true);
            setContentPane(view);When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet. I don't know if it's a problem with the library or if I'm doing something wrong in my applet.

    However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and (...)What do you mean? View extends JApplet? I thought View was meant to extend JPanel in the end...
    When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet.Or, the panel has its preferred size, and this latter is too small. Actually the panel has the size its container's layout manager awards it (taking or not the panel's preferred, minimum, and maximum sizes into account). See the tutorial on [layout managers|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html] .
    In particular, this line adds the myPanel to a parent panel (presumably, it is in class View which extends JPanel, whose default layout is FlowLayout):
    this.add(myPanel);
    I don't know if it's a problem with the library or if I'm doing something wrong in my applet.Likely not (presumably the library interfers only in how it computes the Plot3DPanel's preferred size). There's an easy way to tell: try to layout correctly a custom JPanel of yours, containing only e.g. a button with an icon. Once you understand the basics of layout management, revisit the example using ther 3rd-party library.
    N.B.: there are a lot of "likely" and "presumably" in my reply: in order to avoid hardly-educated guesses especially on what is or isn't in your actual code, you'd better provide an SSCCE , which means reproducing the problem without the 3rd party library.

  • JFrame Problem!!! pls help

    Hi everyone,
    I'm using JFrame in my GUI desing and I try to insert JTable in it with using JPanel. Here is the code for the problem portion:
                    k = new JTable( );
                    gbcPanel0.gridx = 3;
                    gbcPanel0.gridy = GridBagConstraints.RELATIVE;
                    gbcPanel0.gridwidth = 100;
                    gbcPanel0.gridheight = 100;
                    gbcPanel0.fill = GridBagConstraints.BOTH;
                    //gbcPanel0.weightx = 1;
                    gbcPanel0.weighty = 5;
                    gbcPanel0.anchor = GridBagConstraints.NORTH;
                    gbPanel0.setConstraints( k, gbcPanel0 );When this section appears on the screen with my actionlistener button, it always appear at the right most part of the screen. But I would like to see it at the bottom of screen as a new paragraph (sorry for simile). I have read somewhere; in JFrame addings will be appear at the right most default.
    I would be glad if you help me to change this

              getContentPane().setLayout(new GridBagLayout());
              JPanel firstParagraph = new JPanel();
              JTable secondParagraph = createTable();
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.gridx = 0;
              gbc.gridy = 0;
              gbc.fill = GridBagConstraints.BOTH;
              gbc.weightx = 1;
              gbc.weighty = 1;
              gbc.anchor = GridBagConstraints.NORTH;
              getContentPane().add(firstParagraph, gbc);
              gbc.gridy++;
              getContentPane().add(new JScrollPane(secondParagraph), gbc);

  • Using JPanel with JFrame

    I am using a JFrame to encapsulate my program. I want to have a JPanel inside my JFrame to handle all of my 2d displaying (like fillRect() etc...). I used forte to set this up but I am having problems dispaying on the JPanel. Here is my code:
    here is how I call the function from the main .java file
    I dubuged this and know it works (proof will come later)
    private void Start_ButtonActionPerformed(java.awt.event.ActionEvent evt)
    myDisplay.draw();
    here is my entire JPanel class
    import java.awt.*;
    import javax.swing.*;
    public class Display extends javax.swing.JPanel
    public Display() {
    initComponents();
    public void paintComponent(Graphics g )
    System.out.println("1");
    super.paintComponent(g);
    g.setColor(Color.black);
    g.fillOval(50,10,60,60);
    public void draw()
    System.out.println("1");
    this.repaint(); //i also tried repaint() but it didn't work either
    System.out.println("2");
    private void initComponents()
    setLayout(new java.awt.BorderLayout());
    when I press the start button, 1 and 2 are displayed but 3 isn't. For some reason the repaint() function is not telling the paintComponent function to work. Any help is appreciated.
    Thanks,
    Every_man

    Every_man,
    After doing the super.paintComponent(g); you must use Graphics2D. So you next line should cast your graphics object to a graphics 2D object, like this. Graphics2D g2 = (Graphics2D)g;

  • Trying to wait for a button press on a seperate JFrame- problems.

    Hi,
    I've been getting aquainted with Java recently. I'd like to think I was reasonable now at creating console based applications but I'm having a lot of trouble getting used to the swing API. I'm making a little game type thing at the moment and part of it involves displaying a problem to the user in a seperate JFrame and returning which option they picked. If I was doing this in a console based App I'd probably do something along the lines of:
         while (UserInput == null) { //while they haven't entered anything continue to loop.
              UserInput = InputScanner.next(); //get the user's input
         }I thought I'd do something similar for my JFrame based app but haven't been able to do it. I essentially would like the code to not execute past a certain point until one of the options on the JFrame has been picked. Here's the code for the JFrame showing the dilemma to the user:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * This is the window displayed to a user with dilemma details
    public class DilemmaWindow extends JFrame implements ActionListener {
        int OptionPicked = 0; //the option the user picks
        JLabel DescriptionLabel;
        JButton Button1;
        JButton Button2;
        public DilemmaWindow(String WindowTitle, String LabelText, String Button1Text, String Button2Text) {
            //construct the JFrame with the relevant parameters
            setTitle(WindowTitle);
            setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            setLayout(new FlowLayout(FlowLayout.CENTER));
            Button1 = new JButton(Button1Text);
            Button2 = new JButton(Button2Text);
            Button1.addActionListener(this);
            Button2.addActionListener(this);
            DescriptionLabel = new JLabel();
            DescriptionLabel.setText(LabelText);
            add(DescriptionLabel);
            add(Button1);
            add(Button2);
            pack();
            setVisible(true);
        public void actionPerformed(ActionEvent evt) {
            //determine which button was clicked and set OptionPicked accordingly
            if(evt.getSource() == Button1) {
                OptionPicked = 1;
            } else {
                OptionPicked = 2;
        public int GetDilemmaChoice() {
            if (OptionPicked > 0) { //if an option was picked
            this.dispose(); //clean up the window
            return OptionPicked; //return which option was picked
    }The idea of this being that it constructs a window and when the GetDilemmaChoice() function is called it'll return which button has been clicked.
    I do, as I said, want to wait until one of the buttons has been clicked before continuing with the execution of the code in the class that constructs the JFrame, so I made the following function:
    public int GetDilemmaChoice() {
            int Choice = 0;
            DilemmaWindow MyDilemmaWindow = new DilemmaWindow(CaperDilemma.GetDilemmaName(),CaperDilemma.GetDilemmaDescription(),CaperDilemma.GetOption1Text(),CaperDilemma.GetOption2Text());
            while (Choice == 0) {
                Choice = MyDilemmaWindow.GetDilemmaChoice();      
            return Choice;
        }The idea being that while the window returns that no buttons have been clicked the function loops round. The problem I'm having is that the while loop continually looping seems to hog all the CPU time or something, as the dilemma JFrame doesn't display properly (I get a blank window, with none of the buttons) and so I can't click any of the options. I've been banging my head against a brick wall all day trying to get round this and am wondering if I should put the looping in a seperate thread or something. Sadly, though, I don't know anything about threads so wouldn't know where to start.
    If anyone has any idea of how to solve this problem I'd be very grateful! I hope I've managed to explain it well enough.

    Why not use a modal JDialog here and not a JFrame. You probably shouldn't be coding directly to a JFrame (or JDialog) anyway but to a JPanel that can be placed on the proper root container of choice (which again here is a JDialog). You can make your JPanel as complex as desired, then place it in the JDialog, make that dialog application modal, and when you show it via setVisible(true), the application will halt at that point until the dialog has been dealt with.

  • How to embed a Jpanel in JFrame

    I have made two JPanel classes
    JPanelclass1
    JPanelclass2
    and a JFrame class
    JFrameclass1
    in netbean 5.5.1
    I want to embed that JPanel in the JFrame and when a button is clicked the ist JPanel dissaper and the second JPanel appears on the same JFrame..... i have tried to declare an object of that JPanel class in the JFrame
    Please Help

    One word: CardLayout

  • JPanel in jFrame

    Hello
    I have a class pannel1.java which is basicly a jpannel
    public class pannel1 extends javax.swing.JPanel {
    public pannel1() {
    initComponents();
    Now i have a different class which is basicly a jframe
    How can i display the jpannel class into the jframe class ?

    Read through the tutorials as recommended. However, in answer to your question, something like this.
    public class Class1 extends JPanel {
      //all your methods and jpanel sizes ommitted
    public class Main {
      public static void main(String[] args) {
         JFrame f = new JFrame();
        Class1 cl = new Class1();
         f.add(cl);
         f.setVisible(true);
    }Hope that helps.
    You can do others such as getContentPane().setContentPane(cl).
    This is just to get you started. All thread safety features have been ommited. Read about Swing thread safety after you get some understanding of Java Swing.

Maybe you are looking for