[b]GridLayout Problem[/b]

Hi all I am just a Beginner and have a problem in that when using grid layout (2,1) it splits my GUI in half!
This is a problem as the Panel I wish to add in the first half od the screen only takes up 1/5 of the screen.
Does anyone know if I can tell the gridlayout how to proportionate the screen so it is not a half half disection???

It's from documentation: "A GridLayout places components in a grid of cells.
Each component takes all the available space within its cell, and each cell is exactly the same size."
So you have no chance to add panel that takes 1/5 of whole space with your (2,1) GridLayout.
Use some more sophisticated layout to do this.

Similar Messages

  • GridLayout problem in Linux with SashForm (SWT)

    I have tried an example using SashForm in Linux.
    Its displaying well if I use FillLayout for my Shell.
    but SashForm and its contents are not displayed if
    I use GridLayout for Shell.
    I have given my code below.
    Please help me in this issue.
    Thanks in advance
    import java.awt.BorderLayout;
    import java.awt.Frame;
    import java.awt.Panel;
    import org.apache.batik.swing.JSVGCanvas;
    import org.eclipse.swt.*;
    import org.eclipse.swt.awt.SWT_AWT;
    import org.eclipse.swt.custom.*;
    import org.eclipse.swt.layout.*;
    import org.eclipse.swt.widgets.*;
    public class SashTest {
    public static void main (String [] args) {
    final Display display = new Display ();
    Shell shell = new Shell(display);
    shell.setLayout (new GridLayout(1,true));
    GridData data = new GridData(GridData.FILL_BOTH);
    Composite comp = new Composite(shell, SWT.EMBEDDED|SWT.BORDER);
    comp.setLayout(new FillLayout());
    comp.setLayoutData(data);
    SashForm sashForm = new SashForm(comp,SWT.HORIZONTAL|SWT.EMBEDDED|SWT.BORDER);
    sashForm.setLayout(new FillLayout(SWT.HORIZONTAL));
    Composite ctreeComp= new Composite(sashForm,SWT.BORDER);
    ctreeComp.setLayout(new FillLayout());
    Tree cTree = new Tree(ctreeComp, SWT.SINGLE | SWT.BORDER);
    for(int i=0;i TreeItem items = new TreeItem(cTree, SWT.NULL);
    items.setText("Treeitem "+i);
    Composite cgComp = new Composite(sashForm, SWT.BORDER|SWT.EMBEDDED);
    cgComp.setLayout(new FillLayout());
    sashForm.setWeights(new int[]{20,80});
    //Setting up canvas for rendering process wise communication graphs
    Frame pcFrame = SWT_AWT.new_Frame(cgComp);
    Panel cPanel = new Panel(new BorderLayout());
    pcFrame.add(cPanel);
    cPanel.add(new JSVGCanvas());
    shell.open ();
    while (!shell.isDisposed ()) {
    if (!display.readAndDispatch ()) display.sleep ();
    display.dispose ();
    }

    Mario,
    Open Source drivers for our DAQ products are developed by the Comedi project. It should be noted that these drivers may not contain the full functionality of the NI-DAQ driver available for E Series devices under the various Windows and Mac operating systems.
    For information regarding the Comedi Project please see http://stm.lbl.gov/comedi. Support for the Comedi drivers is available through the Comedi mailing list. Please contact the Comedi mailing list for questions regarding this Open Source driver.
    For more information on National Instruments Measurement and Automation products for linux, see http://www.ni.com/linux.
    Regards,
    Justin Britten
    Applications Engineer
    National Instruments

  • Problem with seeing JComponents in GridLayout

    Hi everybody. I'm having some hard time with my pie chart application and hope that you can help me to fix the problem.
    I have a Graph class that represents a single pie chart. It's similar to this (I've simplified it for better understanding):
      public class Graph extends JComponent{
      public SliceVal[] slices;
      public Graph(){
       setPreferredSize(new Dimension(100, 100));
       slices = new SliceVal[sliceNum];
      public SliceVal[] getSliceVal(){
        return this.slices;
      public void setSliceVal(SliceVal[] slices){
        this.slices = slices;
      public void drawGraph(Graphics2D g, Rectangle area, SliceVal[]
    slices) {
            //Some code here
            g.setColor(...);
            g.fillArc(...);
            setBorder( BorderFactory.createLineBorder(Color.BLUE) );
      public void paintComponent(Graphics g) {
            drawGraph((Graphics2D)g, getBounds(), slices);
    I use this class in my application to show the pie charts with a gridview layout. The code I use to achieve this is like:
    public void run() {
           Graph[] graphs = new Graph[graphNum];
           JFrame frame = new JFrame();
           for(int i=0; i<graphNum; i++){
             graphs[i] = new Graph();
             SliceVal[] sliceValA = new SliceVal[sliceNum];
             for(int j=0;j<sliceNum;j++){
               sliceValA[j] =  new SliceVal(new BigDecimal(10.0),
    colors[j]);
             graphs.setSliceVal(sliceValA);
    JPanel grafPanel = new JPanel();
    graphPanel.setLayout(new GridLayout(1,graphNum));
    for (int i=0; i<graphNum; i++) {
    grafPanel.add(graphs[i]);
    frame.getContentPane().add(graphPanel);
    frame.pack();
    frame.setVisible(true);
    The output of this pogram can be seen here:
    http://img459.imageshack.us/img459/5517/graf5gf.jpg
    graphNum was 4 but I can only see the first component.
    Do you see something wrong here?
    I would appreciate any help, thanks.
    Eren Aykin

    The coordinates are as you said but I can't see why this is a problem. Each
    graph is sopposed to be drawn in it's own area.getBounds() returns the location/size of the object (let's work with just the first 2)
    0,0,100,100
    100,0,100,100
    these coordinates are its location and its size within its container
    the first one draws OK, because it is being drawn at 0,0 with a width/height of 100,100
    the second one starts drawing at 100,0
    this 100,0 is the point of the component, not the point on the container, so it is
    being drawn from the very right edge out into oblivion - not drawn onto the next
    component.
    here's a simple version of your code. It just draws a string number, relative
    to its placement - 0,1,2,3
    run it as is, same problem, only the 0 will appear in the first panel
    comment out the drawgraph with getBounds() and uncomment the line where
    the dimensions of the component are passed, and 0,1,2,3 all appear
    import java.awt.*;
    import javax.swing.*;
    class Testing
      public Testing()
        int graphNum = 4;
        Graph[] graphs = new Graph[graphNum];
        JFrame frame = new JFrame();
        for(int i=0; i < graphNum; i++)
          graphs[i] = new Graph(i);
        JPanel grafPanel = new JPanel();
        grafPanel.setLayout(new GridLayout(1,graphNum));
        for (int i=0; i < graphNum; i++)
          grafPanel.add(graphs);
    frame.getContentPane().add(grafPanel);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    public static void main(String[] args){new Testing();}
    class Graph extends JComponent
    int graphNum;
    public Graph(int gn)
    graphNum = gn;
    setPreferredSize(new Dimension(100, 100));
    public void drawGraph(Graphics g, Rectangle area)
    g.drawString(""+graphNum,area.x,area.y+50);//50 is to ensure below titlebar
    setBorder( BorderFactory.createLineBorder(Color.BLUE) );
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    drawGraph(g, getBounds());//<----------------------------comment out this line, then use below line
    //drawGraph(g, new Rectangle(0,0,100,100));

  • Problem updaing a GridLayout JPanel

    Problem updaing a GridLayout JPanel
    What I want to do in the following method is very straight forward. First, I will remove all components inside the namesPanel, then reset the layout and add new things back to the panel. However, now it does not clean up things. For example, if I set numberOfPlayers to 10, and call this method, 10 users info will be shown. Then if I set numberOfPlayers to 2, more than 2 users' info will be shown! Some info from the previous 10 users will be left behind. Is there a better way to clean up things?
    Also, if I call this method right after I add the namesPanel to its parent panel, which will be added to the contentPanel of JFrame, it won't work, but it will work if I call it after that through the actionPerformed method. The value of numberOfPlayers is set by a JComboBox. When a user selects an item, numberOfPlayers will be changed, and the populateNames() will be called through the actionPerformed method. Thank you in advance.
    public void populateNames(){
             namesPanel.removeAll();
             jf.pack();
             namesPanel.setLayout(new GridLayout(numberOfPlayers+1, 2));
             JTextField[] jt_playerNames = new JTextField[numberOfPlayers];
             playerNames = new String[numberOfPlayers];
            for(int i=0;i<numberOfPlayers;i++){
                 namesPanel.add(new JLabel("Player name:"));
                jt_playerNames[i] = new JTextField("Player " + (i+1));
                playerNames[i] = "Player " + (i+1);
                namesPanel.add(jt_playerNames);

    No, namesPanel.revalidate(); doesn't help. jf.repaint() actually works.
    But it still doesn't work the first time I call it right before I add it to its parent panel.

  • Inherited JPanels inserted to GridLayout - panel size problem

    Hello,
    I'm not sure if I implemented it correctly, however I'm trying to have different-sized JPanels inserted to GridLayout. JPanels are inherited from base JPanel class. Shortly:
    public class CMyBasePanel extends javax.swing.JPanel
    public class CPanelBig extends CMyBasePanel
        this.setLayout(null);
        this.setPreferredSize(new java.awt.Dimension(642, 138));
    public class CPanelSmall extends CMyBasePanel
        this.setLayout(null);
        this.setPreferredSize(new java.awt.Dimension(642, 50));
    }and I'm trying to insert them that way:
    int numPanels = this.panels.size();    // Vector of CMyBasePanel
    jPanelSteps = new JPanel();
    jPanelSteps.setLayout(new GridLayout(numPanels, 1));
    for (int i = 0; i < numPanels; i++)
        CMyBasePanel onePanel = (CMyBasePanel)this.panels.get(i);
        jPanelSteps.add(onePanel);
    jScrollPaneSteps.setViewportView(jPanelSteps);
    jScrollPaneSteps.revalidate();
    jScrollPaneSteps.repaint();This method shows created panels correctly, but the panel height is constant for all panels, even if they have different Dimensions set in the constructor.
    Full case can be downloaded here: http://slajerek.demon.pl/others/bugs/JPanelInheritProblem.tar.gz
    After starting the case just right click on empty space to show popup menu and add two different panels, size of already added panels is changed respectively (add 10 small panels, and then big one). Java version: Java(TM) SE Runtime Environment (build 1.6.0_02-b05), Linux
    is this a bug or bad implementation? I thought that if I change one of the parameters in the inherited class I'm not changing the base class. For me it seems that the panel size is declared "static"? how to avoid this problem and have different heights for panels?

    yea GridLayout resizes components to fit in the grid, where all the grids are the same size. So if you have one big component in a grid, then the components in the other grid will be resized i believe.

  • Problem with drawLine and GridLayout Manager

    Hi
    I am writing a piece of software that lets you design a local area network. Currently I have a JPanel with a GridLayout of 10 squares by 10 squares. Each of these grid spaces is filled with a small custom component that is blank if empty or displaying the relevant graphic to the user if a node has been placed. The difficulty that I am having is that I want to be able to draw a section of cable between nodes. As an example, when the user places a Server and a client, I want them to be able to hold down SHIFT, select the two nodes, then press a key (probably 'c') to automatically generate a run of cable between the two nodes. The software achieves this by getting the co-ordinates of the center point of the two nodes and drawing a line between them using the graphics class drawLine() method. I have all of this working fine apart from the bit where the cable needs to be drawn. The reason is that I can only create a section of cable by creating a new component and then using g.drawLine(). Fair enough. However, I can only draw within the small grid section designated by the GridLayout manager in the JPanel. What I am asking is how would I go about getting the software to draw a line between two relative co-ordinates on the screen, disregarding any positioning that the GridLayout manager tries to impose. To put it another way, how would I go about getting the software to draw a line between two absolutety specified co-ordinates, as opposed to relative co-ordinates currently being used? Any help would be greatly appeciated, thanks

    Here's a way to draw lines between component centers irrespective of layouts.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class GridDrawing
        public static void main(String[] args)
            JLabel[] labels = new JLabel[100];
            JPanel loPanel = new JPanel(new GridLayout(0,10));
            for(int j = 0; j < labels.length; j++)
                labels[j] = new JLabel(String.valueOf(j + 1), JLabel.CENTER);
                labels[j].setBorder(BorderFactory.createEtchedBorder());
                loPanel.add(labels[j]);
            OverdrawPanel overdrawPanel = new OverdrawPanel();
            CableSelector selector = new CableSelector(overdrawPanel, loPanel);
            JPanel panel = new JPanel();
            OverlayLayout overlay = new OverlayLayout(panel);
            panel.add(overdrawPanel);
            panel.setLayout(overlay);
            panel.add(loPanel);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class OverdrawPanel extends JPanel
        List cableList;
        public OverdrawPanel()
            cableList = new ArrayList();
            setOpaque(false);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.red);
            for(int j = 0; j < cableList.size(); j++)
                g2.draw((Line2D)cableList.get(j));
        public void addCable(Point2D p1, Point2D p2)
            Line2D line = new Line2D.Double(p1, p2);
            cableList.add(line);
            repaint();
        public void register(CableSelector cs)
            addMouseListener(cs);
    class CableSelector extends MouseAdapter
        OverdrawPanel overdrawPanel;
        JPanel loPanel;
        boolean firstPointSet;
        Point2D firstPoint;
        public CableSelector(OverdrawPanel op, JPanel lp)
            overdrawPanel = op;
            loPanel = lp;
            firstPointSet = false;
            overdrawPanel.register(this);
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            Component[] c = loPanel.getComponents();
            Rectangle r;
            for(int j = 0; j < c.length; j++)
                r = c[j].getBounds();
                if(r.contains(p))
                    if(!firstPointSet)
                        firstPoint = new Point2D.Double(r.getCenterX(), r.getCenterY());
                        firstPointSet = true;
                    else
                        Point2D p2 = new Point2D.Double(r.getCenterX(), r.getCenterY());
                        overdrawPanel.addCable(firstPoint, p2);
                        firstPointSet = false;
    }

  • Problem with Gridlayout

    I have a two dimensional Button array ([19] [31]), and I want to put them in a window with 19 rows of buttons, 31 buttons a row, no space between the buttons (sorta like minesweeper). Is gridlayout the best solution for this. If it is, could someone please tell me how to put them there, I have come as far as making a doubleloop. What is the command for adding buttons, and how do I decide the coordinates for it?
    �sbj�rn from Norway

    Do I have to create a panel first in order to use GridBagLayout? Could you write how you create a panel in gridbag and add buttons from an already existing twodimensional array, please?

  • Can some one help me with this problem with my frame???

    i have gt a veri strange problem with my program,that is teh graphic changes only when i resize the the frame,if i dun resize,it will remain the same.However what i intended is that when i click on the radio button,it will change immediately to the respective pages.A simple version of my code is below,can someone helpl me solve it??(there is 3 different class)
    import java.awt.event.*;
    import javax.swing.*;
    public class MainPg extends JFrame implements ActionListener{
         private javax.swing.JPanel jContentPane = null;
         private javax.swing.JPanel buttons = null;
         private javax.swing.JRadioButton one = null;
         private javax.swing.JRadioButton two = null;
         private javax.swing.JPanel change = null;
         public MainPg() {
              super();
              initialize();
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
              this.setName("mainClass");
              this.setVisible(true);
         private javax.swing.JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(new java.awt.BorderLayout());
                   jContentPane.add(getButtons(), java.awt.BorderLayout.WEST);
                   jContentPane.add(getChange(), java.awt.BorderLayout.CENTER);
              return jContentPane;
         private javax.swing.JPanel getButtons() {
              if(buttons == null) {
                   buttons = new javax.swing.JPanel();
                   java.awt.GridLayout layGridLayout1 = new java.awt.GridLayout();
                   layGridLayout1.setRows(2);
                   layGridLayout1.setColumns(1);
                   ButtonGroup group=new ButtonGroup();
                   group.add(getOne());
                   group.add(getTwo());
                   buttons.setLayout(layGridLayout1);
                   buttons.add(getOne(), null);
                   buttons.add(getTwo(), null);
              return buttons;
         private javax.swing.JRadioButton getOne() {
              if(one == null) {
                   one = new javax.swing.JRadioButton();
                   one.setText("One");
                   one.setSelected(true);
                   one.addActionListener(this);
                   one.setActionCommand("one");
              return one;
         private javax.swing.JRadioButton getTwo() {
              if(two == null) {
                   two = new javax.swing.JRadioButton();
                   two.setText("Two");
                   two.addActionListener(this);
                   two.setActionCommand("two");
              return two;
         private javax.swing.JPanel getChange() {
              if(change == null) {
                   change = new javax.swing.JPanel();
              change.add(new One());
              return change;
         public static void main(String[] args){
              new MainPg();
         public void actionPerformed(ActionEvent e) {
              change.removeAll();
              if("one".equals(e.getActionCommand())){
                   change.add(new One());
              else{
                   change.add(new Two());
              change.repaint();
    import javax.swing.*;
    public class One extends JPanel {
         private javax.swing.JPanel jPanel = null;
         private javax.swing.JLabel jLabel = null;
         private javax.swing.JPanel jPanel1 = null;
         private javax.swing.JLabel jLabel1 = null;
         private javax.swing.JLabel jLabel2 = null;
         public One() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setLayout(new java.awt.BorderLayout());
              this.add(getJPanel(), java.awt.BorderLayout.NORTH);
              this.add(getJPanel1(), java.awt.BorderLayout.WEST);
              this.setSize(300, 200);
         * This method initializes jPanel
         * @return javax.swing.JPanel
         private javax.swing.JPanel getJPanel() {
              if(jPanel == null) {
                   jPanel = new javax.swing.JPanel();
                   jPanel.add(getJLabel(), null);
              return jPanel;
         * This method initializes jLabel
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setText("one");
              return jLabel;
         * This method initializes jPanel1
         * @return javax.swing.JPanel
         private javax.swing.JPanel getJPanel1() {
              if(jPanel1 == null) {
                   jPanel1 = new javax.swing.JPanel();
                   java.awt.GridLayout layGridLayout2 = new java.awt.GridLayout();
                   layGridLayout2.setRows(2);
                   layGridLayout2.setColumns(1);
                   jPanel1.setLayout(layGridLayout2);
                   jPanel1.add(getJLabel2(), null);
                   jPanel1.add(getJLabel1(), null);
              return jPanel1;
         * This method initializes jLabel1
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel1() {
              if(jLabel1 == null) {
                   jLabel1 = new javax.swing.JLabel();
                   jLabel1.setText("one");
              return jLabel1;
         * This method initializes jLabel2
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel2() {
              if(jLabel2 == null) {
                   jLabel2 = new javax.swing.JLabel();
                   jLabel2.setText("one");
              return jLabel2;
    import javax.swing.*;
    public class Two extends JPanel {
         private javax.swing.JLabel jLabel = null;
         public Two() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setLayout(new java.awt.FlowLayout());
              this.add(getJLabel(), null);
              this.setSize(300, 200);
         * This method initializes jLabel
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setText("two");
              return jLabel;
    }

    //change.repaint();
    change.revalidate();

  • Puzzle Game and new Game Problem

    Hello Java Programmers,
    Once again I have encountered a problem with my ongoing puzzle game. I have completed it all. Now I want my user to be able to start a new game in after they win. I tried repaint and update method with JFrame but it deosn't reshuffle the buttons. How can I do that. The code geos below.
    [/b]
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JOptionPane;
    public class PuzzleGame{
       String[] btn_Labels = {"1","2","3","4","5","6","7","8","9",
                            "10","11","12","13","14","15"," "};
       String[] labels = {"1","2","3","4","5","6","7","8","9",
                            "10","11","12","13","14","15"};
       private final int ONE = 1, TWO = 2, THREE = 3, FIVE = 5;
       private boolean WIN_STATE = false; 
       private JButton b[];
       public String clicked_btn_label = "";
       //Constructor method.
       public PuzzleGame(){
          showSplashScreen();
          initGame();
       public static void main(String args[]){
          PuzzleGame game = new PuzzleGame();
       //When a new Game started labels of buttons are shuffled using this method.
       public void shuffleNumbers(){
          String temp = null;   
          for(int j=0; j<16; j++){
          int k = (int)(Math.random()*16);
          temp = btn_Labels[j];
          btn_Labels[j] = btn_Labels[k];
          btn_Labels[k] = temp;           
       //Game initialization method.
       public void initGame(){
          b = new JButton[16];
          JPanel p = new JPanel();
          JFrame frame = new JFrame();
          shuffleNumbers();
          for(int i=0; i<16; i++){
             b[i] = new JButton();
             b.setText(btn_Labels[i]);
    b[i].setActionCommand(""+(i+1));
    for(int i=0; i<16; i++){
    b[i].addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent e){
    clicked_btn_label =(String)e.getActionCommand();
    doSwapping();
    checkWin();
    p.add(b[i]);
    p.setLayout(new GridLayout(4,4));
    frame.getContentPane().add(p);
    frame.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    Dimension dm = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (dm.width - 230)/2;
    int y = (dm.height - 240)/2;
    frame.setBounds(x,y,320,240);
    frame.setSize(340,240);
    frame.setVisible(true);
    //This method swaps the clicked button with the empty button if it doesn't violate rule.
    public void doSwapping(){
    int num = Integer.parseInt(clicked_btn_label);
    String temp;
    if( (num + ONE <= 16) && b[num].getText() == " " && num % 4 != 0){
    temp = b[num].getText();
    b[num].setText(b[num-ONE].getText());
    b[num-ONE].setText(temp);
    else if((num - TWO >= 0) && b[num-TWO].getText() == " " && ((num - ONE) % 4 != 0)){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num-TWO].getText());
    b[num-TWO].setText(temp);
    else if( (num + THREE < 16) && b[num+THREE].getText() == " "){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num+THREE].getText());
    b[num+THREE].setText(temp);
    else if( (num - FIVE >= 0) && b[num-FIVE].getText() == " "){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num-FIVE].getText());
    b[num-FIVE].setText(temp);
    // else{}
    public void checkWin(){
    WIN_STATE = true;
    for(int i=0; i<15; i++){
    if( b[i].getText() != labels[i])
    WIN_STATE = false;
    if(WIN_STATE == true){
    JOptionPane.showMessageDialog(null,"Congratulations You Have won the Game!","You Win",JOptionPane.INFORMATION_MESSAGE);
         initGame();
    public void showSplashScreen(){
    JWindow w = new JWindow();
    JPanel p = (JPanel)w.getContentPane();
    JLabel l = new JLabel(new ImageIcon("splash.jpg"));
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (d.width - 230)/2;
    int y = (d.height - 240)/2;
    p.add(l);
    w.setBounds(x,y,320,240);
    w.setVisible(true);
    try{
    Thread.sleep(10000);
    catch(Exception e){
    w.setVisible(false);
    [/b]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Sorry for violation. I would like to add a menubar to the application containing a single menu button for new game. adding a menubar is simple but how can i reshuffle the buttons using methods like update etc. or any other way.

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • How to make a JPanel with a GridLayout scroll

    I am using a JPanel to hold around 100 buttons. The JPanel is using GridLayout to organise these buttons in rows of 3 buttons per row. i.e. buttonPanel.setLayout(new GridLayout(33,3)); As there are so many buttons they obviously don't all fit in the viewable area of the screen. To get around this I am trying to use a JScrollPane on the buttonPanel to make it scroll but I can't get it to work. I have tried both creating a seperate JScrollPane object and adding the buttonPanel to it
    JScrollPane buttonScroll = new JScrollPane();
    buttonPanel.setLayout(new GridLayout(33,3));
    buttonPanel.setPreferredSize(new Dimension(380,400));
    buttonPanel.setMaximumSize(new Dimension(380,400));
    buttonScroll.add(buttonPanel);and also embeding everything into a new JPanel like:
    buttonHolder.add(new JScrollPane(buttonPanel),BorderLayout.CENTER);Neither way works. Any ideas. I've read about view port but not exactly sure what this is or if this will fix my problem.
    Help urgently required.

    Fixed layouts have their perils.
    We need to figure the size for the buttonScroll. Here's one way to approach this:
        topPanel
            messagePanel 400 x 400    buttonScroll unknown size
        inputPanel
            previewPane  600 x  80    sendButton   icon size (55 x 68, duke)
        For a fixed layout, find the size required for the buttonScroll by commenting out the
        two lines that add the buttons to buttonPanel and calling pack on the frame:
        frame size (pack w/no buttons)     743 x 570
        topPanel size                      735 x 400
        therefore, required size for
            buttonScroll is                335 x 400     (735 - 400, 400)
    After adding the buttons back in the final sizes become
    C:\jexp>java GUI
    frame width = 763       height = 570
    topPanel width = 755    height = 400I substituted a Duke image for your sendIcon so the sizes may differ but this should get you started...
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.Container.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    public class GUI extends JFrame
        Icon sendIcon = new ImageIcon(getClass().getResource("images/T4.gif"));
        Icon deleteIcon = new ImageIcon(getClass().getResource("images/T6.gif"));
        JButton sendButton = new JButton("Send",sendIcon);
        JButton deleteButton = new JButton("Delete",deleteIcon);
        JLabel statusBar = new JLabel();
        JMenu optionsMenu = new JMenu("Options");
        JMenu helpMenu = new JMenu("Help");
        JMenuBar menuBar = new JMenuBar();
        JMenuItem connectMenuItem = new JMenuItem("Connect");
        JMenuItem disconnectMenuItem = new JMenuItem("Disconnect");
        JMenuItem exitMenuItem = new JMenuItem("Exit");
        JMenuItem helpMenuItem = new JMenuItem("Online Help");
        JMenuItem aboutMenuItem = new JMenuItem("About");
        JPanel buttonPanel = new JPanel();
        JPanel inputPanel = new JPanel();
        JPanel messagePanel = new JPanel();
        JPanel topPanel = new JPanel();
        JPanel buttonHolder = new JPanel();
        JScrollPane buttonScroll = new JScrollPane(buttonPanel,20,30);
        JTextPane messageArea = new JTextPane();
        JTextPane previewPane = new JTextPane();
        public GUI()
            super("Chat Program");
            String userName = "user";
            statusBar.setText("Connected: " + userName);
            menuBar.add(optionsMenu);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            optionsMenu.add(connectMenuItem);
            optionsMenu.add(disconnectMenuItem);
            optionsMenu.add(exitMenuItem);
            helpMenu.add(helpMenuItem);
            helpMenu.add(aboutMenuItem);
            buttonPanel.setLayout(new GridLayout(0,3));
            for(int i = 0; i < 100; i++)
                buttonPanel.add(new JButton("Button " + (i + 1)));
            messageArea.setEditable(false);
            previewPane.setEditable(false);
            previewPane.setPreferredSize(new Dimension(600,80));
            previewPane.setMaximumSize(new Dimension(600,80));
            messagePanel.setLayout(new BorderLayout(10,10));
            messagePanel.add(new JScrollPane(messageArea),BorderLayout.CENTER);
            messagePanel.setPreferredSize(new Dimension(400,400));
            messagePanel.setMaximumSize(new Dimension(400,400));
            // w = 735 - 400, h = 400
            // does not take into account the width of the vertical scrollBar
            buttonScroll.setPreferredSize(new Dimension(335,400));       // *
            Box box = new Box(BoxLayout.X_AXIS);
            box.add(new JScrollPane(previewPane));
            box.add(sendButton);
            inputPanel.add(box,BorderLayout.CENTER);
            statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
            topPanel.setLayout(new BorderLayout(10,10));
            topPanel.add(messagePanel, BorderLayout.WEST);
            topPanel.add(buttonScroll, BorderLayout.EAST);
            Container content = getContentPane();
            content.add(topPanel,   BorderLayout.NORTH);
            content.add(inputPanel, BorderLayout.CENTER);
            content.add(statusBar,  BorderLayout.SOUTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
    //        setSize(?,?);       // 763, 570 (now we know)
            setLocation(200,200);
            setVisible(true);
            // collect size information
            System.out.println("frame width = " + getWidth() + "\t" +
                               "height = " + getHeight() + "\n" +
                               "topPanel width = " + topPanel.getWidth() + "\t" +
                               "height = " + topPanel.getHeight());
        public static void main(String[] args)
            new GUI();
    }

  • MDI JTable Overlap Area Repaint Problem

    Hi all,
    I have a problem for my application in MDI mode.
    I open many windows (JInternalFrame contain JTable) under JDesktopPane. Some of the windows are overlapping and when they receive update in the table, it seems repaint all of the overlapping windows, not only itself. This make my application performance become poor, slow respond for drap & drop an existing window or open a new window.
    To prove this, i make a simple example for open many simple table and have a thread to update the table's value for every 200 mill second. After i open about 20 windows, the performance become poor again.
    If anyone face the same problem with me and any suggestions to solve the problem ?
    Please help !!!!!
    Following are my sources:
    public class TestMDI extends JFrame {
        private static final long serialVersionUID = 1L;
        private JPanel contentPanel;
        private JDesktopPane desktopPane;
        private JMenuBar menuBar;
        private List<TestPanel> allScreens = new ArrayList<TestPanel>();
        private List<JDialog> freeFloatDialogs = new ArrayList<JDialog>();
        private List<JInternalFrame> mdiInternalFrm = new ArrayList<JInternalFrame>();
        int x = 0;
        int y = 0;
        int index = 0;
        private static int MDI_MODE = 0;
        private static int FREE_FLOAT_MODE = 1;
        private int windowMode = MDI_MODE;
        public TestMDI() {
            init();
        public static void main(String[] args) {
            new TestMDI().show();
        public void init() {
            contentPanel = new JPanel();
            desktopPane = new JDesktopPane();
            desktopPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
            desktopPane.setFocusTraversalKeysEnabled(false);
            desktopPane.setFocusTraversalPolicyProvider(false);
            desktopPane.setBorder(null);
            desktopPane.setIgnoreRepaint(true);
            desktopPane.setPreferredSize(new Dimension(1000, 800));
            this.setSize(new Dimension(1000, 800));
            menuBar = new JMenuBar();
            JMenu menu1 = new JMenu("Test");
            JMenuItem menuItem1 = new JMenuItem("Open Lable Screen");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        final TestJLableScreen screen = new TestJLableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            JMenuItem menuItem2 = new JMenuItem("Open Table Screen");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        TestTableScreen screen = new TestTableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            menu1.add(menuItem1);
            menu1.add(menuItem2);
            this.setJMenuBar(menuBar);
            this.getJMenuBar().add(menu1);
            this.getJMenuBar().add(createSwitchMenu());
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(desktopPane);
            desktopPane.setDesktopManager(null);
        public JInternalFrame createInternalFram(final TestPanel panel) {
            final CustomeInternalFrame internalFrame = new CustomeInternalFrame(panel.getTitle(), true, true, true, true) {
                public void doDefaultCloseAction() {
                    super.doDefaultCloseAction();
                    allScreens.remove(panel);
            internalFrame.setPanel(panel);
            // internalFrame.setOpaque(false);
            internalFrame.setSize(new Dimension(1010, 445));
            internalFrame.add(panel);
            internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setFocusTraversalPolicyProvider(false);
            desktopPane.getDesktopManager();
            // internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setIgnoreRepaint(true);
            return internalFrame;
        public JDialog createJDialog(final TestPanel panel) {
            JDialog dialog = new JDialog(this, panel.getTitle());
            dialog.setSize(new Dimension(1010, 445));
            dialog.add(panel);
            dialog.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    allScreens.remove(panel);
            return dialog;
        public JMenu createSwitchMenu() {
            JMenu menu = new JMenu("Test2");
            JMenuItem menuItem1 = new JMenuItem("Switch FreeFloat");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = FREE_FLOAT_MODE;
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    remove(desktopPane);
                    desktopPane.removeAll();
    //                revalidate();
                    repaint();
                    add(contentPanel);
                    index = 0;
                    for (JDialog dialog : freeFloatDialogs) {
                        dialog.setVisible(false);
                        dialog.dispose();
                        dialog = null;
                    freeFloatDialogs.clear();
                    for (int i = 0; i < allScreens.size(); i++) {
                        JDialog dialog = createJDialog(allScreens.get(i));
                        freeFloatDialogs.add(dialog);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        dialog.setLocation(x, y);
                        dialog.setVisible(true);
            JMenuItem menuItem2 = new JMenuItem("Switch MDI");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = MDI_MODE;
                    remove(contentPanel);
                    add(desktopPane);
                    for (int i = 0; i < freeFloatDialogs.size(); i++) {
                        freeFloatDialogs.get(i).setVisible(false);
                        freeFloatDialogs.get(i).dispose();
                    freeFloatDialogs.clear();
    //                revalidate();
                    repaint();
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    index = 0;
                    for (int i = 0; i < allScreens.size(); i++) {
                        JInternalFrame frame = createInternalFram(allScreens.get(i));
                        desktopPane.add(frame);
                        mdiInternalFrm.add(frame);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        frame.setLocation(x, y);
                        frame.setVisible(true);
            menu.add(menuItem1);
            menu.add(menuItem2);
            return menu;
    public class TestTableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        JTable testTable = new JTable();
        MyTableModel tableModel1 = new MyTableModel(1);
        private boolean notRepaint = false;
        int start = 0;
        JScrollPane scrollPane = new JScrollPane();
        private Timer timmer = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(50);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        notRepaint = false;
                        TestTableScreen.this.update(index + "|" + val);
        public TestTableScreen(String title) {
            this.title = title;
            init();
            tableModel1.setTabelName(title);
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                List vals = tableModel1.getVector();
                if (vals.size() > index) {
                    vals.set(index, val[1]);
    //                 tableModel1.fireTableRowsUpdated(index, index);
                } else {
                    vals.add(val[1]);
    //                 tableModel1.fireTableRowsUpdated(vals.size() - 1, vals.size() - 1);
                tableModel1.fireTableDataChanged();
        public TableModel getTableModel() {
            return tableModel1;
        public void init() {
            testTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            testTable.setRowSelectionAllowed(true);
            this.testTable.setModel(tableModel1);
            int[] width = { 160, 80, 45, 98, 60, 88, 87, 88, 80, 70, 88, 80, 75, 87, 87, 41, 88, 82, 75, 68, 69 };
            TableColumnModel columnModel = testTable.getColumnModel();
            for (int i = 0; i < width.length; i++) {
                columnModel.getColumn(i).setPreferredWidth(width[i]);
            testTable.setRowHeight(20);
            tableModel1.fireTableDataChanged();
            this.setLayout(new BorderLayout());
            TableColumnModel columnMode2 = testTable.getColumnModel();
            int[] width2 = { 200 };
            for (int i = 0; i < width2.length; i++) {
                columnMode2.getColumn(i).setPreferredWidth(width2[i]);
            scrollPane.getViewport().add(testTable);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            this.add(scrollPane, BorderLayout.CENTER);
        class MyTableModel extends DefaultTableModel {
            public List list = new ArrayList();
            String titles[] = new String[] { "袨怓1", "袨怓2", "袨怓3", "袨怓4", "袨怓5", "袨怓6", "袨怓7", "袨怓8", "袨怓9", "袨怓10", "袨怓11",
                    "袨怓12", "袨怓13", "袨怓14", "袨怓15", "袨怓16", "袨怓17", "袨怓18", "袨怓19", "袨怓20", "袨怓21" };
            String tabelName = "";
            int type_head = 0;
            int type_data = 1;
            int type = 1;
            public MyTableModel(int type) {
                super();
                this.type = type;
                for (int i = 0; i < 50; i++) {
                    list.add(i);
            public void setTabelName(String name) {
                this.tabelName = name;
            public int getRowCount() {
                if (list != null) {
                    return list.size();
                return 0;
            public List getVector() {
                return list;
            public int getColumnCount() {
                if (type == 0) {
                    return 1;
                } else {
                    return titles.length;
            public String getColumnName(int c) {
                if (type == 0) {
                    return "head";
                } else {
                    return titles[c];
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            public Object getValueAt(int r, int c) {
                if (list.size() == 0) {
                    return null;
                switch (c) {
                default:
                    if (type == 0) {
                        return r + " " + c + "  test ";
                    } else {
                        return list.get(r) + "   " + c;
        public boolean isNotRepaint() {
            return notRepaint;
        public void setNotRepaint(boolean notRepaint) {
            this.notRepaint = notRepaint;
    public class TestPanel extends JPanel {
        protected String title = "";
        protected boolean needRepaint = false;
        protected boolean isFirstOpen = true;
        public String getTitle() {
            return title;
        public void setNeedRepaint(boolean flag) {
            this.needRepaint = flag;
        public boolean isNeedRepaint() {
            return needRepaint;
        public boolean isFirstOpen() {
            return isFirstOpen;
        public void setFirstOpen(boolean isFirstOpen) {
            this.isFirstOpen = isFirstOpen;
    public class TestJLableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        private JLabel[] allLables = new JLabel[20];
        private Timer timmer = new Timer(20, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(10);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        TestJLableScreen.this.setNeedRepaint(true);
                        TestJLableScreen.this.update(index + "|" + val);
        public TestJLableScreen(String title) {
            this.title = title;
            init();
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                allLables[index * 2 + 1].setText(val[1]);
        public void init() {
            this.setLayout(new GridLayout(10, 2));
            boolean flag = true;
            for (int i = 0; i < allLables.length; i++) {
                allLables[i] = new JLabel() {
                    // public void setText(String text) {
                    // super.setText(text);
                    // // System.out.println("  setText " + getTitle() + "   ; " + this.getName());
                    public void paint(Graphics g) {
                        super.paint(g);
                        // System.out.println("  paint " + getTitle() + "   ; " + this.getName());
                    // public void repaint() {
                    // super.repaint();
                    // System.out.println("  repaint " + getTitle() + "   ; " + this.getName());
                allLables[i].setName("" + i);
                if (i % 2 == 0) {
                    allLables[i].setText("Name " + i + "  : ");
                } else {
                    allLables[i].setOpaque(true);
                    if (flag) {
                        allLables[i].setBackground(Color.YELLOW);
                        flag = false;
                    } else {
                        allLables[i].setBackground(Color.CYAN);
                        flag = true;
                    allLables[i].setText(i * 8 + "");
            for (int i = 0; i < allLables.length; i++) {
                this.add(allLables[i]);
    public class CustomeInternalFrame extends JInternalFrame {
        protected TestPanel panel;
        public CustomeInternalFrame() {
            this("", false, false, false, false);
        public CustomeInternalFrame(String title) {
            this(title, false, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable) {
            this(title, resizable, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable) {
            this(title, resizable, closable, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) {
            this(title, resizable, closable, maximizable, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable,
                boolean iconifiable) {
            super(title, resizable, closable, maximizable, iconifiable);
        public TestPanel getPanel() {
            return panel;
        public void setPanel(TestPanel panel) {
            this.panel = panel;

    i had the same problem with buttons and it seemed that i overlayed my button with something else...
    so check that out first do you put something on that excact place???
    other problem i had was the VAJ one --> VisualAge for Java (terrible program)
    it does strange tricks even when you don't use the drawing tool...
    dunno 2 thoughts i had... check it out...
    SeJo

  • Design problem(split pane scrollpane Insets)

    hi,
    doing a exam simulator prgm
    design is like,
    Question (text area with scrollpane)
    Answers (checkbox inside panel with scrollpane)
    used split pane between qst and ans but big thick bar comes how to reduce size and it is not
    moving.
    used GridLayout for container and panel.
    PROBLEM is how to leave space qst textarea appears from very left edge of screen how to leave some space
    same prblm for checkbox they to appear extreme left on screen.

    Put those components in a JPanel overwriting the getInsets() method like this:
    JPanel cPane=new JPanel(){
        private final Insets _insets=new Insets(10,10,10,10);
        public Insets getInsets(){
            return _insets;
    };...should do the trick, take a look at the Insets class if you need information on how defining it...

  • Java code to get integer values from a gridLayout to put into an array?

    I am writing a tictactoe game for a programming class. I made a grid of 3x3 layout and it alternates between putting an X when clicked and an O. I need to know how to retrieve what button off the grid was picked so I can create an array to check for win conditions...Or how to access the rowIndex and columnIndex of a selected button on the grid
    Thanks in advance
    Edited by: ryAnOnFire on May 23, 2010 6:10 PM

    import java.awt.*;
    import java.awt.Container;
    import javax.swing.*;
    import java.awt.event.*;
    public class TicTacToe
         JFrame theWindow;
         JButton theButton;
         Container thePane;
         JTextField theText;
         MyListener theListener;
         public JButton[][] grid = new JButton[3][3];
         public TicTacToe()
              theWindow = new JFrame("Tic Tac Toe");
              theWindow.setSize(250, 250);
              String empty = " ";
             theListener = new MyListener();
              JFrame frame = new JFrame("TicTacToe");
              Container thePane = theWindow.getContentPane();
              thePane.setLayout(new GridLayout (3,3,5,5));
              for(int i = 0; i < 3; i++)
                   for(int j =0; j < 3; j++)
                        grid[i][j] = new JButton(empty);
                        thePane.add(grid[i][j]);
                        grid[i][j].addActionListener(theListener);
              JButton blankSpot = new JButton(empty);
              blankSpot.setFont(new Font("Papyrus", Font.BOLD, 35));
              theWindow.setVisible(true);
         public static void main(String[] args)
              new TicTacToe();
    class MyListener implements ActionListener
              String[][] spots1 = new String[3][3];
              String[][] spots2 = new String[3][3];
              static int playerTurnCounter = 0;
               JButton[][] grid; // !! added
                // !! added
                public MyListener(JButton[][] grid)
                     this.grid = grid;
              public void actionPerformed(ActionEvent e)
                   JButton jb = (JButton)e.getSource();
                   if(playerTurnCounter % 2 == 0)
                        jb.setText("X");
                        for(int i = 0; i < grid.length; i++)
                             for(int j = 0; j < grid.length; j++)
                                  spots1[i][j] = grid[i][j].getText();
                        if((spots1[0][0].equals("X")))
                             JOptionPane.showMessageDialog(null, "TICTACTOE", "WIN", JOptionPane.PLAIN_MESSAGE);
                        //The problem seems to be occuring in the above block commented area
                   else
                        jb.setText("O");
                   jb.setEnabled(false);
                   playerTurnCounter ++;
    Compiler Error:
    C:\Documents and Settings\HP_Administrator\My Documents\TicTacToe.java:24: cannot find symbol
    symbol  : constructor MyListener()
    location: class MyListener
             theListener = new MyListener();
                           ^
    1 error
    Tool completed with exit code 1
    I'm just going to let you ponder over this as I do too...
    I have no idea...my minimal experience with ActionListeners is doing me nothing for this one.
    Edited by: ryAnOnFire on May 23, 2010 8:12 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem with JScrollPane and Mouse Event in JDK 1.4

    The folowing code works fine with JDK 1.3. But not with JDK 1.4. It has got a JPanel(main panel) which hosts JScrollPane which hosts another JPanel (drawing Panel). If I remove(do not add) JScrollPane to the main Panel and ad drawing panel directly to the main panel, it works.
    Thanks.
    In order to replicate the exact scenario, I have modified Sun's tutorial ScrollDemo2.java
    * This code is based on an example provided by John Vella,
    * a tutorial reader.
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class ScrollDemo2 extends JPanel {
    private Dimension size; // indicates size taken up by graphics
    private Vector objects; // rectangular coordinates used to draw graphics
    private final Color colors[] = {
    Color.red, Color.blue, Color.green, Color.orange,
    Color.cyan, Color.magenta, Color.darkGray, Color.yellow};
    private final int color_n = colors.length;
    JPanel drawingArea;
    public ScrollDemo2() {
    setOpaque(true);
    size = new Dimension(0,0);
    objects = new Vector();
    //Set up the instructions.
    JLabel instructionsLeft = new JLabel(
    "Click left mouse button to place a circle.");
    JLabel instructionsRight = new JLabel(
    "Click right mouse button to clear drawing area.");
    JPanel instructionPanel = new JPanel(new GridLayout(0,1));
    instructionPanel.add(instructionsLeft);
    instructionPanel.add(instructionsRight);
    class MyScrollPane extends JScrollPane
    MyScrollPane(JPanel drawingArea)
    super(drawingArea);
    public void grabFocus()
    super.grabFocus();
    public void requestFocus()
    super.requestFocus();
    protected void processFocusEvent(FocusEvent e)
    if ( e.getID() == FocusEvent.FOCUS_GAINED )
    int i = 0;
    else
    if( e.getID() == FocusEvent.FOCUS_LOST )
    int i = 0;
    super.processFocusEvent(e);
    //Set up the drawing area.
    drawingArea = new JPanel() {
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Rectangle rect;
    for (int i = 0; i < objects.size(); i++) {
    rect = (Rectangle)objects.elementAt(i);
    g.setColor(colors[(i % color_n)]);
    g.fillOval(rect.x, rect.y, rect.width, rect.height);
    g.drawString("Hello",100,100);
    protected void processMouseEvent(MouseEvent pEvent)
    if(pEvent.getID() == pEvent.MOUSE_PRESSED)
    super.processMouseEvent(pEvent);
    else
    super.processMouseEvent(pEvent);
    drawingArea.setBackground(Color.LIGHT_GRAY);
    addMouseListener(new MyMouseListener());
    //Put the drawing area in a scroll pane.
    JScrollPane scroller = new MyScrollPane(drawingArea);
    scroller.setPreferredSize(new Dimension(200,200));
    setLayout(new BorderLayout());
    add(scroller, BorderLayout.CENTER);
    //If the above line is commented and the line bellow will be uncommented it works.
    //add(drawingArea, BorderLayout.CENTER);
    protected void processMouseEvent(MouseEvent pEvent)
    if(pEvent.getID() == pEvent.MOUSE_PRESSED)
    super.processMouseEvent(pEvent);
    else
    super.processMouseEvent(pEvent);
    class MyMouseListener extends MouseInputAdapter {
    final int W = 100;
    final int H = 100;
    public void mouseReleased(MouseEvent e) {
    boolean changed = false;
    if (SwingUtilities.isRightMouseButton(e)) {
    // This will clear the graphic objects.
    objects.removeAllElements();
    size.width=0;
    size.height=0;
    changed = true;
    } else {
    int x = e.getX() - W/2;
    int y = e.getY() - H/2;
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    Rectangle rect = new Rectangle(x, y, W, H);
    objects.addElement(rect);
    drawingArea.scrollRectToVisible(rect);
    int this_width = (x + W + 2);
    if (this_width > size.width)
    {size.width = this_width; changed=true;}
    int this_height = (y + H + 2);
    if (this_height > size.height)
    {size.height = this_height; changed=true;}
    if (changed) {
    //Update client's preferred size because
    //the area taken up by the graphics has
    //gotten larger or smaller (if cleared).
    drawingArea.setPreferredSize(size);
    //Let the scroll pane know to update itself
    //and its scrollbars.
    drawingArea.revalidate();
    drawingArea.repaint();
    public static void main (String args[]) {
    JFrame frame = new JFrame("ScrollDemo2");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    frame.setContentPane(new ScrollDemo2());
    frame.pack();
    frame.setVisible(true);

    I tried it . It didn't work.
    Thanks for the suggestionI've got it... I know that inside the paitComponet method you can't call setSize() in jdk1.4, but you could in previous versions... that has caused al lot of problems to me...
    Abraham

Maybe you are looking for

  • Maximum line size for OO ALV

    Hi, 1) What is the maximum line size for OO ALV? Or in the other way round, how is the maximum column size for OO ALV when i using the method below:   DATA: r_grid TYPE REF TO cl_salv_form_layout_grid.   CREATE OBJECT r_grid.   r_grid->create_text(  

  • Ok.. so if one can't EMAIL them.....

    and btw - I sent pages docs/folders, with imported figures and tables (thanks Yvan, for being so knowledgeable and sharing. I learned a lot from reading your replies) from Eudora to Eudora. They opened just fine although the names were somewhat garbl

  • Assign German keyboard layout to English input source?

    I have a MacBook Pro with a German keyboard layout (physical). If I change the input source to US English, Mac would not recoginze the German keyboard layout (i.e. it prints Z when I press Y). Is there a way to assign German keyboard layout to the US

  • Graph canvas size problem - missing rows

    Hi all, we have a simple horizontal bar graph based on a view, with just one total value pr. company showing. Problem is, if we set the canvas size too a small value, e.g. 400x400, then instead of resizing bars down so that all rows are shown, the gr

  • Charging related question

    Is it ok if I leave my iPhone connected to my Mac all the time and only let it discharge once a month (as recommended by Apple)...I browsed the forum but couldn't find a clear and definite answer to that... Thx!