0

我有一个JFrame包含一个JPanel. 用户可以使用鼠标调整框架的大小。当frame的宽度>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 时,滚动条无法正确更新。我需要的是,当框架的宽度小于阈值时,面板应调整为恒定值,否则为另一个值。

4

1 回答 1

3

滚动条没有正确更新。

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

// this.jScrollPane1.revalidate();
this.inFrame.revalidate();
于 2010-09-24T03:59:32.260 回答