JFrame And jTables

Hi
I can connect a database to a table in a normal class just fine. But doing it in jFrame is mind boggling. I have put a jPanel on the frame. I have put my table in a scrollpanel. But i have no idea how to connect it to the database. Appreciate your help with this coz ive been trying to figure out for the better part of the last 3 weeks.

But i have no idea how to connect it to the databaseThere is no way to connect a JTable directly to a database.
I can connect a database to a table in a normal class just fineEvery class is a "normal" class. So just do exactly as you have been doing. The only difference is that instead of doing a System.out.println(...) to display the results of the database query you need to built a DefaultTableModel which you then add the to the JTable.
Swing related questions should be posted in the Swing forum. If you search the Swing forum you will find my "tablefromdatabase" example.

Similar Messages

  • Print option:-  to print the entire JFrame and its components

    I have created a screen using JFrame.
    The screen contains components such as a graph, combobox, tabbedpane and JTable.
    Now we have given 2 options to the end user, either to print the entire screen(JFrame) or
    the contents available in the table.
    My query is , how can i print the entire screen(all the components must be printed),
    is there any api available for this purpose.
    If possible provide me some sample codes.

    <h3>{color:#ff0000}Cross posted{color}</h3>
    [http://forum.java.sun.com/thread.jspa?threadID=5286030]
    Cross posting is rude.
    db

  • PLS help with stupid JPanel and JTable :-(

    Hi all im crying now :-(
    Ive just recreated a panel for use with SWING. Now I want the table to be displayed but it just is not there.
    Nothing i seem to do makes it appear and im really confused????? Just add this to a simple JFrame and you will see what I mean
    it should look like this
    TITLE
    lbl1 txt1 lbl2 txt2
    lbl3 txt3 lbl4 txt 4
    button
    Table
    however the table is not there :-(
    Author: Justin Thomas
    Date  : 14 Jan 2002
    Notes : A simple login display
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Options extends JPanel implements ActionListener
        private IDNTester parent;
        private TextArea Results = new TextArea(18,80);
        private JButton Start = new JButton("Start Test");
        private JLabel error = new JLabel ("");
        private JTextField txtConns = new JTextField("1",4);
        private JTextField txtClients = new JTextField("10",4);
        private JTextField txtServer = new JTextField("Nutcracker",10);
        private JTextField txtPort = new JTextField("8101",5);
        public String Server;
        public int Port;
        public int Connections;
        public int Clients;
        private String newline;
        public Options(IDNTester ref)
            parent = ref;
            newline = System.getProperty("line.separator");
            JLabel lblMain = new JLabel ("WebIDN Performance Tester");
            JLabel  lblServer = new JLabel ("Server:");
            JLabel  lblPort = new JLabel ("Port:");
            JLabel  lblConns = new JLabel ("Connections:");
            JLabel  lblClients = new JLabel ("Clients:");
            GridBagLayout gridBag = new GridBagLayout();
            GridBagConstraints constraints = new GridBagConstraints();
            setLayout(gridBag);
            constraints.anchor = GridBagConstraints.CENTER;
            constraints.gridwidth = 4;
            constraints.gridx = 0;
            gridBag.setConstraints(lblMain, constraints);
            add(lblMain);
            constraints.insets = new Insets(10,0,0,0);  //top padding
            constraints.gridy = 1;
            gridBag.setConstraints(error, constraints);
            error.setForeground(Color.red);
            add(error);
            constraints.anchor = GridBagConstraints.WEST;
            constraints.gridwidth = 1;
            constraints.gridx = 0;
            //********************************Server and COnnections***************
            constraints.fill = GridBagConstraints.BOTH;
            constraints.gridy = 2;
            gridBag.setConstraints(lblServer, constraints);
            add(lblServer);
            constraints.gridx = 1;
            gridBag.setConstraints(txtServer, constraints);
            add(txtServer);
            // Add some space between fields
            constraints.gridx = 2;
            gridBag.setConstraints(lblConns, constraints);
            add(lblConns);
            constraints.gridx = 3;
            gridBag.setConstraints(txtConns, constraints);
            add(txtConns);
            //********************************** Port and clients******************
            constraints.gridy = 3;
            constraints.insets = new Insets(5,0,0,0);
            constraints.gridx = 0;
            gridBag.setConstraints(lblPort, constraints);
            add(lblPort);
            constraints.gridx = 1;
            gridBag.setConstraints(txtPort, constraints);
            add(txtPort);
            constraints.gridx = 2;
            gridBag.setConstraints(lblClients, constraints);
            add(lblClients);
            constraints.gridx = 3;
            gridBag.setConstraints(txtClients, constraints);
            add(txtClients);
            //********************************** Buttons***************************
            constraints.anchor = GridBagConstraints.CENTER;
            constraints.gridy = 4;
            constraints.insets = new Insets(10,0,0,0);  //top padding
            constraints.gridwidth = 4;   //4 columns wide
            constraints.gridx = 0;
            gridBag.setConstraints(Start, constraints);
            add(Start);
            // Results area
            constraints.gridx = 0;
            constraints.gridy = 5;
            constraints.gridwidth = 5;   //Colum width
            //gridBag.setConstraints(Results, constraints);
            //add(Results);
            // JTable
            DefaultTableModel defaultTab = new DefaultTableModel();
            JTable jtable = new JTable(defaultTab);
            defaultTab.addColumn("ThreadID");
            defaultTab.addColumn("ClientID");
            defaultTab.addColumn("RIC");
            defaultTab.addColumn("TimeTaken");
            defaultTab.addColumn("RCount");
            defaultTab.addColumn("Bytes");
            //add scrollpane to our table
            gridBag.setConstraints(jtable, constraints);
            add(new JScrollPane(jtable));
            // Add listeners
            txtConns.addActionListener(this);
            txtClients.addActionListener(this);
            txtServer.addActionListener(this);
            txtPort.addActionListener(this);
            Start.addActionListener(this);
        public void actionPerformed(ActionEvent event)
            // Validate fields and if correct then start
            boolean valid = true;
            Server = txtServer.getText();
            try {
                Port= Integer.parseInt(txtPort.getText());
                Connections = Integer.parseInt(txtConns.getText());
                Clients = Integer.parseInt(txtClients.getText());
            catch(NumberFormatException nfe) {
                valid = false;
            if (valid && Server.length() > 0)
                error.setText("");
                parent.connect();
            else
                error.setText("Port/Client/Connections must be numerical");
                validate();
        // Add a new line to the test
        public void addLine(String text)
            Results.append(text + newline);
    }

    Hi,
    It looks like you haven't closed the comments. Is anything added after error.
    Anyway try setting the fill constrains on your table to BOTH. The table you have created in empty so it may have trouble determining it's size.
    regards,
    Terry

  • How to ZOOM the JFrame and its components ?

    Hi
    I could not find any solution/suggestions for this, so I am asking help.
    I am adding multiple components (JLables, JtextFields and a JTable) in to Jpanel(s) and to a JFrame window and I want to add Zoom (+ or - ) functions.
    I don't want to take each and every component from JFrame/ JPanel(s) and resize or repaint.
    Is there any way, that you can increase and decrease the whole JFrame and JPanel's view so that the components, which are been added to them, look like their sizes are also increased / decreased?
    Any suggestions or help would be appreciated.
    Thanks.
    Regards,
    Vally.

    ok...
    god bless the "GlassPane"
    you can take a snapShot of your frame...
    draw it on your glassPane..
    and just use your glassPane
    to paint the image with the requested size...
    in this approach you cant press a button and to things..
    shay

  • BufferedImage and JTable

    I am trying to create a BufferedImage from a JTable so that I can convert it into a JPEG file, however,
    I can't get seem to get the graphics into the BufferedImage unless I first put the table into a JFrame and set
    it visible. Basically what I am doing is:
    JTable table = new JTable("with simple parameters");
    BufferedImage buf = new BufferedImage(table.getPrefferedSize.width,table.getPrefferedSize().height,TYPE_INT_RGB);
    Graphics g = buf.getGraphics();
    table.paint(g);
    I have tried paint, paintAll, createGraphics and many more - none of them have worked unless I first put the table into a container and then set the container visible. I can get a label and button to print out this way without having to first set them visible, but I can't do it with a JTable. Does anybody know a way to fix this??
    -Thanks for your help.

    Here is an example that saves a JTable as a JPEG image:
    import java.awt.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.color.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import com.sun.image.codec.jpeg.*;
    public class SaveJTable {
        public static void saveComponentAsJPEG(Component cmp, Container cont, String jpegfile) {
           Rectangle d = cmp.getBounds();
           BufferedImage bi = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
           Graphics2D g2d = bi.createGraphics();
           SwingUtilities.paintComponent(g2d,cmp,cont, 0,0,d.width,d.height);
           saveImageAsJPEG(bi, jpegfile);
       public static void saveImageAsJPEG(BufferedImage bi, String filename) {
          try {
             ByteArrayOutputStream boutstream = new ByteArrayOutputStream();
             JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(boutstream);
             enc.encode(bi);
             FileOutputStream fimage = new FileOutputStream(new File(filename));
             boutstream.writeTo(fimage);
             fimage.close();
          } catch (Exception e) { System.out.println(e); }
       public static void  main(String[] args){
          SaveJTable comp = new SaveJTable();
          JButton jb = new JButton("my button");
          jb.setSize(100,50);
          JPanel jp = new JPanel();
          String data[][] = {{"a","b","c"},
                             {"e","f","g"},
                             {"h","i","j"},
                             {"k","l","m"}};
          String colnames[] = {"col1", "col2", "col3"};
          JTable jtb = new JTable(data, colnames);
          JFrame jf = new JFrame();
          JScrollPane jsp = new JScrollPane(jtb);
          jf.getContentPane().add(jsp);
          jf.pack();
          comp.saveComponentAsJPEG(jsp,jf.getContentPane(),"jtable.jpg");
          System.exit(0);
    }In the main() method, I created a sample JTable and put in in a JScrollPane. For some reason, the saved image doesn't show the column names if I don't put the JTable in a JScrollPane (no time to debug, sorry). So, I saved the JScrollPane instead of JTable.

  • How can i hide a JFrame and then Show it again in runtime

    How can i hide a JFrame and then Show it again in runtime??
    Please, please help me
    Its URGENT

    Here's even an example:
    import javax.swing.*;
    public class HideAndShow extends JFrame
         public HideAndShow()
              super("Hello");
              setSize(200, 200);
              setVisible(true);
              try
                   Thread.sleep(2000);
              } catch(InterruptedException e) {}
              setVisible(false);
              try
                   Thread.sleep(2000);
              } catch(InterruptedException e) {}
              setVisible(true);
         public static void main(String[] args)
              new HideAndShow();
    The JFrame will show, then hide, then show again. This is at runtime.

  • JFrame and Windows as a whole

    Hey peoples,
    Anyone know where I can get information in regards to building custom windows? For example, the default Java Window has the Java Icon on the top right of the window and has a particular color to it. I was interested on making a window with a different border, color, (Top label)...you know, just customize the appearance...any clues?
    Thanx,
    Shrubz

    I'm building a standard application. I know how to use JFrame and the whole nine yards; however, I was looking into customizing the actual Window which is created by Swing. Let us say that the TOP bar which every window has by default is displaying a stretched image rather than the light blue color is has by default...know what I mean?
    Thanx,
    Shrubz

  • Enlarge JFrame and its components properties  proportionally

    Hi,
    We have a simple JFrame � Container - uses Flow Layout and has got Buttons, Text Fields� All of them are using Java�s default fonts, sizes..�
    And we want to increase or enlarge all of the JFrame and its sub components properties proportionally (especially Font�.) like in for example MS-Word.
    In the Ms-Word, there is ZOOM option in the Standard tool bar menu. If you set zoom to 150%, the font is automatically increases. And if you set it to 100% the font sets back to normal. And if the window is not enough to fit, it adds the scroll bars.
    For example, if we increase the Labels Font, the height of that component also should increase proportionally. So the Frame also should increase.
    How could we achieve this sort of functionality ( i.e. Proportionally increasing the component�s properties ) in Swing?
    I believe it is hard to set/adjust the all of the Frame�s components properties (I.e. Height, Font�) proportionally by using the Component listeners.
    (Another example, you might have noticed that the Frame�s Font, hight,width �sizes are proportionally bigger in Systems screen�s 800 by 600 pixels mode compare with 1024 by 768 pixels mode. May be this is windows feature. But we are looking at achieving the same sort of feature)
    Any help or thoughts would be appreciated.
    Thanks in advance.
    Vally.

    Here is a working sample:
    package ui_graphics;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.LayoutManager;
    import java.util.Arrays;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    import javax.swing.SpinnerListModel;
    import javax.swing.SpinnerModel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class ZoomableFrameTest {
       private ZoomablePanel zoomPanel;
       private JLabel label;
       public ZoomableFrameTest() {
          label = new JLabel("Essai pour le zoom");
          label.setBounds(0,0,200,16);
          zoomPanel = new ZoomablePanel();
          zoomPanel.add(label);
          JFrame frame= new JFrame("Zoom test");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(getZoomSpinner(), BorderLayout.NORTH);
          frame.getContentPane().add(zoomPanel, BorderLayout.CENTER);
          frame.pack();
          frame.setVisible(true);
       public static void main(String[] args) {
          new ZoomableFrameTest();
       public JSpinner getZoomSpinner() {
          String[] zoomValues = { "50", "100", "150" };
          SpinnerModel model = new SpinnerListModel(Arrays.asList(zoomValues));
          final JSpinner spZoom = new JSpinner(model);
          Dimension dim = new Dimension(60, 22);
          spZoom.setMinimumSize(dim);
          spZoom.setPreferredSize(dim);
          spZoom.setMaximumSize(dim);
          spZoom.setFocusable(false);
          spZoom.addChangeListener(new ChangeListener() {
             public void stateChanged(ChangeEvent e) {
                // R�cup�re le facteur d'�chelle
                int factor = Integer.parseInt((String)spZoom.getValue());
                setScaleFactor(factor);
          spZoom.setValue("100");
          return spZoom;
       private void setScaleFactor(int factor) {
          zoomPanel.setZoomFactor(factor);
    class ZoomablePanel extends JPanel {
       private int zoomFactor;
       public ZoomablePanel() {
          super(null);
       public void setZoomFactor(int factor) {
          this.zoomFactor = factor;
          if (this.isShowing()) this.repaint();
       public void paint(Graphics g) {
          super.paintComponent(g);
          double d = zoomFactor / 100d;
          Graphics2D g2 =(Graphics2D)g;
          g2.scale(d, d);
          super.paint(g2);
    }

  • Using KeyMap in Editable JComboBoxes and JTable

    I am using Keymapping for JTextFields. It works fine ! I am interested in extending the keymap feature to JComboBoxes and JTable.

    if you want to do the keymapping inside the editable component of the combobox or the table, make sure you apply it on the editor component.e.g. comboBox.getEditor().getEditorComponent() and table.getCellEditor().getTableCellEditorComponent().

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

  • Escape key "dies" in combobox and JTable

    I have set in my JDialog the default key ESCAPE as this standard code:
              KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
              int param = JComponent.WHEN_IN_FOCUSED_WINDOW;
              root.getInputMap(param).put(escKey, "close");
              root.getActionMap().put("close", actionCancel);
         this.btCancel.setAction(actionCancel);
    The problem is when I have JComboBoxs and JTables. All key events seem to be consumed
    In this components (and maybe more components). So, if I press ESCAPE and my focus
    in a combobox, the dialog won't close.
    How could I work around this?
    thank you

    I've got the solution!
    I have a javaBean (JPanel) that has only one JComboBox. I trigger key pressed (don't know
    if should be key released in this case) on comboBox. Then I check if...
    this.comboBox.isPopupVisible().
    Simple. If popup is not visible and dispatch the event to this.
    I just wonder how the event goes to my javaBean, my javabean is in a dialog and this
    dialog of mine ends up to catch the event. ???
    Ok, this stays has a solution for future developers to found - in case they guess that
    right keywords :)

  • Showing a JFrame and waiting for its closing

    Hi,
    I have to show a JFrame and wait until the user clicks OK button within the JFrame (therefore JFrame closes and continues program flow).
    Is there any method or trick to stop program's execution when JFrame.show() code is executed? Or do I have to wait in an infinite loop until a variable's value is changed?
    EXAMPLE:
    program code A;
    JFrame a;
    a.show(); // It must wait here
    // Executed after OK button in JFrame
    program code B;
    Thanks

    I spent quite a while trying to make a JFrame modal (or make a modal JDialog appear to be like a frame, by displaying it in the title in the win32 taskbar) the problem is, is that JFrame and JDialog are heavyweight components (that use native code) so I think it is a restriction of the Operating System and not Swing.
    This is what i have concluded anyway. If someone does know this to be incorrect and knows a way of doing this. I would also like to know, as it was one that i could find no perfect solution.
    Cheers
    wwe8

  • Disposing a jframe, and freeing up memory

    Greetings,
    I hope this is the proper forum for memory issues.
    I have an enterprise database reporting desktop application that I am developing. The GUI application reports on a huge set of data that results in the app taking up to 125 MB worth of memory when fully loaded. There are moments in using the application that all of the data will need to be refreshed entirely, and the JFrame that reports it be reloaded in the process.
    I am wondering how to dispose the JFrame and release all of the data associated with it. I use NetBeans to develop my GUI, and so all of the data that is needed for the JFrame is a class variable of the JFrame (so the data can be accessed as it is needed). But, when the frame is disposed, I no longer need anything associated with the JFrame that gets disposed. The Javadoc for Window.dispose() seems to imply that not all of the resources will be released and GC'd when you call dispose, because it says "The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show." which to me says that the data is being remembered and not collected by the GC.
    Anyone have any tips for GUIs and memory management? It seems like any GUI app could get pretty large pretty fast if there's no way to release the data associated with the GUI.
    Here's the code I've tested that doesn't seem to be releasing the memory (stress tests of closing and re-opening the window multiple times shows the java.exe process eating more and more memory):
        public void reset(){
            this.dispose();
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PartsDashboard(partNum, dateFrom, dateTo);
            try{
                this.finalize();
            } catch (Throwable t){
                t.printStackTrace();
        }Thanks in advance.

    Three things you can always count on in life: Death, Taxes, and AndrewThompson64 telling people to post an SSCCE. =)
    Just poking fun.
    Anyways, this problem has gone from probably-should-deal-with-soon to critical issue. Here is the SSCCE to illustrate the problem. NOTE: My client is using Windows and I am using Windows, so how this acts on Linux/Mac isn't important to me. Also, a few of my client's machines are not well equipped (512 MB RAM), so they have agreed to up their hardware a bit.
    But the big problem, on my end, is that disposed windows DO NOT free up resources once disposed. My program is very data-heavy. I have considered grabbing less data from the database but this would mean the program would have to go to the database more often. The ultimate dilemma of time vs space, essentially.
    To explain the SSCCE: There is a main window with a button. If you click the button, it launches another window with a String array that is 500,000 items large (to simulate a lot of data), and a JList to view those strings. Closing the data-heavy child window does not free up the memory that it uses, and if you launch a bunch of the child windows in the same program instance (close each child before launching a new one) then you will see the amount of memory piling up.
    Am I doing something wrong? Has anyone else experienced similar problems? Does anyone have suggestions? Thank you.
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    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.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    * @author Ryan
    public class MemoryLeak {
        public static void main(String[] args) {
            // Launch Base Frame
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new BaseFrame().setVisible(true);
    class BaseFrame extends JFrame{
        public BaseFrame() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setPreferredSize(new Dimension(300,300));
            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout(FlowLayout.CENTER, 150, 5));
            JButton button = new JButton("Launch Data-Heavy Child");
            // JButton will launch Child Frame
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            // Notice no references to ChildFrame, period.
                            new ChildFrame().setVisible(true);
            panel.add(button);
            add(panel);
            pack();
    class ChildFrame extends JFrame{
        public ChildFrame() {
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setPreferredSize(new Dimension(300,600));
            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            // Simulate lots of data.
            String[] dataArr = new String[500000];
            for(int i = 0; i < dataArr.length; i++) {
                dataArr[i] = "This is # " + i;
            // Something to display the data.
            JList list = new JList(dataArr);
            JScrollPane scrollPane = new JScrollPane(list);
            scrollPane.setPreferredSize(new Dimension(200, 550));
            panel.add(scrollPane);
            add(panel);
            pack();
    }

  • Resizing JFrames and JPanels !!!

    Hi Experts,
    I had one JFrame in which there are three objects, these objects are of those classes which extends JPanel. So, in short in one JFrame there are three JPanels.
    My all JPanels using GridBagLayout and JFrame also using same. When I resize my JFrame ,it also resize my all objects.
    My Problem is how should i allow user to resize JPanels in JFrame also?? and if user is resizing one JPanel than other should adjust according to new size ...
    Plese guide me, how should i do this ...
    Thanknig Java Community,
    Dhwanit Shah

    Hey there, thanx for your kind intereset.
    Here is sample code .
    In which there is JFrame, JPanel and in JPanel ther is one JButton.Jpanel is added to JFrame.
    I want to resize JPanel within JFrame,I am able to do resize JFrame and JPanel sets accroding to it.
    import java.awt.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    public class FramePanel extends JFrame {
    JPanel contentPane;
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    public FramePanel() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    FramePanel framePanel = new FramePanel();
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(gridBagLayout1);
    this.setSize(new Dimension(296, 284));
    this.setTitle("Frame and Panel Together");
    MyPanel myPanel = new MyPanel();
    this.getContentPane().add(myPanel);
    this.setVisible(true);
    class MyPanel extends JPanel {
    public MyPanel() {
    this.setSize(200,200);
    this.setLayout(new FlowLayout());
    this.setBackground(Color.black);
    this.setVisible(true);
    this.add(new JButton("Dhwanit Shah"));
    I think i might explained my problem
    Dhwanit Shah
    [email protected]

  • Inserting a Gui program using JFrames and JPanel

    I'm trying to insert a chat program into a game that I've created! The chat program is using JFrames and JPanels. I want to insert this into a GridLayout and Panel. How can I go about doing this?

    whatever is in the frame's contentPane now, you add to a separate JPanel.
    you also add your chat stuff to the separate panel
    the separate panel is added to the frame as the content pane

Maybe you are looking for