The Cosmetics of a JPanel

Hey guys,
I have a quiz program that consists of a text area to show prompts, two text fields for input, a submit button, as well as a reset button. The problem is I have no idea how to set their locations. They have a standard location I can control with the order of implementation, but I would like to have more control on exactly where the components are and I would also like to anchor them (which I do not foresee being as difficult as the coordinates). I want to do this because the window happens to be re-sized, all the components are moving and I don't want that. Any help on achieving such a feet would be greatly appreciated. I'll attach my code. Thanks in advance.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
public class SonnetTest {
    public static void main(String[] args) {
         JFrame frame = new JFrame();
         //Creates a new PoemGenerator object
         final PoemGenerator vanorden = new PoemGenerator();
         //Sets the standard width of the fields
         final int FIELD_WIDTH = 20;
         //Initializes the input fields for author and title
         final JTextField authorField = new JTextField(FIELD_WIDTH);
         final JTextField titleField = new JTextField(FIELD_WIDTH);
         //Labels the input fields
         final JLabel titleLabel = new JLabel("Title");
         final JLabel authorLabel = new JLabel("Author");
         //Initializes the display area
         final JTextArea display = new JTextArea();
         display.setText(vanorden.verse);
         display.setEditable (false);
          //Initializes the submit and new poem buttons
         JButton submitButton = new JButton("Submit");
         JButton newPoemButton = new JButton("New Poem");
         //Constructs the panel      
         JPanel panel = new JPanel();
         panel.add(display);
         panel.add(authorLabel);
         panel.add(authorField);
         panel.add(titleLabel);
         panel.add(titleField);
         panel.add(submitButton);
         panel.add(newPoemButton);
         frame.add(panel);
         //Creates a listener to be used when the submit button is pressed
         class CheckAnswerListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   String authorGuess = authorField.getText();
                   //Compares the input with the correct (ignoring case)
                   if(authorGuess.compareToIgnoreCase(vanorden.Poet) == 0){
                        display.setText("Correct!");
                   else{
                        display.setText("Incorrect, the poet's name is " + vanorden.Poet + ".");
         ActionListener listener = new CheckAnswerListener();
         submitButton.addActionListener(listener);
         //Creates a listener to be used when the new poem button is pressed
         class NewPoemListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   PoemGenerator vanorden = new PoemGenerator();
                   display.setText(vanorden.verse);     
         ActionListener listener2 = new NewPoemListener();
         newPoemButton.addActionListener(listener2);
         //Sets the panel's size
         frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
    //Sets the variables to be used as dimensions for the window
    private static final int FRAME_WIDTH = 250;  //Good width for input fields
    private static final int FRAME_HEIGHT = 200;
}

Learn about LayoutManagers: [http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]
If you don't want a frame to be resizable:
frame.setResizable(false);ps: in future, post Swing questions to the [Swing forum|http://forums.sun.com/forum.jspa?forumID=57] .

Similar Messages

  • Displaying the content of one JPanel in an other as a scaled image

    Hi,
    I'd like to display the content of one JPanel scaled in a second JPanel.
    The first JPanel holds a graph that could be edited in this JPanel. But unfortunately the graph is usually to big to have a full overview over the whole graph and is embeded in a JScrollPanel. So the second JPanel should be some kind of an overview window that shows the whole graph scaled to fit to this window and some kind of outline around the current section displayed by the JScrollPanel. How could I do this?
    Many thanks in advance.
    Best,
    Marc.

    Hi,
    I'd like to display the content of one JPanel scaled
    in a second JPanel.
    The first JPanel holds a graph that could be edited
    in this JPanel. But unfortunately the graph is
    usually to big to have a full overview over the whole
    graph and is embeded in a JScrollPanel. So the second
    JPanel should be some kind of an overview window that
    shows the whole graph scaled to fit to this window
    and some kind of outline around the current section
    displayed by the JScrollPanel. How could I do this?
    Many thanks in advance.
    Best,
    Marc.if panel1 is the graph and panel2 is the overview, override the paintComponent method in panel2 with this
    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.scale(...,...);
    panel1.paint(g2);
    }

  • How can i save the data in a jpanel form to a .txt document

    how can i save the data in a jpanel form to a text file using parse function,this should happen when i click a save button .
    please help me..

    each time when i fill the form and click save button ,all the data in the form should be written to a text file and each time when i repeat it should append to the old data in the text file.the elements in the form should be seperated by pipe delimeter.
    thanks for your patience..

  • How to place a JPanel at the center of another JPanel?

    Can anyone tell me how to place a JPanel inside another JPanel? The first JPanel consists of three JPanels each consisting of a label&textfield and are placed using BoxLayout. The second JPanel is a big blank screen. So, i would like to put the first JPanel at the center of second JPanel(horizontally & vertically). The problem is that i don't have any other component. So,if i try to use FlowLayout, i am able to put it at the center(horizontally, not vertically) only on the top edge. I tried to use BoxLayout. But, i couldn't(as i don't have any other elements). I tried to create some blank elements. But, they are messing up the elements of my JPanel. Any cluesssssssss??????????

    import java.awt.*;
    import javax.swing.*;
    public class CenteredLayout
        private JPanel getPanel()
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            JPanel p = new JPanel(gridbag);
            addComponents(new JLabel("label 1"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 2"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 3"), new JTextField(8), p, gbc);
            JPanel panel = new JPanel(gridbag);
            panel.setBackground(Color.pink);
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.insets = new Insets(0,0,0,0);
            panel.add(p, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            c.add(c2, gbc);
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new CenteredLayout().getPanel());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Refreshing the jtree in a jpanel

    hi,
    i created a jtree of files in a certain folder... if some files changed in my folder, how can i refresh the jtree in my jpanel...
    thanks!!!

    Hi,
    look here:
    http://forum.java.sun.com/thread.jspa?threadID=478780&messageID=2226565
    L.P.

  • How do you define the width of a JPanel?

    How do you define the width of a JPanel?

    it may not be perfect but this is what i have tried:
    import javax.swing.*;
    import java.awt.event.*;
    public class myPane extends JFrame {
         public myPane() {
              super("myPane");
              setDefaultCloseOperation.(JFrame.EXIT_ON_CLOSE);
              JButton myButt = new JButton("press");
              JPanel pane = new JPanel();
              pane.add(myButt);
              setContentPane(pane);
         public static void main(String args[]) {
              myPane p1 = new myPane();
              p1.setBounds(20, 20, 600, 400);
              p1.setVisible(true);
    }

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

  • How do i get the width of a JPanel

    Hey
    Im trying to get the width of my JPanel with this code, but it just prints 0, what am i doing wrong?
    public class GamePanel extends JPanel implements Runnable {
         private static final int PWIDTH = 500;   // size of panel
         private static final int PHEIGHT = 400;
         private static final int NO_DELAYS_PER_YIELD = 16;     
         private static int MAX_FRAME_SKIPS = 5;
         private MovingGame frame;
         private Thread animator;
         private volatile boolean running = false;   // used to stop the animation thread
         private long gameStartTime;   // when the game started
         private BallSprite ball;
         //      off-screen rendering
         private Graphics dbg;
         private Image dbImage = null;
         //      holds the background image
         private BufferedImage bgImage = null;
         public GamePanel(MovingGame frame){     
              this.frame = frame;
              setDoubleBuffered(true);
              setBackground(Color.blue);
              setPreferredSize( new Dimension(PWIDTH, PHEIGHT));
              setFocusable(true);
              requestFocus();
              addKeyListener( new KeyAdapter() {
                   public void keyPressed(KeyEvent e)
                       { processKey(e);  }
              ball = new BallSprite(40, 40, this);
              System.out.println("Width: " + getWidth());    <------- this prints 0
         }

    veldhanas wrote:
    Hi,
    Use
    setSize(PWIDTH, PHEIGHT); instead of
    setPreferredSize( new Dimension(PWIDTH, PHEIGHT));ThanksWrong Wrong Wrong Wrong
    .setSize() sets the size of the component at that instant in time and has no effect on anything the layout managers do with the component. .setPreferredSize() sets the size the layout manager will look at (assuming it cares about what size you want the component at).

  • Dynamically changing the size of a JPanel

    Hi All,
    I am loading multiple images in a JPanel. I want the size of the JPanel to increase dynamically as and when the images are loaded. I have also added a JScrollPane and added the JPanel to this JScrollPane.
    However, the images are cut as soon as it crosses 800 pixels (which is the preferred size of the JScrollPane and it starts to give me NullPointerExceptions where I try to access the image height and width. Here is the code that gives me the problem. The files are opened using the filechooser and put into a Vector, which is then retrieved in the paint() method and rendered to the panel.
    CurrentScreenSize is a Dimension that stores the value of the current screent size that the image pane should have.
    imagePane is the JPanel that contains all the images.
    //File | Open action performed
    void jMenuFileOpen_actionPerformed(ActionEvent e) {
    //Handle open action.
    if (e.getSource() == jMenuFileOpen) {
    fc = new JFileChooser();
    //Filter out only image files (uses Utils.java and ImageFilter.java)
    fc.addChoosableFileFilter(new ImageFilter());
    fc.setAcceptAllFileFilterUsed(false);
    fc.setMultiSelectionEnabled(true);
    int returnVal = fc.showOpenDialog(MainFrame.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File[] files = fc.getSelectedFiles();
    //This is where a real application would open the file.
    int x=10, y=50;
    for(int i=0;i<files.length;i++)
    try {
    Image tempImage = ImageIO.read(files);
    image.add(tempImage);
    if(tempImage.getHeight(this) > currentScreenSize.getHeight())
    currentScreenSize.setSize(currentScreenSize.getWidth()
    + tempImage.getWidth(this),
    tempImage.getHeight(this));
    else
    currentScreenSize.setSize(currentScreenSize.getWidth()
    + tempImage.getWidth(this),
    currentScreenSize.getHeight());
    if (imagePane.getSize().getWidth() <
    currentScreenSize.getSize().getWidth() ||
    imagePane.getSize().getHeight() <
    currentScreenSize.getSize().getHeight())
    imagePane.setSize(currentScreenSize);
    this.pack();
    //repaint();
    catch (IOException ex) {
    ex.printStackTrace();
    //When all images are loaded then paint it / display it
    repaint();
    public void paint(Graphics g){
    int x=10, y=50;
    super.paint(g);
    g = imagePane.getGraphics();
    for (int j=0; j<image.size() ; j++)
    Image img = (Image)image.elementAt(j);
    int imageWidth = img.getWidth(this);
    int imageHeight = img.getHeight(this);
    g.drawImage(img, x, y, imageWidth, imageHeight, this);
    x = x+imageWidth;

    got the Solution, using validate() method does the work under the hood.

  • How can I disable all the components in a JPanel?

    I want to disable all the components( button, text field ) in a JPanel. I know I can search the panel and disable each of its children component recursively. Is there a better way to do this?

    I want to disable all the components( button, text field ) in a JPanel.You haven't defined what you mean by "disable".
    If you mean you want the component to be repainted in its disabled state, then you would need to set the property of each individual component to disable, which would imply some kind of recursion.
    If you just want to prevent components from receiving key events and mouse events, then you can use a glass pane or maybe a panel with an overlay layout that contains a non-opaque panel that intercepts all events.

  • Can We show the ppt slides in jpanel or other componant ?

    Hello sir,
    There is a problem with me, I want to display ppt slides into jpanel .Is it possible ? if it is possible than please give me ideas and send codes .

    the cheapest way i can think of rite now is to convert the ppt to image and then display it .... use the buttons to get to the new ppt the same way.
    if you really want to automate the process try reading this ...
    http://www.oooforum.org/forum/viewtopic.phtml?t=8715&highlight=java+converting+ppt+image
    it tells you the procedure to convert a ppt to jpeg ... if have a jpeg you can then display it as an image on JPanel.

  • How to change the background of a JPanel when printing?

    I have a JPanel that has a background color of gray when displayed on the screen. I would like to change the background to white when printing but leave it gray on the screen. I am calling setBackground(), clearRect() and fillRect() but it still prints out with the gray background. Any thoughts on what method I could call to change this?
    public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
    if (pageIndex >= 1) {
    return Printable.NO_SUCH_PAGE;
    double pageHeight = pf.getImageableHeight();
    double pageWidth = pf.getImageableWidth();          
    Graphics2D g2 = (Graphics2D) g;
    g2.setBackground(Color.white);
    g2.clearRect((int)pageWidth/2, (int)pageHeight/2, (int)pageWidth, (int)pageHeight);
    g2.fillRect((int)pageWidth/2, (int)pageHeight/2, (int)pageWidth, (int)pageHeight);
    paint(g2);

    From reading the doc, it appears that you have to change the background color of the Component:
    setBackground
    public abstract void setBackground(Color color)
    Sets the background color for the Graphics2D context. The background color is used for clearing a region. When a Graphics2D is constructed for a Component, the background color is inherited from the Component. Setting the background color in the Graphics2D context only affects the subsequent clearRect calls and not the background color of the Component. To change the background of the Component, use appropriate methods of the Component.
    Parameters:
    color - the background color that isused in subsequent calls to clearRect
    See Also:
    getBackground(), Graphics.clearRect(int, int, int, int)
    V.V.

  • How to change the background of a Jpanel

    All I want to do is change the background color of my JPanel. I have looked at some of the java tutorials, and I am still having a really hard time figuring it out. Is there a simple way to just change the background color, without messing with overriding the paintComponent() method?

    All I want to do is change the background color of my
    JPanel. I have looked at some of the java tutorials,
    and I am still having a really hard time figuring it
    out. Is there a simple way to just change the
    background color, without messing with overriding the
    paintComponent() method?Simple enough?
    myPanel.setBackground(Color.BLUE);Edit: You'd better learn how to use and search through the API:
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JPanel.html
    null

  • How to define the position of a JPanel in a JScrollPane?

    I have put a panel into scrollpane. The panel is used to draw some graphs, if the panel enlarge the scrollbar will dispaly. it works well. I use jScrollPane.getViewport().add(jPanelDraw, null) to add panel into the scrollpane. I found the panel is always in the top left coner of the scrollpane, how could i do if i want put the panel in the center of the scrollpane?

    Try something like this:
    BorderLayout bl = new BorderLayout();
    JPanel parent = new JPanel();
    JScrollPane scrollPane = new JScrollPane();
    Then set the layout:
    scrollPane.setLayout(bl); // Our BorderLayout
    To add a component in the center:
    scrollPane.getViewport().add(myJComponent, BorderLayout.Center);
    Then add the scoller to the parent
    parent.add(scrollPane);
    Of course you should also specify a layout for the parent, too...

  • By clicking the JButton getting another JPanel in place of before JPanel in

    my program having two JButtons ,Two JPanels,one JFrame.when i click on JButton1 ,JPanel1 with some content will be opened in the JFrame.After clicking on JButton2 ,JPanel2 with some cotent will be opened on the same JFrame at the same place before where the JPanel1 will be displayed.
    JButtons will be at the top.Below that in the same JFrame JPanels will be displayed
    plz help me..................

    plz help ..how to see the code that you sent

Maybe you are looking for