0

panel code derive from oracle docs(https://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html). I want add a clear button to the same frame, So I created another panel: panel1. Now the situation is panel and panel1, the code will only show one of the panel. While running code, I want panel1 above the panel. Please tell me how to make it happen? The SpringLayout and SpringUtilities works very well.

SpringLayout

import javax.swing.*;
import java.awt.*;
public class SpringDemo1 {
    public static void createAndShowGUI() {
        JFrame springlayoutFrame = new JFrame("Springlayout Demo");
        JPanel panel = new JPanel(new SpringLayout());
        JPanel panel1 = new JPanel(new SpringLayout());
        JRadioButton jRadioButton = new JRadioButton("Clear");
        panel1.add(jRadioButton);
        int rows = 5;
        int cols = 10;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                int anInt = (int) Math.pow(r, c);
                JTextField jTextField1 = new JTextField(Integer.toString(anInt));
                panel.add(jTextField1);
            }
        }

        SpringUtilities.makeCompactGrid(panel, //parent
                rows, cols,
                10, 50,  //initX, initY
                3, 3); //xPad, yPad
        //SpringUtilities.makeCompactGrid(panel1,1,1,0,50,5,5);
        panel.setOpaque(true);
        panel1.setOpaque(true);
        //springlayoutFrame.setContentPane(panel);
        springlayoutFrame.getContentPane().add(panel);
        //springlayoutFrame.getContentPane().add(panel1);
        springlayoutFrame.pack();
        springlayoutFrame.setVisible(true);
        }
    }
jian
  • 4,119
  • 1
  • 17
  • 32
  • SpringUtilities.makeCompactGrid() method will sort out one Panel> But I want add more than one Panel to the frame. Then problem occurs. – jian Jun 22 '21 at 08:03
  • 1
    Use other layout managers. The Oracle tutorial, [A Visual Guide to Layout Managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) shows you seven other layout managers. – Gilbert Le Blanc Jun 22 '21 at 10:42
  • Make a third panel, with its own layout, and place `panel` and `panel1` in that third panel. – VGR Jun 22 '21 at 12:02
  • Don’t use `SpringLayout` for everything. In fact, none of the examples in that tutorial is a convincing one; all of them can be easier achieved with one of the other existing layout managers. You could get rid of the `panel1` entirely and just do `springlayoutFrame.getContentPane().add(jRadioButton, BorderLayout.PAGE_START);`. But why a radio button for a clear action? That sounds like a job for a simple `JButton`. – Holger Jun 22 '21 at 15:37

0 Answers0