Put  a stopwatch in a JFrame

Hi. Can anyone tell me the simplest way to put a stopwatch in a JFrame? I saw some examples but I couldn't quite understand them.

You didn't have to be so sarcastic! :) Anyway, I'm working on a quiz and I want to time how much it takes a person to finish the quiz. Here is my stopwatch class for the moment..
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
public class Cronometru extends JLabel
     int delay=1000;
     int counter=0,hours=0,minutes=0;
     Date date=new Date();
     private final static SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
     ActionListener action=new ActionListener(){
          public void actionPerformed(ActionEvent e)
                    counter++;
                    if (counter<60)
                         date.setSeconds(counter);
                    else
                         if(minutes<59)
                              date.setMinutes(++minutes);
                         else {date.setHours(++hours); minutes=0;
                         counter=0;
                    setText(sdf.format(date));
     private javax.swing.Timer timer=new javax.swing.Timer(delay,action);
     public Cronometru()
          timer.start();
}

Similar Messages

  • Putting an image in a JFrame

    I'm trying to paint an image onto a JFrame. Im making a monopoly game and need to paint the board, and repaint it after every turn. I dont know how to put an image onto a JFrame and was wondering if anyone could give me a basic algorithm or code example of how to do this. Thanks.

    Here is the basic algorithm to paint to a JFrame:
    Don't do it!
    Set the preferred size of a JPanel and add the JPanel to the JFrame. Paint to the JPanel by extending the paintComponent method. When you're ready to display, then remember to pack the JFrame and setVisible appropriately.
    You can read about doing this in the Java Tutorial.
    public void paintComponent(Graphics g){ //override in JPanel
      super.paintComponent(g);
      //do what ever you need to do here to draw your graphics.
    }I prefer to do all of my drawing to a BufferedImage and then use drawImage to show the image (off screen rendering):
    public void paintComponent(Graphics g){ //override in JPanel
      g.drawImage(myImage, 0, 0, this);
    }

  • Putting a jpanel into a jframe

    I have a main JFrame which was created by:
    public class ControllerGUI extends javax.swing.JFrameand inside this somewhere is a JPanel called myPanel.
    I have a seperate class which is a JPanel created by:
    public class Calc extends javax.swing.JPanelI am quite new to swing and have been using the GUI builder in Netbeans, so could someone please tell me how to put the seperate Calc JPanel into the JPanel myPanel which is in the JFrame. Is it something to do with creating a container for it? Thanks.
    Thanks.

    Not sure if you're still around, but here's a very simple example of putting a JPanel derived object into another JPanel. The Calc class here extends JPanel. It does nothing but shows a 3 by 3 grid of JLabels:
    import java.awt.Color;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    class Calc extends JPanel
        public Calc()
            setBorder(BorderFactory.createEmptyBorder(15, 0, 15, 0));
            // what the heck, have it show a 3x3 label grid
            setLayout(new GridLayout(0, 3, 10, 10)); // sets layout for the grid
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    String labelString = "[" + (i + 1) + ", " + (j + 1) + "]";
                    JLabel label = new JLabel(labelString);
                    label.setBorder(BorderFactory.createLineBorder(Color.blue));
                    label.setHorizontalAlignment(SwingConstants.CENTER);
                    add(label); // adds each label to the grid
    }Now I'll add it to myPanel which is a JPanel object, but before adding it, I'll set the myPanel's layout to be BorderLayout, and I'll add the Calc class to the CENTER position:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class FooFrame extends JFrame
        // declare and initialize the myPanel JPanel object and
        // the myCalc Calc object:
        private JPanel myPanel = new JPanel();
        private Calc myCalc = new Calc();
        public FooFrame(String s)
            super(s);
            getContentPane().add(myPanel); // add myPanel to the contentPane making it the main panel
            setPreferredSize(new Dimension(500, 400));
            myPanel.setLayout(new BorderLayout());  // here set the layout of mypanel
            myPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            // create a title panel and add it to the top of myPanel
            JLabel title = new JLabel("Application Title");
            JPanel titlePanel = new JPanel(new FlowLayout()); // redundant since jpanels
                                                            //use flowlayout by default
            titlePanel.add(title);
            myPanel.add(titlePanel, BorderLayout.PAGE_START); // adds title to top of myPanel
            // create a button panel and add it to the bottom of myPanel
            // here we'll use gridlayout
            JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 15, 0));
            JButton okButton = new JButton("OK"); // create buttons
            JButton cancelButton = new JButton("Cancel");
            buttonPanel.add(okButton); // add buttons to button panel
            buttonPanel.add(cancelButton);
            myPanel.add(buttonPanel, BorderLayout.PAGE_END); // adds buttonpanel to bottom of myPanel
            //** add the myCalc object to the center of the myPanel via borderlayout
            myPanel.add(myCalc, BorderLayout.CENTER);
        // initialize and show the JFrame
        private static void createAndShowUI()
            JFrame frame = new FooFrame("FooFrame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        // but be careful to show the JFrame in a thread-safe manner:
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • How and put data frrom DB into JFrame.tables ?

    hello,
    I tried to get rows from a DB into a table. Therefore I created a class(A) with a function(a1) throws SQLException. Connect and select rows from the DB runs perfectly. Now I want to put this data into a table. I created another class(B) extends JFrame with an inner class(icB1) extends AbstractTableModel. From here I tried call A.a1 to get the rows but
    1. the return type should be StringArray, how should i declare a function returning type stringarray and
    2. I tried to put the data into a String, so that the return value is String(Iwould try sort the data after returning values) like
    " icB1 extends AbstractTableModel { A.a1(); }" then i get the error msg: "java.sql.SQLException; must caught or declared to be thrown". Then i tried with this: " try { statement } catch { statement }" but it also doesnt func .. So how put I data from a DB into a table ? the main idea is to show and manage DB tables from the web. Many Thanks
    regards erkan

    Hi Erkan
    Here's parts of a simple tutorial style app that shows how to easily get data from a DB into a table. Note that the code is incomplete and may have typos.
    public class SQLHandler {
      public List getData(String sql, List headers) {
        List result = new ArrayList();
        ResultSet rs = connection.executeQuery(sql);
        // Get column details
        ResultSetMetaData rsmd = rs.getMetaData();
        int columns = rsmd.getColumnCount();
        for (int i=0;i<columns;i++) {
          headers.add(rsmd.getColumnLabel(i+1));
        while(rs.next()) {
          Object array = new Object[columns];
          for(int i=0;i<columns;i++) {
            array[i] = rs.getObject(i+1); 
          list.add(array):
        return result;
    public class SQLDataTableModel implements AbstractTableModel {
      private List data;
      private List headers = new ArrayList();
      public SQLDataTableModel(String sql) {
         data = sqlHandler.getData(sql,headers);
      // abstract methods
      public int getRowCount() {
        return list.size();
      public int getColumnCount() {
        return headers.size();
      public Object getValueAt(int row, int column) {
        Object[] array = data.get(row);
        return array[column];
    // Create JTable and assign a model
    JTable table = new JTable();
    table.setModel( new SQLDataTableModel("select * from table")):cheers
    Dave

  • How can I put a Viewer in my JFrame?

    Hello,
    I mean that i have a 3DViewer for VRML ,and i just want to put it on my JFrame(GUI) with JSplitPane ,the left of JFrame is ToolBar and the right is the Viewer.How can i do?
    Must i the Viewer in a Container load?

    Hi, mary. 
    Thank you for visiting Apple Support Communities. 
    I understand you are wanting to pair your iPhone with your car's hands free system.  The article below will walk you through that process.  Make sure to review your vehicle user guide for the pairing instructions and code. 
    iOS: Third-party Bluetooth accessories
    http://support.apple.com/kb/ht1664
    Cheers,
    Jason H. 

  • Putting an image into a JFrame or a JPanel

    Hello everybody,
    I'd like to know how to put an image (a real one, not a small icon we can't see it!) into a JFrame, or a JPanel, or included into a miscellanea element (label, textfield or somethiong else).
    Thanks,
    Regards
    Cedric

    Hi Cedric,
    If the image format is Jpg or gif, then the best way to insert the image
    into the Frame or panel is to use JLabel. You can pass the argument to the file as parameter to JLabel construction.
    For other formats, you have the option of using drawimage in paint function of applets.
    Hope this helps.
    Best Regards,
    Chandru

  • Need Help putting a JTable in a JFrame

    the problem iam having is trying to display the contents of a JTable into a JFrame, after pushing a JButton on the JFrame. I cant figure out how to do this. This is what i have for the ActionListener of the JButton:
    display = new JButton("Display Table");
    display.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    String file = null, line;
    String[][] data = new String[2155][7]; //A 2-dimensional array to store cells' data.
    String[] tmp = new String[7];
    String[] columnNames = new String[7];
    BufferedReader br = null;
    DefaultTableModel dm = new DefaultTableModel();
    dm = (DefaultTableModel) table.getModel();
    dm.setRowCount(0);
    dm.setColumnCount(0);
    try{
    br = new BufferedReader(new FileReader("testDetails.csv"));
    line = br.readLine(); //read the column headers
    //Set the column headers.
    columnNames = line.split(",");
    line = br.readLine(); //start reading into the records.
    //Create data for the table.
    int row = 0;
    while(line != null){
    tmp = line.split(",");
    for (int col = 0; col < columnNames.length; ++col){
    data[row][col] = tmp[col];
    row++;
    line = br.readLine();
    }//end of WHILE-statement.
    }//END of TRY-statement.
    catch(Exception er) { System.out.println(er); }
    // Configure the model with the data and column headers.
    dm.setDataVector(data, columnNames);
    // Create the table.
    table = new ram1Table();
    // Connect the model to the table.
    table.setModel(dm);
    // Create a scroll pane for the table.
    scrollpane = new JScrollPane(table); //scrollpane contains the table.
    // Make the table visible.
    field.add(scrollpane);
    Whatever help i get will be greatly appreaciated.

    1) Swing related questions should be posted in the Swing forum.
    2) Use the "code" formatting tags so the posted code is readable
    3) Get the program working first without using a JButton and ActionListener
    4) Whenever you add a component to a visible GUI you need to use revalidate() on the parent container. Of course the GUI won't automatically resize itself to show the new component so you may also need to resize the frame itself.

  • Problem with Paining in a Panel in a JFrame.

    So I can paint directly on a JFrame, and I can paint on a class that extends Panel, and put the Panel on a JFrame. But if I try to Repaint the Panel it won't show on the JFrame. Do I have to do anything to the JFrame to show the changes to the objects inside as well?

    I'm not sure if you've done this, but don't change the paint method when using Swing components, use paintComponent instead. By default, the JFrame will paint its children. Just remember whenever overriding any of the paintComponent methods to call super.paintComponent(g) first.

  • Drawing a picture within JFrame when I've already created a JFrame

    Hi everyone,
    I was wondering if you could help me out with this problem I'm getting. I'm creating a program to simulate an 'elevator.' When first creating the project I created a brand new 'Java GUI Form' : 'JFrame Form'. From here I went on to drag-and-drop various command buttons and labels to create the user interface (the 'inside' of an elevator). Here is where my question comes in. On the very left of my interface I want to have the program draw a simulation of a box (the elevator) moving up and down with the 'floor numbers' the user pushes. However i don't know how to access the coding of the jFrame object that I created through the design editor so i can input the coding.
    First Question: What do i have to 'write' that would force that box to print into the current JFrame?
    Second Question: What Code (and where do i put it) essentially 'locks' the JFrame from being resized?

    Here, maybe by putting this it might help you recognize what i'm trying to say. The code i'm trying to put in is:
    JFrame window = new JFrame ("Drawing");
            window.setBounds(200,200,700,500);
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setVisible(true);
            Container contentPane = window.getContentPane();
            contentPane.setBackground(new Color(125, 125, 125));
            Graphics g = contentPane.getGraphics();* This is a portion of the code
    When run, this program creates a NEW JFRAME WINDOWS, i'm trying to make it run inside an already existing JFrame, whose variable Name i dont know how to find.

  • How to print the JFrame In The Center Of The Page?

    hi there in the following code iam trying to print a JFrame
    but the frame appear in the printed page at the top left
    and i want it to appear in the top center of the page
    how to do that?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.print.*;
    class PrintUIWindow implements Printable, ActionListener {
        JFrame frameToPrint;
        public int print(Graphics g, PageFormat pf, int page) throws
                                                            PrinterException {
            if (page > 0) {
                return NO_SUCH_PAGE;
            Graphics2D g2d = (Graphics2D)g;
            g2d.translate(pf.getImageableX(), pf.getImageableY()-55);
            frameToPrint.print(g);
            return PAGE_EXISTS;
        public void actionPerformed(ActionEvent e) {
             PrinterJob job = PrinterJob.getPrinterJob();
             job.setPrintable(this);
             boolean ok = job.printDialog();
             if (ok) {
                 try {
                      job.print();
                 } catch (PrinterException ex) {
        public PrintUIWindow(JFrame f) {
            frameToPrint = f;
        public static void main(String args[]) {
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            JFrame f = new JFrame("Print UI Example");
            f.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {System.exit(0);}
            JLabel label1=new JLabel("Selling Bill",JLabel.CENTER);
            JLabel label2=new JLabel("Customer Name :Mahmoud Saleh       ",JLabel.LEFT);
            JLabel label3=new JLabel("Buying Date :29/8/2008             ",JLabel.LEFT);
            JLabel label4=new JLabel("Book Buyed :Java Printing          ",JLabel.LEFT);
            JLabel label5=new JLabel("Number : 6 Copies                  ",JLabel.LEFT);
            JLabel label6=new JLabel("Total Price :600 $                 ",JLabel.LEFT);
            label1.setFont(new Font("Courier New", Font.BOLD, 13));
            label2.setFont(new Font("Courier New", Font.BOLD, 13));
            label3.setFont(new Font("Courier New", Font.BOLD, 13));
            label4.setFont(new Font("Courier New", Font.BOLD, 13));
            label5.setFont(new Font("Courier New", Font.BOLD, 13));
            label6.setFont(new Font("Courier New", Font.BOLD, 13));
            JButton printButton = new JButton("Print This Window");
            printButton.addActionListener(new PrintUIWindow(f));               
            JPanel panel=new JPanel();
            panel.setLayout(new GridLayout(6,1));
            panel.add(label1);
            panel.add(label2);
            panel.add(label3);
            panel.add(label4);
            panel.add(label5);
            panel.add(label6);
            f.setSize(300,300);       
            f.setLocationRelativeTo(null);       
            f.add(panel,BorderLayout.CENTER);
            f.add(printButton,BorderLayout.SOUTH);
            panel.setBackground(Color.WHITE);
            f.setResizable(false);
            f.setVisible(true);
    }

    First_knight wrote:
    please tell me am i thinking right
    about this method: setImageableArea(.....)
    public void setImageableArea(double x, double y,  double width, double height);
    like I said, I've tried this method and it doesn't seem to do anything.
    the width=the JFrame Width,the height=the JFrame Height right?actually, when printing, 72 points (printing version of pixels) = 1 inch, so to do WYSIWYG, you need width = JFrameWidth * 72.0 / Toolkit.getToolkit().getScreenResolution. Ditto with height
    upper left beginningx(0)---------------------------200--------------------------------600-----------------------------------y(1000)upper right beginningyou need to do something like PageSetup.getImageableX and do Graphics.translate(x,y);
    also, if your page width = 720, that = 10 inches - that's a wide page (unless its in landscape)
    so if i want the JFrame To Be In The Center Of The Page I Would Choose From x=200 ,y=600 depending that frame width is 400Actually, it would be 300 - 700 in your example
    Because when i tried to use:setImageableArea(200, 600,  400, 200);like the above code
    no changes occurs in the printed paperYes. You need to offset the Graphics object

  • Hyperlink in JFrame

    I need to put a hyperlink in a JFrame and have the corresponding web page open when the link is clicked.
    Do you know how to or have code to do this?

    Look at JEditorPane and HyperlinkListener class. Check out O'Reilly's Java Swing, 2nd edition p.880.
    Cheers
    CB

  • Multiple Components in a JFrame (simple question)

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

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

  • GIF images in JFrame

    hi all, i'm trying to put a gif image in JFrame. The problem is the gif images gets flickering(fluctuation) while it is placed in a frame. i had also placed some labels near the image and all of them gets disturbed becoz of this gif file in frame. plz tel me a solution.
    Thanks .
    //MY CODE
    //~~~~~~~~~~
    import java.awt.*;
    import java.awt.Color;
    import java.awt.event.*;
    import javax.swing.*;
    class Label_ON_G extends JFrame// implements MouseListener,MouseMotionListener
      private Image image;
      JLabel label1;
      JButton button1;
      Dimension dimension=Toolkit.getDefaultToolkit().getScreenSize();
      public Label_ON_G()
           super("Display image example");
           getContentPane().setBackground(Color.white);
           getContentPane().setSize(dimension);
        setResizable(true);
        getContentPane().setLayout(null);
         Toolkit tk = Toolkit.getDefaultToolkit ();
         image = tk.getImage ("singlearea.gif");
        label1= new JLabel("RADHA");
        label1.setBounds(120,110,80,30);
        label1.setEnabled(false);
        add(label1);
        button1= new JButton("VIEW LABEL");
        button1.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent ae)
              label1.setEnabled(true);
             System.out.println("ActionPerformed");
        button1.setBounds(600,600,100,30);
        add(button1);
        setVisible(true);
        show();
    public void paint (Graphics g)
      g.drawImage(image, 100, 100, this);
      public static void main (String[] args)
      {     new Label_ON_G();     }
    }

    There is no need to do custom painting to display an image.
    [url http://java.sun.com/docs/books/tutorial/uiswing/components/label.html]How to Use Labels
    Unless you know what you are doing, never override the paint() method of the JFrame. There is no reason to do this.
    If you need to do custom painting then you override the paintComponent() method of a component that extends JComponent.

  • Multiple JScrollPanes in a singe JFrame

    Hi
    I want both JPanels to scroll. Pretty simple code, just add 9 buttons to two JPanels, out the JPanels in JScrollPanes and put the JScrollPanes in the JFrame. I've tried resizing the JFrame and setSize for the Panels/ScrollPanes but I can only get the top (doesn't matter which panel is added first) of the JFrame to show the scroll bar. The bottom Panel doesn't show the scroll bar.
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.StringTokenizer;
    import java.lang.*;
    public class testSP   {
       public static void main(String args[]) {
          JFrame j = new JFrame();
          JPanel jjj = new JPanel();
        //jjj.setSize(new Dimension(600,600));
          jjj.setLayout(new GridLayout(0,1));
          JButton b0 = new JButton("0");
          JButton b1 = new JButton("1");
          JButton b2 = new JButton("2");
          JButton b3 = new JButton("3");
          JButton b4 = new JButton("4");
          JButton b5 = new JButton("5");
          JButton b6 = new JButton("6");
          JButton b7 = new JButton("7");
          JButton b8 = new JButton("8");
          b0.setSize(new Dimension(100,100));
          b1.setSize(new Dimension(100,100));
          b2.setSize(new Dimension(100,100));
          b3.setSize(new Dimension(100,100));
          b4.setSize(new Dimension(100,100));
          b5.setSize(new Dimension(100,100));
          b6.setSize(new Dimension(100,100));
          b7.setSize(new Dimension(100,100));
          b8.setSize(new Dimension(100,100));
          jjj.add(b0);
          jjj.add(b1);
          jjj.add(b2);
          jjj.add(b3);
          jjj.add(b4);
          jjj.add(b5);
          jjj.add(b6);
          jjj.add(b7);
          jjj.add(b8);
          JScrollPane jjjSP = new JScrollPane(jjj);
         //jjjSP.setSize(new Dimension(600,600));
          JPanel kkk = new JPanel();
        //kkk.setSize(new Dimension(600,600));
          kkk.setLayout(new GridLayout(0,1));
          JButton k0 = new JButton("0");
          JButton k1 = new JButton("1");
          JButton k2 = new JButton("2");
          JButton k3 = new JButton("3");
          JButton k4 = new JButton("4");
          JButton k5 = new JButton("5");
          JButton k6 = new JButton("6");
          JButton k7 = new JButton("7");
          JButton k8 = new JButton("8");
          k0.setSize(new Dimension(100,100));
          k1.setSize(new Dimension(100,100));
          k2.setSize(new Dimension(100,100));
          k3.setSize(new Dimension(100,100));
          k4.setSize(new Dimension(100,100));
          k5.setSize(new Dimension(100,100));
          k6.setSize(new Dimension(100,100));
          k7.setSize(new Dimension(100,100));
          k8.setSize(new Dimension(100,100));
          kkk.add(k0);
          kkk.add(k1);
          kkk.add(k2);
          kkk.add(k3);
          kkk.add(k4);
          kkk.add(k5);
          kkk.add(k6);
          kkk.add(k7);
          kkk.add(k8);
          JScrollPane kkkSP = new JScrollPane(kkk);
        //kkkSP.setSize(new Dimension(600,600));
          j.getContentPane().add(kkkSP, BorderLayout.SOUTH);
          j.getContentPane().add(jjjSP, BorderLayout.CENTER);
          j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          j.setSize(275,395);
          j.setVisible(true);
    }

    import javax.swing.*;
    import java.awt.*;
    class testSP
       public static void main(String args[])
          JFrame j = new JFrame();
          JPanel jjj = new JPanel(new GridLayout(0,1));
          JPanel kkk = new JPanel(new GridLayout(0,1));
          JButton[] btn = new JButton[20];
          for(int x = 0; x < btn.length; x++)
            btn[x] = new JButton(""+(x+1));
            btn[x].setSize(new Dimension(100,100));
            if(x < 10)jjj.add(btn[x]);
            else kkk.add(btn[x]);
          JScrollPane jjjSP = new JScrollPane(jjj);
          jjjSP.setPreferredSize(new Dimension(300,200));//<--------------
          JScrollPane kkkSP = new JScrollPane(kkk);
          kkkSP.setPreferredSize(new Dimension(300,200));//<-----------
          j.getContentPane().add(kkkSP, BorderLayout.SOUTH);
          j.getContentPane().add(jjjSP, BorderLayout.CENTER);
          j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          j.pack();
          j.setVisible(true);
    }

  • Images in JFrame

    Hi. I need to put an image over a JFrame, I browse a lot of sites but I did not found anything useful. Someone know how to do this?
    Regards.

    You cannot place the image directly on the JFrame's rootpane
    Try the following
    JLabel imageLabel = new JLabel(new ImageIcon("test.gif"));Then add this label to your frame.

Maybe you are looking for