JAVA

JAVA开发

2012年7月30日 #

JAVA SWING自定义行列标题的滚动面板示例

JScrollPane有以下两个方法 setColumnHeaderView(Component view) setRowHeaderView(Component view) 你可以利用它们, 一个用来显示表行头,一个用来显示列头

同例行标题也有.

package scrollpanel;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;

public class CustomScrollDlg extends JDialog {

 private static final long serialVersionUID = 1L;
 private final static int WIDTH = 100;
 private final static int HIGHT = 30;

 private JScrollPane jsp = new JScrollPane();
 private JPanel jpnlColumn = new JPanel();
 private JPanel jpnlRow = new JPanel();
 private JPanel jpnlContent = new JPanel();
 private Dimension dim = new Dimension(WIDTH, HIGHT);
 private int total = 20;

 public CustomScrollDlg() {
  setTitle("JAVA SWING自定义行列标题的滚动面板示例");
  setSize(600, 500);
  setLocation(200, 100);
  init();
 }

 private void init() {
  jpnlContent.setLayout(new GridBagLayout());
  jpnlColumn.setLayout(new GridBagLayout());
  jpnlRow.setLayout(new GridBagLayout());

  List<JLabel> colList = getLabelList(total);
  List<JLabel> rowList = getLabelList(total);
  JLabel lbl = null;
  for (int i = 0; i < total; i++) {
   lbl = colList.get(i);
   jpnlColumn.add(lbl, new GridBagConstraints(i, 0, 1, 1, 0, 0,
     GridBagConstraints.EAST, GridBagConstraints.NONE,
     new Insets(0, 0, 0, 0), 0, 0));

   lbl = rowList.get(i);
   jpnlRow.add(lbl, new GridBagConstraints(0, i, 1, 1, 0, 0,
     GridBagConstraints.NORTH, GridBagConstraints.NONE,
     new Insets(0, 0, 0, 0), 0, 0));
  }

  jpnlContent.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
  jpnlContent
    .setPreferredSize(new Dimension(WIDTH * total, HIGHT * total));
  jsp.getViewport().add(jpnlContent);

  JViewport colVP = new JViewport();
  colVP.setView(jpnlColumn);
  jsp.setColumnHeader(colVP);

  JViewport rowVP = new JViewport();
  rowVP.setView(jpnlRow);
  jsp.setRowHeader(rowVP);

  JLabel title = getLabel("Title");
  jsp.setCorner(JScrollPane.UPPER_LEFT_CORNER, title);
  jsp.setCorner(JScrollPane.LOWER_LEFT_CORNER, getLabel("****"));
  jsp.setCorner(JScrollPane.UPPER_RIGHT_CORNER, getLabel("**"));

  getContentPane().add(jsp);

 }

 private JLabel getLabel(String text) {
  JLabel lbl = new JLabel(text);
  lbl.setPreferredSize(dim);
  lbl.setMaximumSize(dim);
  lbl.setMinimumSize(dim);
  lbl.setBorder(BorderFactory.createEtchedBorder());
  return lbl;
 }

 private List<JLabel> getLabelList(int count) {
  List<JLabel> list = new ArrayList<JLabel>();
  for (int i = 0; i < count; i++) {
   list.add(getLabel(" JLabel" + i));
  }

  return list;
 }

 public static void main(String[] args) {
  new CustomScrollDlg().setVisible(true);
 }

}

posted @ 2012-07-30 20:50 caoyong 阅读(458) | 评论 (0)编辑 收藏