调整父JFrame的大小时调整子面板的大小

时间:2010-09-24 03:39:37

标签: java swing jframe jpanel jscrollpane

我有JFrame,其中包含JPanel。用户可以使用鼠标调整框架的大小。当框架的宽度> 400,jpanel里面的宽度设置为10;否则1080。

在框架和面板之间,还有一个JScrollBar

这是我的代码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ComponentEvent;
import javax.swing.*;
import javax.swing.table.*;
/**
 *
 * @author Administrator
 */
public class TableFrame extends javax.swing.JFrame {
public JScrollPane jScrollPane1 = new JScrollPane();
public JTable table;
public JScrollPane getScrollPane(){
    return this.jScrollPane1;
}

JPanel inFrame = new JPanel();
public TableFrame() {
    initComponents();

    jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    //this.jScrollPane1.setViewportView(inFrame);
    this.getContentPane().setLayout(new BorderLayout());
    this.addComponentListener(new java.awt.event.ComponentAdapter() {
        public void componentResized(ComponentEvent e) {
                    setSize();
            }
    });
    this.getContentPane().add(this.jScrollPane1);

    this.jScrollPane1.setViewportView(this.inFrame);

}

public void setSize(){
    int w = this.getWidth();
    int width = 0;
    int height = 1000;
    if(w < 400){
        width = 10;
        this.inFrame.setBackground(Color.blue);
    }else{
        width = 1080;
        this.inFrame.setBackground(Color.red);
    }
    this.inFrame.setPreferredSize(new Dimension(width, height));
    this.jScrollPane1.revalidate();
}

/** This method is called from within the constructor to
 * initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
    TableFrame frame = new TableFrame();

    frame.setVisible(true);


}

// Variables declaration - do not modify
// End of variables declaration

}

但是,JScrollPane的滚动条无法正常工作。当我将帧从宽度大于400调整到小于400时,滚动条无法正确更新。我需要的是当帧的宽度小于阈值时,面板应调整为一个恒定值,否则为另一个值。

1 个答案:

答案 0 :(得分:3)

  

滚动条不会更新   正确。

您应该重新验证面板,而不是滚动窗格:

// this.jScrollPane1.revalidate();
this.inFrame.revalidate();