关于swing的一个综合例子

关于swing的一个综合例子
JTable 选中某一行某一列

JComboBox 自动生成

JButton 带图片

JLabel

窗体置顶 标题栏图标

自定义布局

package components;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class MySwingDemo extends JPanel {
public MySwingDemo() {
   initComponents();
  //super(new GridLayout(1, 2)); // 一行1列
  /*ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
   * protected static ImageIcon createImageIcon(String path) {
     java.net.URL imgURL = MyButtonDemo.class.getResource(path);
     if(imgURL!=null){
        System.out.println(imgURL+"____"+path);
        return new ImageIcon(imgURL);
     }else{
        System.err.println("couldn't find file:"+path);
        return null;
     }
     }*/
   
}
private void initComponents() {
 
 
   icon = new ImageIcon(this.getClass().getResource("images/right.gif")); 
   btnView = new JButton();
   table = new JTable();
   scrollPane = new JScrollPane();
   displayLabel = new JLabel();
   viewLabel = new JLabel();
   comRow = new JComboBox();
   comColumn = new JComboBox();
 
 
   setLayout(null); //自定义布局方式
   //设置btnView的参数
     btnView.setText("查看");
     btnView.setIcon(icon);
   btnView.setToolTipText("查看");
   btnView.setHorizontalTextPosition(AbstractButton.LEADING);
   btnView.setVerticalAlignment(AbstractButton.CENTER);
   //btnView.setPreferredSize(new Dimension(50,20));
   btnView.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e) {
     // TODO Auto-generated method stub
     btnViewActionPerformed(e);
    }
  
   });
   add(btnView);
   btnView.setBounds(20, 190, 100, 25); //设置 button的位置大小
   //设置table的参数
   table.setModel(tableModel);
  /*jTable1.setModel(new javax.swing.table.DefaultTableModel(
     new Object[][] { { null, null, null, null },
       { null, null, null, null }, { null, null, null, null },
       { null, null, null, null } }, new String[] { "Title 1",
       "Title 2", "Title 3", "Title 4" }));*/
   //table.setPreferredScrollableViewportSize(new Dimension(500, 70));
   table.setForeground(new Color(255, 0, 0));
   table.setFont(getFont().deriveFont(Font.BOLD));
   table.setSelectionBackground(new Color(255, 0, 255));
   table.setCellSelectionEnabled(true); //可以选择一个单元
//   table.setRowSelectionAllowed(true);
   table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
     tableClickActionPerformed(table);
    }
   });

   //scrollPane = new JScrollPane(table);
   scrollPane.setViewportView(table);
   add(scrollPane);
   scrollPane.setBounds(100, 24, 300, 150);
 
   //label
   displayLabel.setText("未选择任何记录!");
   displayLabel.setForeground(Color.RED);
//   displayLabel.setFont();
   add(displayLabel);
   displayLabel.setBounds(200, 200, 400, 30);
 
   viewLabel.setText("未查看任何记录!");
   viewLabel.setForeground(Color.RED);

   add(viewLabel);
   viewLabel.setBounds(200, 230, 400, 30);

   //选择行列的下拉框
   for(int i =0;i<table.getRowCount();i++){
    comRow.addItem("第"+(i+1)+"行");
   }
   comRow.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt){
     comRowActionPerformed(evt);
    }
   });
   add(comRow);
   comRow.setBounds(30, 130, 63, 23);
 
   comColumn.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
     table.getColumnName(0), table.getColumnName(1),
     table.getColumnName(2), table.getColumnName(3)}));
   comColumn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
     comColumnActionPerformed(evt);
    }
   });
   add(comColumn);
   comColumn.setBounds(30, 150, 63, 23);
 
}

private boolean DEBUG = true;
protected ImageIcon icon;
protected JButton btnView;
protected JTable table;
protected JScrollPane scrollPane;
protected JLabel displayLabel;
protected JLabel viewLabel;
protected JComboBox comRow;
protected JComboBox comColumn;

private Object[][] data = {
    { "吕振", "java", new Integer(3), new Boolean(true) },
    { "张沛", ".NET", new Integer(4), new Boolean(true) },
    { "岳飞", "weapon", new Integer(100), new Boolean(false) },
    { "张艺谋", "film", new Integer(50), new Boolean(true) }

};
private String[] columnNames = { "姓名", "专业", "工龄", "健在" };
private DefaultTableModel tableModel = new DefaultTableModel(data,columnNames){

   @Override
   public Class<?> getColumnClass(int c) {
   //实现了如果是boolean自动转成JCheckbox
        /*需要自己的celleditor这么麻烦吧。jtable自动支持Jcheckbox,
        * 只要覆盖tablemodel的getColumnClass返回一个boolean的class,
        * jtable会自动画一个Jcheckbox给你,
        * 你的value是true还是false直接读table里那个cell的值就可以*/
    return getValueAt(0, c).getClass();
   }
 
   //设置哪些行列可以编辑
   public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 1) {
                return false;
            } else {
                return true;
            }
        }
 
};


