Hw to split the jpanel to 3 jpanels

Hello frnds,
In the below mentioned code I need to split the teller panel to three teller can you give any suggestions.
thank you
suraw
package guis.views;
import guis.controllers.GeneralController;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.util.LinkedList;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
* This is a custom view panel that displays a "document" consisting of a single
* text element. Both the document and the text element respond to changes in
* the model state.
* @author Robert Eckstein
public class TellerPanelView extends View
     private JPanel tellerPanel,tellerSubPanel;
     private JList teller;
     private JLabel tellerInfo;
     private JSplitPane SplitPane;
     private LinkedList<String> customerAtTeller;
     private JScrollPane listScroller;
     private DefaultListModel tellerlist;
     // The controller used by this view
     private GeneralController controller;
     * Creates new form TextElementDisplayPanel
     * @param controller An object implenting the controller interface that
     * this view can use to process GUI actions
     public TellerPanelView(GeneralController controller) {
          this.controller = controller;
          initComponents();
          localInitialization();
     * Initialization method called from the constructor
     public void localInitialization() {
     /** This method is called from within the constructor to
     * initialize the form.
     private void initComponents() {
          tellerPanel = new JPanel(new GridLayout(2,1));          
     tellerInfo = new JLabel("Teller1: Teller2: Teller3:");
          teller = new JList();
          tellerlist = new DefaultListModel();
          teller.setModel(tellerlist);
          SplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);          
          for (int a = 0; a <= 2; a++)
          listScroller = new JScrollPane(teller,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
          customerAtTeller = new LinkedList<String>();
          tellerPanel.add(tellerInfo);
          tellerPanel.add(listScroller);
     public JPanel getTellerPanel() {
          return tellerPanel;
     * Called by the controller when it needs to pass along a property change
     * from a model.
     * @param evt The property change event
     public void modelPropertyChange(PropertyChangeEvent evt) {
          if (evt.getPropertyName().equals(GeneralController.ADD_TRANSACTION)) {
               String cust = (String) evt.getNewValue();
               customerAtTeller.addLast(cust);
               tellerlist.addElement(cust);
          revalidate();
          repaint();
}

While it looks like you've split a panel, you really haven't. You've added spcific components to a JPanel that make it look like it's split.
Ingredients needed: a total of 4 JPanels, and 2 JSplitPanes
Step 1: Create 2 new JPanels, and then Create a JSplitPane that houses these two JPanels
JSplitPane jsp1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jPanel2, jPanel3);
Step 2: Create a 3rd JPanel, and then Create a second JSplit Pane that holds the 3rd JPanel, the JSplitPane created in step 1
JSplitPane jsp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jPanel1, jsp1);
Step 3: Now, add the JSplitPane created in step 2 to your original JPanel
jsp0.add(jsp2); // modify the add according to the screen manager you're using
You'll want to set properties on EACH of the JSplitPanes:
((JSplitPane) jsp1).setDividerSize(6);
((JSplitPane) jsp1).setContinuousLayout(true);
((JSplitPane) jsp1).setResizeWeight( (iSliderPos * 0.01) ); // VERY IMPORTANT!!!
((JSplitPane) jsp1).setDividerLocation( (iSliderPos * 0.01) );
where int iSliderPos is 0 - 100
Gotchas: I may look like there is nothing there (empty screen) because there are no components in jsp1, jsp2, and jsp3.
You'll either need to put components on these JPanels, or force the JPanels to have some size by setting:
jpanel1.setMinimumSize(new Dimension(80, 60));
jpanel1.setPreferredSize(new Dimension(800, 600));
jpanel1.setMaximumSize(new Dimension(1600, 1200));
jpanel1.setBounds(0,0,800,600);
jpanel1.setBorder(blackLineBorder);
(repeat for jpanel2 and jpanel3)
and the split panes:
jsp1.setMinimumSize(new Dimension(80, 60));
jsp1.setPreferredSize(new Dimension(800, 600));
jsp1.setMaximumSize(new Dimension(1600, 1200));
jsp1.setBounds(0, 0, 800, 600);
(repeat for jsp2)
This was pretty frustrating for me the first couple (of hundred) times. Maybe try to get it working as 2 panels with one split first.
bcf

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

  • Put an 'X' in the corner of a JPanel, what's the trick?

    I've seen applications (I assume written in java) where there is an 'X' to dispose() of a panel or toolbar.
    Here I've done a quick and dirty mock up of my application. If someone could oblige with a line or 2 showing how to do this, or even a link to the API /forum thread (that I've already searched) - much will be appreciated. Also please bear in mind that I need to keep clear of the 1.4 API 'cos of backward compatability issues, taa.import java.awt.*;
    import javax.swing.*;
    public class justjunk{
       public static void main(String []args){
          new justjunk();
       justjunk(){
          JFrame frame = new JFrame("demo only");
          JPanel north = new JPanel();
          north.add(new JLabel("some text label"));
          north.add(new JButton("A button"));
          north.add(new JButton("nuther button"));
          *    I want to set an 'X' at the top right hand corner of JPanel
          *    west, so that it can be closed at the discretion of the user,
          JPanel west = new JPanel();
          west.setPreferredSize( new Dimension( 100, (frame.getHeight()-north.getHeight()) ) );
          west.setLayout(new FlowLayout(FlowLayout.CENTER));
          west.setBorder(BorderFactory.createTitledBorder(" My Toolset : "));
          JButton []button = new JButton[8];
             for(int i=0; i<button.length; i++){
                button[i] = new JButton("button "+(i+1));
                west.add(button);
    frame.getContentPane().add(north, BorderLayout.NORTH);
    frame.getContentPane().add(west, BorderLayout.WEST);
    frame.getContentPane().add(new JTextArea(), BorderLayout.CENTER);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.setVisible(true);

    Here's a suggestion
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class XMarksTheSpot {
        public static void main(String []args){
            new XMarksTheSpot();
        XMarksTheSpot() {
            final JFrame frame = new JFrame("demo only");
            frame.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            final JPanel north = new JPanel();
            north.add(new JLabel("some text label"));
            north.add(new JButton("A button"));
            north.add(new JButton("nuther button"));
            JLabel x = getXLabel();
            x.addMouseListener(new MouseAdapter()
                public void mousePressed(MouseEvent e)
                    north.setVisible(false);
            north.add(x);
             * I want to set an 'X' at the top right hand corner of JPanel
             * west, so that it can be closed at the discretion of the user,
            final JPanel west = new JPanel();
            west.setPreferredSize( new Dimension( 100, (frame.getHeight() -
                                                        north.getHeight()) ) );
            west.setLayout(new FlowLayout(FlowLayout.CENTER));
            west.setBorder(BorderFactory.createTitledBorder(" My Toolset : "));
            x = getXLabel();
            x.addMouseListener(new MouseAdapter()
                public void mousePressed(MouseEvent e)
                    frame.remove(west);
                    frame.validate();
                    frame.repaint();
            west.add(x);
            JButton []button = new JButton[8];
            for(int i=0; i<button.length; i++) {
                button[i] = new JButton("button "+(i+1));
                west.add(button);
    frame.getContentPane().add(north, BorderLayout.NORTH);
    frame.getContentPane().add(west, BorderLayout.WEST);
    frame.getContentPane().add(new JTextArea(), BorderLayout.CENTER);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.setVisible(true);
    private JLabel getXLabel()
    JLabel label = new JLabel("X", JLabel.RIGHT);
    label.setPreferredSize(new Dimension(45, 25));
    //label.setBorder(BorderFactory.createEtchedBorder());
    label.setFont(new Font("ludida bright demibold", Font.PLAIN, 24));
    label.setForeground(Color.red);
    return label;

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

  • Drawing 2D Graphics in the center of a JPanel

    Hi,
    Below is my GUI. The basic idea is, I want this to create a neat UI on any machine with any monitor resolution settings. Because I dont really know what will be the resolution of the target machine, I do not perform a setPreferred size on any component. I have several problems here.
    1. My DiagramPanel.paintComponent method relies on the Panel's preferred size to draw a rectangle in the center of the panel. When a panel is layed out using BorderLayout, it expands it to fit the space. So is there some method I can use to know, what space the component panel is occupying (its dimension) ?
    2. Also, when the frame is maximized or resized, the DiagramPanel's dimension changes. So I want to be able to redraw the diagram in the new center position. How can I do this ?
    4. I am using the Frame size to be the screen dimension and set it to be maximized. So when I try to restore the window, it takes up the whole screen even the space including the windows taskbar. Is there someway to get the screen dimension leaving out the space for the taskbar ?
    3. I dont set the DividerLocation of the contentPane because, I want it to be set automatically based on the contents of the leftPanel. But when i print out the dividerLocation after creating the UI, it prints -1. How can I get the current divider location then ?
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.LayoutManager;
    import java.awt.Toolkit;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextArea;
    @SuppressWarnings("serial")
    public class MainFrame extends JFrame {
    public MainFrame() {
    createAndShowGUI();
    private void createAndShowGUI() {
    initMainFrame();
    initMenus();
    initPanels();
    initContentPane();
    setVisible(true);
    System.out.println("Divider location "+ contentPane.getDividerLocation());
    private void initMainFrame() {
    setTitle("Main Frame");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setState(JFrame.NORMAL);
    //GETS SCREEN SIZE
    Dimension screen_Dimension = Toolkit.getDefaultToolkit().getScreenSize();
    setSize(screen_Dimension.width, screen_Dimension.height);
    setExtendedState(MAXIMIZED_BOTH);
    private void initContentPane() {
    getContentPane().add(contentPane);
    contentPane.setEnabled(false); / *prevent the divider location from being moved* /
    contentPane.setLeftComponent(leftpanel);
    contentPane.setRightComponent(rightpanel);
    contentPane.setOpaque(true);
    private void initMenus() {
    exitMenu.setActionCommand(EXIT_COMMAND);
    file.add(exitMenu);
    menub.add(file);
    setJMenuBar(menub);
    private void initPanels() {
    initLeftPanel();
    initRightPanel();
    private void initLeftPanel() {
    leftpanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    leftpanel.add(new Button("Click"));
    private void initRightPanel() {
    LayoutManager border = new BorderLayout();
    rightTab.setLayout(border);
    scrollingDiagram = new JScrollPane(diagramPanel);
    diagramDescriptionPanel.setLayout(new BorderLayout());
    diagramDescriptionPanel.add(diagDescTextArea, BorderLayout.CENTER);
    rightTab.add(scrollingDiagram, BorderLayout.CENTER);
    rightTab.add(diagramDescriptionPanel, BorderLayout.SOUTH);
    rightpanel.addTab("Right Tab", rightTab);
    public static void main(String args[]) {
    try {
    new MainFrame();
    } catch (Exception e) {
    e.printStackTrace();
    System.exit(0);
    private JSplitPane contentPane = new JSplitPane();
    private JMenuBar menub = new JMenuBar();
    private JMenu file = new JMenu("File");
    private JMenuItem exitMenu = new JMenuItem("Exit");
    private JPanel leftpanel = new JPanel();
    private JTabbedPane rightpanel = new JTabbedPane();
    private JPanel rightTab = new JPanel();
    private JScrollPane scrollingDiagram;
    private DiagramPanel diagramPanel = new DiagramPanel();
    private JPanel diagramDescriptionPanel = new JPanel();
    private JTextArea diagDescTextArea = new JTextArea(18, 45);
    public static final String EXIT_COMMAND = "Exit";
    @SuppressWarnings("serial")
    class DiagramPanel extends JPanel{
    public static int RECT_WIDTH = 100;
    public static int RECT_HEIGHT = 75;
    public void paintComponent(Graphics g) {
    super.paintComponents(g);
    Coordinates centerOfPanel = getCenterCoordinates();
    g.drawRoundRect(centerOfPanel.x, centerOfPanel.y, RECT_WIDTH, RECT_HEIGHT, 10, 10);
    public Coordinates getCenterCoordinates() {
    Dimension panelDimension = getPreferredSize();
    int x = (panelDimension.width - RECT_WIDTH) / 2;
    int y = (panelDimension.width - RECT_HEIGHT) / 2;
    return new Coordinates(x,y);
    class Coordinates {
    int x;
    int y;
    Coordinates(int x, int y) {
    this.x = x;
    this.y = y;

    Hi,
    The getSize worked perfectly for me. But what I tried doing now is that, instead of just the simple centering of the rectangle, i did this
    1. When the dimension of the rectangle is smaller than the Panel.getSize(), do centering as usual
    2. else when the rectangle is bigger, say because its width was longer than Panel.getSize().getWidth(), I center the rectangle only on its Height, and set the preferred size of the Panel to (rectangle.getWidth(), panel.getSize().getHeight()). And I call revalidate, so that the scrollbars appear.
    Problem im running into now is that, once I do a setPreferredSize, everytime I use a getSize later on, i always get the same size. But what I want to see is that, when the rectangle can fit in the panel, i want it centered without any scrollbars, but when it cannot fit on the width, i want it to appear centered on height, but have a horizontal scroll bar.
    I'd be really grateful, if you could help me with this.
    Here is the code
    public void paintComponent(Graphics g) {
              super.paintComponents(g);
              Coordinates centerOfPanel = getCenterCoordinates();
              g.drawRoundRect(centerOfPanel.x, centerOfPanel.y, RECT_WIDTH, RECT_HEIGHT, 10, 10);
              //preferredSize might have changed, call revalidate
              revalidate();
    public static final int PANEL_MARGIN = 50;
    public Coordinates getCenterCoordinates() {
              setPreferredSize(null);
              Dimension panelDimension = getSize();
              Dimension myPreferredSize = new Dimension();
              if (panelDimension.width > RECT_WIDTH)
                   myPreferredSize.width = panelDimension.width;
              else
                   myPreferredSize.width = RECT_WIDTH + 2 * PANEL_MARGIN; // MARGIN on left end and right end
              if (panelDimension.height > RECT_HEIGHT)
                   myPreferredSize.height = panelDimension.height;
              else
                   myPreferredSize.height = RECT_HEIGHT + 2 * PANEL_MARGIN; // MARGIN on top and bottom
              System.out.println("Panel size is " + getSize());
              setPreferredSize(myPreferredSize);
              System.out.println("Preferred size is " + myPreferredSize);
              //center of the panel.
              int x = (myPreferredSize.width - RECT_WIDTH) / 2;
              int y = (myPreferredSize.height - RECT_HEIGHT) / 2;
              return new Coordinates(x,y);
         }

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

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

  • What's difference between JPanel.remove(); and JPanel = null

    nice day,
    how can remove JPanel (including its JComponents), safe way, can you explain the difference between JPanel.remove () and JPanel = null,
    1/ because if JPanel does not contain any static JComponents
    2/ or any reference to static objects,
    then works as well as JPanel.remove or JPanel = null,
    or what and why preferred to avoid some action (to avoid to remove or to avoid to null)

    mKorbel wrote:
    nice day,
    how can remove JPanel (including its JComponents), safe way, can you explain the difference between JPanel.remove () and JPanel = null, Remove the JPanel from the container it was part of and make sure you do not keep any references to it from your own classes. Don't make it any more difficult than it has to be.

  • How locate a JPanel in a JPanel (SOS !!!)

    I add the class affectation (see below) in a JPanel but I can't succeed in locating it in this JPanel..
    I have tried to use setLayout(null) and to use setLocate and setBounds but it doesn't work..
    Thanks
    public class Affectation extends JPanel{
    public Affectation(int deb, int fin,Color couleur){
    this.setBackground(couleur);
    this.setBorder(BorderFactory.createLineBorder(Color.black));
    //this.setBounds(new Rectangle(deb,10,fin-deb,20));
    this.setLocation(deb, 7);
    this.setPreferredSize (new Dimension(fin-deb,20));
    this.setMinimumSize (new Dimension(fin-deb,20));
    this.setMaximumSize (new Dimension(fin-deb,20));
    }

    You have to locate Affectation in the container you add it to.
    JPanel otherPanel = new JPanel(new NullLayout());
    Affectation myAffectation = new Affection( deb, fin, coleur);
    otherPanel.add(myAffectation);
    myAffectation.setLocation(deb, 7);
    other something like that.
    Cheers
    DB

  • How can i use an inner Jpanel in another JPanel

    Hi, i need to put an inner panel in a container panel.I have been trying for hours but I couldn't make it work. Please waiting for help...
    public class Gui extends JFrame{
         public Gui() {
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setEnabled(true);
              setSize(500, 500);
              JPanel mainPanel=new JPanel();
              int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
              JScrollPane jsp=new JScrollPane(mainPanel,v,h);
              this.add(mainPanel);
              setContentPane(jsp);
                    //this part doesn't works
              JPanel innerPanel=new JPanel();
              innerPanel.setSize(50, 50);
              innerPanel.setLocation(100, 100);
              innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
              innerPanel.setBackground(Color.red);
                   //this part doesn't works
         public static void main(String[] args) {
              Gui gui= new Gui();
              gui.setVisible(true);
    }

    I'm sorry it's my bad that i have forgotten to add the innerPanel to mainPannel (But of course i tried it in the original code :) ). Now i made the changes you suggested but there are still problems.
    I can see the innerPanel now, but the size and the position of the innerPanel doesn't works.
    public Gui() {
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setEnabled(true);
              setSize(500, 500);
              JPanel mainPanel=new JPanel();
              int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
              JScrollPane jsp=new JScrollPane(mainPanel,v,h);
              getContentPane().add(jsp);
              JPanel innerPanel=new JPanel();
              innerPanel.setSize(500, 500);
              innerPanel.setLocation(400, 400);
              innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
              innerPanel.setBackground(Color.red);
                    mainPanel.add(innerPanel);
                    //also i tried
                    //getContentPane().add(innerPanel);
                    //or
                    //jsp.add(innerPanel);        
    ...

Maybe you are looking for

  • Ok making progress on the image sequence importing but...

    I have successfully imported images into Fireworks and then exported them for use in Edge using John Dunning's Edge Animate Extension. When I import them into Edge the only way to get them in is to import them as a symbol. Is there any other way or c

  • Issues with my iPhone 6 after update ios 8.0.2

    LIst of issues after uodate 1-Email comes back after I deleted them. 2-Apps crash or do not respond 3-Screen rotation not working properly 4-Battery drain quick 5- Using iphone get frozen 6-wifi drop connection and bluetooth 7- also gps for years sin

  • PO Waiting for Approval

    Hello SRM Gurus, I am working on a Standalone, I have created a SC and a PO for the same using Sourcing. Few Questions 1.Can i create a PO from SC without using the Sourcing Application? I have Maintained the Vendor and Price in Product Master(commpr

  • Reader X - Holds closed files if appear in splash screen

    Issue: Slightly complex issue - sorry 1. reader is open 2. files have been opened and closed 3. no files are now open in reader but original instance is stll running 4. new splash screen shows a list of files that can be opened (shortcuts ?) 5. using

  • Newbie Request for Assistance

    Hey All, Forgive my ignorance here, I am not that well versed in networking. I have some things in place that I’ve had running (and well) for the better part of two years. I recently acquired an ASA 5505, and have been trying to get it setup. My exis