Resize Jpanel and JtabbedPane

Hi All,
i implement a resize process on jpanel that include JtabbedPane inside.
it working fine except one thing.
when i resize my panel it work fine, until some point it start to shrink and get smaller.
i think it getting shrink because im getting to the end of my dialog.
i want to avoid this beheviour and let the tabbedpanel extend as much as possible:
this is my code:
package test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GraphicsConfiguration;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.Point;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class BaseMain extends JFrame {
     Point sp;
     int     jPanelStartHeight;
     int     jPanelStartWidth;
     int     jTabPaneStartHeight;
     int     jTabPaneStartWidth;
     Point offset;
     private static final long serialVersionUID = 1L;
     private JPanel jContentPane = null;
     private JPanel jPanel = null;
     private JTabbedPane jTabbedPane = null;
     private JPanel jPanel1 = null;
     private JTabbedPane jTabbedPane1 = null;
     private JPanel jPanel2 = null;
     private JTabbedPane jTabbedPane2 = null;
     public BaseMain() throws HeadlessException {
          // TODO Auto-generated constructor stub
          super();
          initialize();
     public BaseMain(GraphicsConfiguration arg0) {
          super(arg0);
          // TODO Auto-generated constructor stub
          initialize();
     public BaseMain(String arg0) throws HeadlessException {
          super(arg0);
          // TODO Auto-generated constructor stub
          initialize();
     public BaseMain(String arg0, GraphicsConfiguration arg1) {
          super(arg0, arg1);
          // TODO Auto-generated constructor stub
          initialize();
      * This method initializes jPanel     
      * @return javax.swing.JPanel     
     private JPanel getJPanel() {
          if (jPanel == null) {
               GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
               gridBagConstraints1.fill = GridBagConstraints.BOTH;
               gridBagConstraints1.weighty = 1.0;
               gridBagConstraints1.weightx = 1.0;
               gridBagConstraints1.gridheight=3;
               jPanel = new JPanel();
               jPanel.setLayout(new BorderLayout());
               jPanel.setBorder(BorderFactory.createLineBorder(Color.black, 2));
               jPanel.add(getJTabbedPane(),BorderLayout.SOUTH/* gridBagConstraints1*/);
               jPanel.addMouseListener(new java.awt.event.MouseAdapter() {
                    public void mousePressed(java.awt.event.MouseEvent e) {
                         System.out.println("mousePressed()"); // TODO Auto-generated Event stub mousePressed()
                         //original size
                         jPanelStartHeight = jPanel.getHeight();
                         jPanelStartWidth  = jPanel.getWidth();
                         jTabPaneStartHeight = jTabbedPane.getHeight();
                         jTabPaneStartWidth  = jTabbedPane.getWidth();
                          offset = SwingUtilities.convertPoint(e.getComponent(),e.getPoint(),jPanel);
               jPanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                    public void mouseDragged(java.awt.event.MouseEvent e) {
                         System.out.println("mouseDragged()"); // TODO Auto-generated Event stub mouseDragged()
                         Point p = SwingUtilities.convertPoint(e.getComponent(),e.getPoint(), jContentPane);
                         jPanel.setSize(jPanelStartWidth,p.y+jPanelStartHeight);
                         jTabbedPane.setSize(jTabPaneStartWidth,p.y+jTabPaneStartHeight);
                         jPanel.setLocation(0/*p.x-offset.x*/,p.y-offset.y);
          return jPanel;
      * This method initializes jTabbedPane     
      * @return javax.swing.JTabbedPane     
     private JTabbedPane getJTabbedPane() {
          if (jTabbedPane == null) {
               jTabbedPane = new JTabbedPane();
               jTabbedPane.addTab(null, null, getJPanel1(), null);
               jTabbedPane.addTab(null, null, getJPanel2(), null);
          return jTabbedPane;
      * This method initializes jPanel1     
      * @return javax.swing.JPanel     
     private JPanel getJPanel1() {
          if (jPanel1 == null) {
               GridBagConstraints gridBagConstraints = new GridBagConstraints();
               gridBagConstraints.fill = GridBagConstraints.BOTH;
               gridBagConstraints.weighty = 1.0;
               gridBagConstraints.weightx = 1.0;
               jPanel1 = new JPanel();
               jPanel1.setLayout(new GridBagLayout());
               jPanel1.add(getJTabbedPane1(), gridBagConstraints);
          return jPanel1;
      * This method initializes jTabbedPane1     
      * @return javax.swing.JTabbedPane     
     private JTabbedPane getJTabbedPane1() {
          if (jTabbedPane1 == null) {
               jTabbedPane1 = new JTabbedPane();
          return jTabbedPane1;
      * This method initializes jPanel2     
      * @return javax.swing.JPanel     
     private JPanel getJPanel2() {
          if (jPanel2 == null) {
               GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
               gridBagConstraints2.fill = GridBagConstraints.BOTH;
               gridBagConstraints2.weighty = 1.0;
               gridBagConstraints2.weightx = 1.0;
               jPanel2 = new JPanel();
               jPanel2.setLayout(new GridBagLayout());
               jPanel2.add(getJTabbedPane2(), gridBagConstraints2);
          return jPanel2;
      * This method initializes jTabbedPane2     
      * @return javax.swing.JTabbedPane     
     private JTabbedPane getJTabbedPane2() {
          if (jTabbedPane2 == null) {
               jTabbedPane2 = new JTabbedPane();
          return jTabbedPane2;
      * @param args
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    BaseMain thisClass = new BaseMain();
                    thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    thisClass.setVisible(true);
      * This method initializes this
      * @return void
     private void initialize() {
          this.setSize(300, 200);
          this.setContentPane(getJContentPane());
          this.setTitle("JFrame");
      * This method initializes jContentPane
      * @return javax.swing.JPanel
     private JPanel getJContentPane() {
          if (jContentPane == null) {
               jContentPane = new JPanel();
               jContentPane.setLayout(new BorderLayout());
               jContentPane.add(getJPanel(), BorderLayout.SOUTH);
          return jContentPane;
}

hey gabi,
i tried your code and it works just fine.... there is no shrinking or any resizing problem?! i don't know... maybe i just don't get it? so maybe u could describe your problem a little more?!
:)

Similar Messages

  • About JPanel and JTabbedPane

    I have a JPanel and i want to know how any tab buttons it contain.
    We have a method in JTabbedPane to find it out ,so how can i type cast the JPanel to JTabbedPane.
    Thanks

    JTabbedPane does not extend JPanel, so you can't cast JPanel to JTabbedPane.
    A JPanel does not contain any tabs.
    I think you might need to rephrase the question.

  • Drawning text/images in a JPanel and then resizing/moving it with the mouse

    Hello ebverybody!
    I need to be able to draw some text objects in a JPanel and then resize/move it with the mouse... How could I do that!? Same for some images loaded from jpg files...
    Should I just paint the text and then repaint when the mouse selects it? How to do this selection?! Or should use something like a jLabel and then change it`s font metrics?!
    I need to keep track of the upper left corner of the text/image, as well as the width/height of it. This will be recorded in a file.
    The text/images need to smoothly move around the panel as the mouse drags when selectin an entity.. not just "click the entity, then click another point and the entity appears there as if by magic...":)
    Please, tell the best way to do that!
    Thanks everybody!
    Message was edited by:
    cassio.marques

    I know what you mean! This happened to me as well!
    And one thing that I found useful is, if you want to directly select a layer without selecting from the layers pallete and without having autoselect enabled, just hold Ctrl and click on in directly in the image. This saved me a lot of time!

  • Resizing JFrames and JPanels !!!

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

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

  • How to dynamically resize JPanel at runtime??

    Hello Sir:
    I met a problem, I need to resize a small JPanel called panel within a main Control JPanel (with null Layout) if I click the mouse then I can Drag and Resize this small JPanel Border to the size I need at runtime, I know I can use panel.setSize() or panel.setPreferredSize() methods at design time,
    But I have no idea how to do it even I search this famous fourm,
    How to dynamically resize JPanel at runtime??
    Can any guru throw some light or good example??
    Thanks

    Why are you using a null layout? Wouldn't having a layout manager help you in this situation?

  • JTable in JPanel in JTabbedPane in JScrollPane in JSplitPane problem

    I have a JSplitPane with a divider in the center; of which the top is a JPanel and the bottom is a JScrollPane that contains a JTabbedPane, for which each tab contains a JPanel which contains a JTable.
    When I move the divider up, so that it now takes up 75% of the JSplitPane, the JScrollPane and the JTabbedPane expand with the JSplitPane, but the JPanel that contains the JTable remains the same size that it had at the beginning.
    What I would like to see is more rows of the JTable as I move the divider to give the JScrollPane more room.
    Is there an easy way to keep all of the J components sizes in sync as the JSplitPane gets larger or smaller ? (JDK 1.3.1)

    Hi,
    The JPanels which you have inside each tab of the JTabbedPanes should have BorderLayout and the JScrollPanes which hold the JTables should be added with the BorderLayout.CENTER constraint. This will make sure that the JScrollPanes that contain the JTables occupy as much space as possible.
    Hope this helps,
    Ranga.

  • Making a customable resizable JPanel, but it only works in certain L&F

    Hi,
    I have created the following resizable JPanel (so that I can set a minimum size it can be dragged to).
    However, I need it to work under the system L&F, which is XP, but it wont work.
    The code is below. if you run it the first time, and try to resize the dialog to a small value, you will see it shrinks in size, to a certain point.
    then if you comment out the 2 lines i specified, and run it again, it wont. Anyone have any ideas? is this a known bug?
    import javax.swing.*;
    import java.awt.event.ComponentListener;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.*;
    public class ResizeTest extends JDialog {
         public ResizeTest(JFrame owner) {
              super(owner);
              this.addComponentListener(resizeListener);
              /* comment out the following 2 lines */
              setUndecorated(true);                  
            getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
         private ComponentListener resizeListener = new ComponentListener() {
              public void componentHidden( ComponentEvent i_e ) { }
              public void componentMoved( ComponentEvent i_e ) { }
              public void componentResized( ComponentEvent i_e ) {
                   int width = ResizeTest.this.getWidth();
                   int height = ResizeTest.this.getHeight();   
                  if( width < 50 ) { width = 50; }
                   if( height < 50 ) { height = 50; }
                   ResizeTest.this.setSize( width, height );
             public void componentShown( ComponentEvent i_e ) { }
         private static void test() {
              final JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JButton launchButton = new JButton("showDialog");
              frame.setContentPane(launchButton);
              final ResizeTest testDialog = new ResizeTest(frame);
              testDialog.setMinimumSize(new Dimension(300, 300));
              testDialog.setSize(500, 500);
              testDialog.setPreferredSize(new Dimension(500, 500));
              launchButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        testDialog.pack();
                        testDialog.setVisible(true);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.setVisible(true);
         public static void main(String[] args) {
              test();
    }

    okay... I see what the problem is.
    1) With those lines uncommented: The L&F is handling the window decorations. Because of this, it's basically a JWindow with custom painting and mouse handling. When you resize, it's constantly calling setSize, which constantly firing events, so your minimum sizing works as you expect.
    2) With those lines commented: The OS is handling the window decorations. Because of this, there are 2 caveats:
    a) There is a minimum width of the window of what looks like about 120-130 pixels. So you can't go any smaller then that for width. And for height, no smaller then the titlebar and lower border.
    b) It only fires the component events when the mouse is released, cuz that's how the undelying native windows deal with it... or at least with Java.
    For #1 above, there's still a minimum size for the L&F decorated windows. But this is related to what content is showing in the titlebar. Which in the case of the decorations showing, is smaller then what your were defining as a minimum.
    So, basically, it's not a bug. It's just the way it is. It's always been like this.

  • JScrollPane for pane and JTabbedPane and Graphics

    Sort of have two topics with same problem.
    I have a set of Panels. I get a stream of jpegs which I have to decode to the fly.
    There are seperate video feeds in the stream and I have to read jpeg data to see which image goes where.
    I was trying to see if I could have a larger image in smaller area. this is why I tried to draw to panel inside a scrollpane.
    One: I tried to put a JPanel into JScrollPane and tried to draw an image to panel with Graphics g. No Scrollability and even when scroll bars are made to stay on permanently, they get overwritten.
    g=panel.getGraphics();
    if(isVisible()) g.drawImage(image,0,0,320,240,Color.BLUE,null);
    two: When putting the pane with the drawn images into toplevel pane into JtabbedPane. I can turn off the drawing of images with a check to isVisible(). When they are not in top level pane isVisible() does not work and the images get drawn over the other tabbed panes.
    BTW everything is swing. JPanel,JScrollPane,JTabbedPane.

    No Scrollability and even when scroll bars are made to stay on permanently,First of all the scrollbars will only appear when the preferred size of the panel is greater than the size of the scrollpane.
    A think a better design for updating the image is to extend JPanel and create a setImage method. The set image method would set the preferred size of the panel and then invoke repaint() on the panel. You would then also need to override the paintComponent(..) method to do the actual drawing of the image. Then when the image changes you just use the new setImage(..) method.

  • Wait for resizing JPanel

    nice day,
    during rezize JFrame simultaneously changing the size of JFrame Childs, how to stop, pause or wait for that and resize JFrame Childs just one time
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.border.EmptyBorder;
    public class PaintPanels extends JFrame {
        private static final long serialVersionUID = 1L;
        private final JPanel fatherPanel = new JPanel();
        private SomePanel centerPanel;
        private SomePanel northPanel;
        private SomePanel southPanel;
        public void makeUI() {
            centerPanel = new SomePanel();
            northPanel = new SomePanel();
            southPanel = new SomePanel();
            centerPanel.setName("centerPanel");
            northPanel.setName("northPanel");
            southPanel.setName("southPanel");
            northPanel.setPreferredSize(new Dimension(1020, 170));
            centerPanel.setPreferredSize(new Dimension(1020, 300));
            southPanel.setPreferredSize(new Dimension(1020, 170));
            fatherPanel.setLayout(new BorderLayout(5, 5));
            fatherPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
            fatherPanel.add(northPanel, BorderLayout.NORTH);
            fatherPanel.add(centerPanel, BorderLayout.CENTER);
            fatherPanel.add(southPanel, BorderLayout.SOUTH);
            setLayout(new BorderLayout(5, 5));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            add(fatherPanel, BorderLayout.CENTER);
            pack();
            setVisible(true);
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new PaintPanels().makeUI();
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class SomePanel extends JPanel {
        private static final long serialVersionUID = 1L;
        private GradientPanel titlePanel;
        protected JLabel titleLabel;
        int borderOffset = 2;
        public SomePanel() {
            setLayout(new BorderLayout(5,5));
            setBorder(BorderFactory.createLineBorder(Color.gray, 1));
            addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Component comp = e.getComponent();
                    String compName = comp.getName();
                    System.out.print("Mouse click from " + compName + "\n");
                @Override
                public void mousePressed(MouseEvent e) {
                @Override
                public void mouseReleased(MouseEvent e) {
                @Override
                public void mouseEntered(MouseEvent e) {
                @Override
                public void mouseExited(MouseEvent e) {
            titleLabel = new JLabel("  Welcome World  ", JLabel.LEADING);
            titleLabel.setForeground(Color.darkGray);
            titlePanel = new GradientPanel(Color.black);
            titlePanel.setLayout(new BorderLayout());
            titlePanel.add(titleLabel, BorderLayout.WEST);
            titlePanel.setBorder(BorderFactory.createEmptyBorder(borderOffset, 4, borderOffset, 1));
            titlePanel.setBorder(BorderFactory.createLineBorder(Color.lightGray));
            titlePanel.setMinimumSize(new Dimension(300, 25));
            titlePanel.setPreferredSize(new Dimension(800, 25));
            titlePanel.setMaximumSize(new Dimension(1200, 25));
            add(titlePanel, BorderLayout.NORTH);
    import java.awt.Color;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import javax.swing.JPanel;
    class GradientPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        public GradientPanel(Color background) {
            setBackground(background);
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (isOpaque()) {// Color controlColor = UIManager.getColor("control");
                //Color background = new Color(44, 61, 146);
                //Color controlColor = new Color(168, 204, 241);
                Color background = new Color(168, 210, 241);
                Color controlColor = new Color(230, 240, 230);
                int width = getWidth();
                int height = getHeight();
                Graphics2D g2 = (Graphics2D) g;
                Paint oldPaint = g2.getPaint();
                g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
                //g2.setPaint(new GradientPaint(0, 0, getBackground(), width, 0, controlColor));
                g2.fillRect(0, 0, width, height);
                g2.setPaint(oldPaint);
    }

    nice day,
    could you hepl me with some definitions, still I can't to define gap for first and last of JLabel (matrix), is there some hack for GridBagLayout,
    hmmm, interesting that if I replace South JPanel and put there JPanet that contains only JButtons, then that's/just only this one (JPanel) doesn't any problems with synchronizations for repaint with JFrame,
    result is: resize isn't smooth, Border jump, resize breaking,
    already at a fraction of JComponents that I would like to display,
    I certainly know that the reason is the LCD display, where its native resolution makes a huge problem with the edge of Border and FontSize, 'glass screen' doesn't suffering from similar diseases,
    so there my question is how to stop the refresh, resize JPanels with its parents, therefore wait until the resize event ends on JFrame
    import java.awt.*;
    import javax.swing.*;
    public class ChildPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        public ChildPanel() {
            JLabel hidelLabel;
            JLabel firstLabel;
            JTextField firstText;
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            for (int k = 0; k < 50; k++) {
                hidelLabel = new JLabel("     ");
                //hidelLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.weightx = 0.5;
                gbc.weighty = 0.5;
                gbc.gridx = k;
                gbc.gridy = 0;
                add(hidelLabel, gbc);
            for (int k = 0; k < 5; k++) {
                firstLabel = new JLabel("Testing Label : ", SwingConstants.RIGHT);
                firstLabel.setFont(new Font("Serif", Font.BOLD, 20));
                firstLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                //gbc.ipady = 0;       //reset to default
                //gbc.weighty = 1.0;   //request any extra vertical space
                //gbc.anchor = GridBagConstraints.PAGE_END; //bottom of space
                gbc.insets = new Insets(0, 0, 5, 0);  //top padding
                gbc.gridx = 0;       //aligned with JLabel 0
                gbc.gridwidth = 8;   //8 columns wide
                gbc.gridy = k + 1;
                add(firstLabel, gbc);
            for (int k = 0; k < 5; k++) {
                firstText = new JTextField("Testing TextField");
                firstText.setFont(new Font("Serif", Font.BOLD, 20));
                firstText.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.insets = new Insets(0, 0, 5, 0);
                gbc.gridx = 9;
                gbc.gridwidth = k + 8;
                gbc.gridy = k + 1;
                add(firstText, gbc);
            for (int k = 0; k < 5; k++) {
                firstLabel = new JLabel("Testing Label : ", SwingConstants.RIGHT);
                firstLabel.setFont(new Font("Serif", Font.BOLD, 20));
                firstLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.insets = new Insets(0, 0, 5, 0);
                gbc.gridx = 20 + k;
                gbc.gridwidth = 8;
                gbc.gridy = k + 1;
                add(firstLabel, gbc);
            for (int k = 0; k < 5; k++) {
                firstText = new JTextField("Testing TextField");
                firstText.setFont(new Font("Serif", Font.BOLD, 20));
                firstText.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.insets = new Insets(0, 0, 5, 0);
                gbc.gridx = 29 + k;
                gbc.gridwidth = 21 - k;
                gbc.gridy = k + 1;
                add(firstText, gbc);
    import java.awt.*;
    import javax.swing.JPanel;
    class GradientPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        public GradientPanel(Color background) {
            setBackground(background);
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (isOpaque()) {
                Color background = new Color(168, 210, 241);
                Color controlColor = new Color(230, 240, 230);
                int width = getWidth();
                int height = getHeight();
                Graphics2D g2 = (Graphics2D) g;
                Paint oldPaint = g2.getPaint();
                g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
                g2.fillRect(0, 0, width, height);
                g2.setPaint(oldPaint);
    }

  • GridBagLayout not working inside jpanel in jtabbedpane

    Have any of you experienced similar behaviour before? Any ideas what could cause this? It seems that any other layout is working except the gridbaglayout. All the components I add will be in the center of the jpanel and on top of each other no matter what gridbagconstraints I use.

    import java.awt.*;
    import javax.swing.*;
    public class GridBag_Demo extends JFrame {
        public GridBag_Demo() {
            initComponents();
        private void initComponents() {
            GridBagConstraints gridBagConstraints;
            tabbedpane = new JTabbedPane();
            panel = new JPanel();
            button1 = new JButton();
            button2 = new JButton();
            button3 = new JButton();
            label1 = new JLabel();
            label2 = new JLabel();
            label3 = new JLabel();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("GridBag Demo");
            panel.setLayout(new GridBagLayout());
            button1.setText("button1");
            gridBagConstraints = new GridBagConstraints();
            gridBagConstraints.weightx = 1.0;
            gridBagConstraints.weighty = 1.0;
            panel.add(button1, gridBagConstraints);
            button2.setText("button2");
            gridBagConstraints.gridy = 1;
            panel.add(button2, gridBagConstraints);
            button3.setText("button3");
            gridBagConstraints.gridy = 2;
            panel.add(button3, gridBagConstraints);
            label1.setText("label1");
            gridBagConstraints.gridx = 2;
            gridBagConstraints.gridy = 0;
            panel.add(label1, gridBagConstraints);
            label2.setText("label2");
            gridBagConstraints.gridy = 1;
            panel.add(label2, gridBagConstraints);
            label3.setText("label2");
            gridBagConstraints.gridy = 2;
            panel.add(label3, gridBagConstraints);
            tabbedpane.addTab("tab1", panel);
            getContentPane().add(tabbedpane, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
        public static void main(String args[]) {
            new GridBag_Demo().setVisible(true);
        private JButton button1;
        private JButton button2;
        private JButton button3;
        private JLabel label1;
        private JLabel label2;
        private JLabel label3;
        private JPanel panel;
        private JTabbedPane tabbedpane;
    }

  • Painting JPanels and graphics

    I have a JPanel into which want to display boxes of data connected by lines. The boxes are JPanels (with a ScrollPane and JList) and the lines simply Graphics2D objects. I have overridden the paint(g) method of the enclosing panel to call super.paint(g) followed by my graphics calls. This works fine on start-up and repaint (from maximizing), but when I resize the main panel, the middle of the panel doesn't show the graphics (the inner panels display fine). I think I see the graphics being drawn then erased, but I'm not sure. Reviewing the Painting in AWT and Swing articles hasn't helped. I've tried various versions of paintComponent(), paintChildren(), etc. as alternatives, but the problem remains (or I never see the graphics at all). This seems like a timing and clipping problem but I can't figure it out. Can anyone explain what resize is doing that is different than a normal paint? How should one combine JPanels and graphics?Thanks.

    Unfortunately, overriding paintComponent() causes the graphics to be completely over-written for some reason. The problem is apparently when the inner Panels are written (I guess by paintChildren()). I'm following the directions in Doing Without a Layout Manager in the Java Tutorial: setting the outer JPanel's layout to null, explicitly setting the bounds of the inner JPanels and overwriting paint() with super.paint() (which paints the inner panels correctly) followed by my graphics code. All is well until I resize.
    Now the Doing Without a Layout Manager page states "However, creating containers with absolutely positioned containers can cause problems if the window containing the container is resized." Guess they're right ;-) Anyone know how to get around this problem?

  • Canvas3D JPanel and Behavior

    Hello,
    I am a student’s geomatic and I do my memory on 3D object implementation in a data base.
    To do that, I have a 3D graphic interface. I use Java 3D and Swing.
    Now, my program load only 3D points. There are 3 parts:
    - a 3D viewer,
    - a table,
    - buttons for the actions.
    I would like to get the 3D mouse coordinates in my 3D world.
    I succeed in a first program’s version. There were two windows JFrame, one included the Canevas3D and the other the table with the buttons.
    For the mouse’s action, I modify this source code :
    http://deven3d.free.fr/telechargements/fichiers/java3d/chap07/SimpleBehavior/SimpleBehavior.java
    Then, I put the Canevas3D in a JPanel (and neither in a separate window). And I add this JPanel to the JFram (those contain the table and the buttons for the actions).
    And after that my class Behavior don’t work.
    I think it’s due to my ActionListener (it’s use to catch the buttons’ press) who intercept the mouse action.
    This is my class Behavior :
    import java.awt.AWTEvent;
    import java.awt.Point;
    import java.awt.event.*;
    import java.util.Enumeration;
    import javax.media.j3d.*;
    import javax.vecmath.Point3d;
    public class InterGraph3d extends Behavior {
           // Condition qui va declencher le stimulus
           private WakeupCondition wakeupCondition =
                new WakeupOnAWTEvent(MouseEvent.MOUSE_PRESSED);
           private Canvas3D caneva;
           InterGraph3d (Canvas3D cane){
                   this.caneva = cane;
         public void initialize() {
             this.wakeupOn(wakeupCondition);
         public void processStimulus(Enumeration criteria) {
              WakeupCriterion critere;
             AWTEvent[] events;
             MouseEvent evt;
             // On boucle sur les critères ayant declenche le comportement
             while (criteria.hasMoreElements()) {
               // On recupere le premier critere de l'enumeration
               critere = (WakeupCriterion)criteria.nextElement();
               // On ne traite que les criteres correspondant a un evenement AWT
               if (critere instanceof WakeupOnAWTEvent) {
                 // On récupère le tableau des evements AWT correspondant au critere
                 events = ((WakeupOnAWTEvent)critere).getAWTEvent();
                 if (events.length > 0) {
                   // On récupère l'événement
                   evt = (MouseEvent)events[events.length-1];
                   // Traitement au cas par cas selon la touche pressée
                   switch(evt.getButton()) {
                   // Obtenir les coordonnées 3D du point cliqué
                     case MouseEvent.BUTTON1: // clic gauche
                     // pour avoir les coordonnées du point cliqué dans l'univers en 3D
                     // on déclare un point 3D
                     Point3d ptSourie = new Point3d();
                     // on utilise la fonction pour avoir les coordonnées de la sourie en 3D.
                     ptSourie = obtenirPointSourieCaneva(caneva, evt.getPoint());
                     // ici faire une liaison avec l'interface graphique
                     System.out.println("Coor sourie");
                       System.out.println(ptSourie.x);
                       System.out.println(ptSourie.y);
                       System.out.println(ptSourie.z);
                       break;
              // Une fois le stimulus traite, on réinitialise le comportement
             this.wakeupOn(wakeupCondition);
         // fonction pour récupérer les coordonnées de la sourie dans le
         public Point3d obtenirPointSourieCaneva(Canvas3D myCanvas, Point clickPos)
              Point3d mousePos = new Point3d();
              //pixel value in image-plate coordinates and copies that value into the object provided.
             myCanvas.getPixelLocationInImagePlate(clickPos.x, clickPos.y, mousePos);
              //This block of code converts our image plate coordinates out to virtual world coordinates
              Transform3D motion = new Transform3D();
              myCanvas.getImagePlateToVworld(motion);
              //We do this convertion the mouse position.
              motion.transform(mousePos);
              return mousePos;
    }

    The ScrollDemo uses the column and row header as well as the corner to create the rulerIt adds a component to the colum and row header and the corner. That component may or may not be a JPanel, or JComponent which they have used for custom painting.
    Can I change the ScrollDemo to use a JPanel instead?Makes no sense. There are 9 areas to add a Component. Any of those 9 areas can hold a JPanel.
    Does a JPanel provide the same elements A panel uses a LayoutManager to place components. Check the scroll pane source code to see what LayoutManager it uses.

  • How to resize JPanel at Runtime ??

    Hi,
    Our Project me t a problem as below, we hope to resize JPanel at Runtime , not at design time, ie, when we first click the button called "Move JPanel" , then we click the JPanel, then we can drag it around within main panel, but we hope to resize the size of this JPanel when we point to the border of this JPanel then drag its border to zoom in or zoom out this JPanel.
    Please advice how to do that??
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.LineBorder;
    import javax.swing.event.*;
    public class ResizeJPanels extends JPanel
        protected JLabel label1, label2, label3, label4, labeltmp;
        protected JLabel[] labels;
        protected JPanel[] panels;
        protected JPanel selectedJPanel;
        protected JButton btn  = new JButton("Move JPanel");
        int cx, cy;
        protected Vector order = new Vector();      
         public static void main(String[] args)
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ResizeJPanels().GroupJLabels());
            f.setSize(600,700);
            f.setLocation(200,200);
            f.setVisible(true);
         private MouseListener ml = new MouseAdapter() {  
              public void mousePressed(MouseEvent e) {   
                   Point p = e.getPoint();      
                   JPanel jp = new JPanel();
                   jp.setLayout(null);
                   Component[] c = ((JPanel)e.getSource()).getComponents();
                   System.out.println("c.length = " + c.length);      
                   for(int j = 0; j < c.length; j++) {        
                        if(c[j].getBounds().contains(p)) {     
                             if(selectedJPanel != null && selectedJPanel != (JPanel)c[j])
                                  selectedJPanel.setBorder(BorderFactory.createEtchedBorder());
                             selectedJPanel = (JPanel)c[j];            
                             selectedJPanel.setBorder(BorderFactory.createLineBorder(Color.green));
                             break;             
                        add(jp);
                        revalidate();
    public JPanel GroupJLabels ()
              setLayout(null);
            addLabels();
            label1.setBounds( 125,  150, 125, 25);
            label2.setBounds(425,  150, 125, 25);
            label3.setBounds( 125, 575, 125, 25);
            label4.setBounds(425, 575, 125, 25);
            //add(btn);
            btn.setBounds(10, 5, 205, 25);
                add(btn);
           determineCenterOfComponents();
            ComponentMover mover = new ComponentMover();
             ActionListener lst = new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     ComponentMover mover = new ComponentMover();
                           addMouseListener(mover);
                           addMouseMotionListener(mover);
              btn.addActionListener(lst);
              addMouseListener(ml); 
              return this;
        public void paintComponent(final Graphics g)
             super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
             Point[] p;
            g2.setStroke(new BasicStroke(4f));
           for(int i = 0 ; i < order.size()-1; i++) {
                JPanel l1 = (JPanel)order.elementAt(i);
                JPanel l2 = (JPanel)order.elementAt(i+1);
                p = getCenterPoints(l1, l2);
                g2.setColor(Color.black);
               // g2.draw(new Line2D.Double(p[0], p[1]));            
        private Point[] getCenterPoints(Component c1, Component c2)
            Point
                p1 = new Point(),
                p2 = new Point();
            Rectangle
                r1 = c1.getBounds(),
                r2 = c2.getBounds();
                 p1.x = r1.x + r1.width/2;
                 p1.y = r1.y + r1.height/2;
                 p2.x = r2.x + r2.width/2;
                 p2.y = r2.y + r2.height/2;
            return new Point[] {p1, p2};
        private void determineCenterOfComponents()
            int
                xMin = Integer.MAX_VALUE,
                yMin = Integer.MAX_VALUE,
                xMax = 0,
                yMax = 0;
            for(int i = 0; i < labels.length; i++)
                Rectangle r = labels.getBounds();
    if(r.x < xMin)
    xMin = r.x;
    if(r.y < yMin)
    yMin = r.y;
    if(r.x + r.width > xMax)
    xMax = r.x + r.width;
    if(r.y + r.height > yMax)
    yMax = r.y + r.height;
    cx = xMin + (xMax - xMin)/2;
    cy = yMin + (yMax - yMin)/2;
    private class ComponentMover extends MouseInputAdapter
    Point offsetP = new Point();
    boolean dragging;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    for(int i = 0; i < panels.length; i++)
    Rectangle r = panels[i].getBounds();
    if(r.contains(p))
    selectedJPanel = panels[i];
    order.addElement(panels[i]);
    offsetP.x = p.x - r.x;
    offsetP.y = p.y - r.y;
    dragging = true;
    repaint(); //added
    break;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    Rectangle r = selectedJPanel.getBounds();
    r.x = e.getX() - offsetP.x;
    r.y = e.getY() - offsetP.y;
    selectedJPanel.setBounds(r.x, r.y, r.width, r.height);
    //determineCenterOfComponents();
    repaint();
    private void addLabels()
    label1 = new JLabel("Label 1");
    label2 = new JLabel("Label 2");
    label3 = new JLabel("Label 3");
    label4 = new JLabel("Label 4");
    labels = new JLabel[] {
    label1, label2, label3, label4
    JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
    jl.setBackground(Color.green);
    jl.setOpaque(true);
              jl.setFont(new Font("Helvetica", Font.BOLD, 18));
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    panels = new JPanel[]{jp};
              jp.setBorder(new LineBorder(Color.black, 3, false));
    jp.setPreferredSize(new Dimension(400,200));
    jp.add(jl, BorderLayout.NORTH);
    for(int i = 0; i < labels.length; i++)
    labels[i].setHorizontalAlignment(SwingConstants.CENTER);
    labels[i].setBorder(BorderFactory.createEtchedBorder());
    jp.add(labels[i], BorderLayout.CENTER);
    jp.setBounds(100, 100, 400,200);
    add(jp);

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.MouseInputAdapter;
    public class Resizing extends JPanel {
        public Resizing() {
            super(null);
            addPanel();
            PanelControlAdapter control = new PanelControlAdapter(this);
            addMouseListener(control);
            addMouseMotionListener(control);
        private void addPanel() {
            JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
            jl.setBackground(Color.green);
            jl.setOpaque(true);
            jl.setFont(new Font("Helvetica", Font.BOLD, 18));
            JPanel jp = new JPanel();
            jp.setLayout(new BorderLayout());
            jp.setBorder(new LineBorder(Color.black, 3, false));
            jp.add(jl, BorderLayout.NORTH);
            jp.setBounds(50,50,400,200);
            add(jp);
        public static void main(String[] args) {
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Resizing());
            f.setSize(500,400);
            f.setLocation(100,100);
            f.setVisible(true);
    class PanelControlAdapter extends MouseInputAdapter {
        Resizing host;
        Component selectedComponent;
        LineBorder black;
        LineBorder green;
        Point offset = new Point();
        Point start = new Point();
        boolean dragging = false;
        boolean resizing = false;
        public PanelControlAdapter(Resizing r) {
            host = r;
            black = new LineBorder(Color.black, 3, false);
            green = new LineBorder(Color.green, 3, false);
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            boolean hovering = false;
            Component c = host.getComponent(0);
            Rectangle r = c.getBounds();
            if(r.contains(p)) {
                hovering = true;
                if(selectedComponent != c) {
                    if(selectedComponent != null)  // reset
                        ((JComponent)selectedComponent).setBorder(black);
                    selectedComponent = c;
                    ((JComponent)selectedComponent).setBorder(green);
                if(overBorder(p))
                    setCursor(p);
                else if(selectedComponent.getCursor() != Cursor.getDefaultCursor())
                    selectedComponent.setCursor(Cursor.getDefaultCursor());
            if(!hovering && selectedComponent != null) {
                ((JComponent)selectedComponent).setBorder(black);
                selectedComponent = null;
        private boolean overBorder(Point p) {
            Rectangle r = selectedComponent.getBounds();
            JComponent target = (JComponent)selectedComponent;
            Insets insets = target.getBorder().getBorderInsets(target);
            // Assume uniform border insets.
            r.grow(-insets.left, -insets.top);
            return !r.contains(p);
        private void setCursor(Point p) {
            JComponent target = (JComponent)selectedComponent;
            AbstractBorder border = (AbstractBorder)target.getBorder();
            Rectangle r = target.getBounds();
            Rectangle ir = border.getInteriorRectangle(target, r.x, r.y, r.width, r.height);
            int outcode = ir.outcode(p.x, p.y);
            Cursor cursor;
            switch(outcode) {
                case Rectangle.OUT_TOP:
                    cursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_TOP + Rectangle.OUT_LEFT:
                    cursor = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_LEFT:
                    cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_LEFT + Rectangle.OUT_BOTTOM:
                    cursor = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_BOTTOM:
                    cursor = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_BOTTOM + Rectangle.OUT_RIGHT:
                    cursor = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_RIGHT:
                    cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_RIGHT + Rectangle.OUT_TOP:
                    cursor = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);
                    break;
                default:
                    cursor = Cursor.getDefaultCursor();
            selectedComponent.setCursor(cursor);
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(selectedComponent != null) {
                Rectangle r = selectedComponent.getBounds();
                if(selectedComponent.getCursor() == Cursor.getDefaultCursor()) {
                    offset.x = p.x - r.x;
                    offset.y = p.y - r.y;
                    dragging = true;
                } else {
                    start = p;
                    resizing = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
            resizing = false;
        public void mouseDragged(MouseEvent e) {
            Point p = e.getPoint();
            if(dragging || resizing) {
                Rectangle r = selectedComponent.getBounds();
                if(dragging) {
                    r.x = p.x - offset.x;
                    r.y = p.y - offset.y;
                    selectedComponent.setLocation(r.x, r.y);
                } else if(resizing) {
                    int type = selectedComponent.getCursor().getType();
                    switch(type) {
                        case Cursor.N_RESIZE_CURSOR:
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        case Cursor.NW_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        case Cursor.W_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            break;
                        case Cursor.SW_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            r.height += p.y - start.y;
                            break;
                        case Cursor.S_RESIZE_CURSOR:
                            r.height += p.y - start.y;
                            break;
                        case Cursor.SE_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            r.height += p.y - start.y;
                            break;
                        case Cursor.E_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            break;
                        case Cursor.NE_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        default:
                            System.out.println("Unexpected resize type: " + type);
                    selectedComponent.setBounds(r.x, r.y, r.width, r.height);
                    start = p;
    }

  • Is there a way to minimize packaged links sizes to that of resized dimensions and dpi  InDesign C

    Looking for a way to minimize packaged links sizes to that of resized dimensions and dpi?
    Is this a script? How would I go about finding something like this? What is the best way to
    not duplicate images. Storage is beginning to become a problem!
    Thanks,
    Alex

    Hey Alex,
    I think that a plugin called Link Optimizer is just what you're looking for.
    http://zevrix.com/linkoptimizer.php
    Cheers,
    -Andrew

  • Array of JPanel and Array of JTextField?

    Hi,
    I try to create array of jpanel and inizialize it in "for" , but when run it give me this error message:
    "Exception in thread "main" java.lang.NullPointerException"
    at the row: "panInsCantante.add(panInsNCC);"
    why?
    (ps. i tried in another code to create array of jtextfield and it give me same error message..)
    here part of code :
          JPanel [] panInsCantante = new JPanel[3];
          for(int i=0;i<=N;i++){
               JPanel panInsNCC= new JPanel();
               panInsNCC.setLayout( new GridLayout(3,1) );
               panInsNCC.add(campoTesto1);
               panInsNCC.add(campoTesto2);
               panInsNCC.add(campoTesto3);
               //panInsCantante[i] = new JPanel();
               //panInsCantante.setLayout( new GridLayout(1,1) );
         panInsCantante[i].add(panInsNCC);

    a question (theoric...)A VERY important question I may add.
    what's the difference between ..
    this instance :
    JPanel [] panInsCantante = new
    JPanel[3];This declares and initializes the array itself, nothing more. No JPanels have been initialized as yet, just the array. It's as if you have now built the shelves to hold the books, but you have no books up there yet...
    and this instance of panInsCantante? :
    panInsCantante[i] = new JPanel();and this initializes each JPanel in the array as you loop through the array. .... and now you have filled the shelves with the books and can use the books.
    You will need them both.
    In all likelihood, the reason for your confusion is that all of your previous arrays were arrays of primative types: int, double, float, and char. In this situation, you don't need to go through the step of initializing the variable.
    But now you are faced for the first time with an array of reference type, an array of Objects. This is a different situation and requires the steps that we have gone through.
    Message was edited by:
    petes1234

Maybe you are looking for