/* public void setUpSportColumn(JTable table, TableColumn sportColumn) {

   JCheckBox box = new JCheckBox();
   sportColumn.setCellEditor(new DefaultCellEditor(box));

   // Set up tool tips for the sport cells.
   DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
   renderer.setToolTipText("Click for combo box");
   sportColumn.setCellRenderer(renderer);
}*/
protected static ImageIcon createImageIcon(String path) {
   //好像不支持ico?
     java.net.URL imgURL = MyButtonDemo.class.getResource(path);
     if(imgURL!=null){
        System.out.println(imgURL+"____"+path);
        return new ImageIcon(imgURL);
     }else{
        System.err.println("couldn't find file:"+path);
        return null;
     }
}
public void tableClickActionPerformed(JTable table){
   table.setCellSelectionEnabled(true);
   int numRow = table.getSelectedRow();
   int numColumn = table.getSelectedColumn();
   javax.swing.table.TableModel model = table.getModel();
   displayLabel.setText("当前选中的记录为》》 row: "
        + (numRow+1)+" column: "
        + (numColumn+1)+" values: "
        + model.getValueAt(numRow, numColumn));
 
}
public void printDebugData(JTable table) {
   // 测试时用到
   int numRows = table.getRowCount();
   int numColumns = table.getColumnCount();
   javax.swing.table.TableModel model = table.getModel();
   System.out.println("Value of Data:");
   for (int i = 0; i < numRows; i++) {
    System.out.print("   row" + i + ": ");
    for (int j = 0; j < numColumns; j++) {
     System.out.print(" " + model.getValueAt(i, j));
    }
    System.out.println();
   }
   System.out.println("==============================");
}
public void comRowActionPerformed(ActionEvent e){
   //改变comRow的时候做的操作
   table.setCellSelectionEnabled(false);
   table.setRowSelectionAllowed(true); //使之可以选中整行
   //table.clearSelection();
   table.setRowSelectionInterval(comRow.getSelectedIndex(), comRow.getSelectedIndex());
   //选择从 index0 到 index1 之间(包含两端)的行
   System.out.println("test"+comRow.getSelectedIndex());
}
public void comColumnActionPerformed(ActionEvent e){
   //改变comColumn的时候做的操作
   table.setCellSelectionEnabled(false);
   table.setCellSelectionEnabled(true);
   table.setColumnSelectionInterval(comColumn.getSelectedIndex(), comColumn.getSelectedIndex());
   //选择从 index0 到 index1 之间(包含两端)的列
   System.out.println("test"+comColumn.getSelectedIndex());
}
public void btnViewActionPerformed(ActionEvent e){
 
   // 点击查看按钮做的操作
   table.setCellSelectionEnabled(true);
   int numRow = comRow.getSelectedIndex();
   int numColumn = comColumn.getSelectedIndex();
   javax.swing.table.TableModel model = table.getModel();
   viewLabel.setText("当前查看的记录为》》 row: " + (numRow + 1) + " column: "
      + (numColumn + 1) + " values: "
      + model.getValueAt(numRow, numColumn));
   table.changeSelection(numRow, numColumn, false, false);

   /*
    * 此实现使用以下约定:
    *
    * toggle:false,extend:false。清除以前的选择并确保选定新的单元格。
    * toggle:false,extend:true。将以前的选择从定位点扩展到指定的单元格,清除所有其他选择。
    * toggle:true,extend:false。如果指定的单元格是选定的,则取消选定它。如果它不是选定的,则选定它。
    * toggle:true,extend:true。将定位点的选择状态应用于它与指定单元间的所有单元。
    */
}
public static void createAndShowGUI() {
   JFrame frame = new JFrame("测试swing的综合例子");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   MySwingDemo newContentPane = new MySwingDemo();
   newContentPane.setOpaque(true);
//   frame.setUndecorated(true); //设置为true则无标题栏
   frame.setContentPane(newContentPane);
 
   frame.setAlwaysOnTop(true); //设置窗口置顶
 
   ImageIcon icon1 = createImageIcon("images/Xbutton4.jpg");
   frame.setIconImage(icon1.getImage()); //设置标题栏图标
 
 

   //frame.setBounds(400, 300, 400, 300);
   frame.setPreferredSize(new Dimension(600,500));
//   frame.setSize(300, 400);
   frame.pack(); //不加只用setSize即可 加上需先设定setPreferredSize
  //Frame.pack()这个方法的作用就是根据窗口里面的布局及组件的 preferedSize来确定frame的最佳大小。
   /* *//** pack函数原型
      * Causes this Window to be sized to fit the preferred size
      * and layouts of its subcomponents. If the window and/or its owner
      * are not yet displayable, both are made displayable before
      * calculating the preferred size. The Window will be validated
      * after the preferredSize is calculated.
      * @see Component#isDisplayable
      *//*
     public void pack() {
   Container parent = this.parent;
   if (parent != null && parent.getPeer() == null) {
      parent.addNotify();
   }
   if (peer == null) {
      addNotify();
   }
         Dimension newSize = getPreferredSize();
         if (peer != null) {
             setClientSize(newSize.width, newSize.height);
         }

         if(beforeFirstShow) {
             isPacked = true;
         }

   validate();
     }*/
   frame.setVisible(true);
  /*
   Toolkit tk=Toolkit.getDefaultToolkit() ;
   Image image=tk.createImage("images/qq.ico"); //设置您的窗体标题上的图标
   frame.setIconImage(image); 
     Image img=tk.getImage("fpdbw.ico"); //设置您的光标
     Cursor cu=tk.createCustomCursor(img,new Point(10,10),"stick");
     frame.setCursor(cu); */

}

/**
* @param args
*/
public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
     createAndShowGUI();
    }
   });
}

}

你可能感兴趣的:(.net,swing,qq,单元测试,J#)