2012-04-27 154 views
0

我有点新摇摆,我试图咳出一些涉及Jtable的代码。 我发现即使我添加了滚动条策略,垂直滚动条似乎并没有出现。这段代码很简陋(事先警告你)。但是,请您指出我需要在滚动条政策中加入哪些内容。我曾尝试在很多地方添加它,但似乎并未出现。jTable swing中的垂直滚动条不会出现

另一个问题是我如何做一个空表。就像在每次点击过程按钮时一样,我想刷新表格。你能不能指出我这个方向?

使用说明:只需在常规节点文本框中输入一个数字,如5或10 ,然后单击处理按钮。

我的代码:

package ui; 

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Component; 
import java.awt.FlowLayout; 
import java.awt.Font; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.FocusEvent; 
import java.awt.event.FocusListener; 
import java.util.Arrays; 
import java.util.LinkedList; 
import java.util.List; 
import java.util.Map; 
import java.util.Set; 

import javax.swing.BorderFactory; 
import javax.swing.Box; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTabbedPane; 
import javax.swing.JTable; 
import javax.swing.JTextField; 
import javax.swing.UIManager; 
import javax.swing.UIManager.LookAndFeelInfo; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.table.DefaultTableModel; 

import utils.ThroughputUtility; 

/** 
* @author Nathan 
* 
*/ 
public class EntryPoint extends JPanel{ 
    public boolean isProcesed =false; 
    static JFrame frame; 

    JTabbedPane jTabbedPane = new JTabbedPane(); 

    private static final long serialVersionUID = -6490905886388876629L; 
    public String messageTobeSent = null; 
    public int regularNodeCount =0; 

    public static final String MESSAGE_TO_BE_SENT =" Please Enter the message to be sent. "; 

    protected static final String ONE = "1"; 

    Map<String,Double> regNodeThroughputMap ; 
    static JTable tableOfValues; 

    Object columnNames[] = { "<html><b>Regular Node Name</b></htm>", "<html><b>Throughput Value Obtained</b></html>"}; 

    Object rowData[][] = null; 
    public EntryPoint() { 



     jTabbedPane.setTabPlacement(JTabbedPane.NORTH); 
     Font font = new Font("Verdana", Font.BOLD, 12); 
     jTabbedPane.setFont(font); 

     //Server Side Panel. 
     JPanel serverPanel = getServerPanel();  
     jTabbedPane.addTab("Server", serverPanel); 

     //Client side Panel. 
     JPanel clientPanel = getClientPanel();  
     jTabbedPane.addTab("Client", clientPanel); 

    } 

    private JPanel getClientPanel() { 
     //Heading Label 
     JPanel clientPanel = new JPanel(); 
     JLabel RegularNodeLabel = new JLabel("<html><u>Throughput Optimization For Mobile BackBone Networks</u></html>"); 
     RegularNodeLabel.setFont(new Font("Algerian",Font.BOLD,20)); 
     RegularNodeLabel.setForeground(new Color(176,23,31)); 

     clientPanel.add(RegularNodeLabel); 

     return clientPanel; 
    } 

    /**Server Side Code 
    * @return 
    */ 
    private JPanel getServerPanel() { 

     //Heading Label 
     JPanel serverPanel = new JPanel(new FlowLayout()); 
     final Box verticalBox1 = Box.createVerticalBox(); 
     Box horozontalBox1 = Box.createHorizontalBox(); 
     Box verticalBox2forsep = Box.createVerticalBox(); 
     Box horozontalBox2 = Box.createHorizontalBox(); 


     JPanel heading = new JPanel(new FlowLayout(FlowLayout.CENTER)); 

     JLabel backBoneNodeLabel = new JLabel("<html><u>Throughput Optimization For Mobile BackBone Networks</u></html>"); 
     backBoneNodeLabel.setFont(new Font("Algerian",Font.BOLD,20)); 
     backBoneNodeLabel.setForeground(new Color(176,23,31)); 
     backBoneNodeLabel.setAlignmentX(Component.CENTER_ALIGNMENT); 

     //Indication of BackBone Node 
     JPanel body = new JPanel(new FlowLayout(FlowLayout.LEFT)); 
     JLabel backBoneNodeID = new JLabel("Fixed BackBone Node"); 
     backBoneNodeID.setFont(new Font("Algerian",Font.BOLD,16)); 
     backBoneNodeID.setForeground(new Color(176,23,31)); 
     backBoneNodeID.setAlignmentX(Component.CENTER_ALIGNMENT); 

     //Seperator 
     JLabel seperator = new JLabel("  "); 
     seperator.setFont(new Font("Algerian",Font.BOLD,20)); 
     seperator.setForeground(new Color(176,23,31)); 
     verticalBox2forsep.add(seperator); 

     //Message label 
     JLabel messageLabel = new JLabel("Please enter the Message to be sent: "); 
     messageLabel.setFont(new Font("Algerian",Font.BOLD,16)); 
     messageLabel.setForeground(new Color(176,23,31)); 
     messageLabel.setAlignmentX(Component.LEFT_ALIGNMENT); 

     //Message Text 
     final JTextField messageText = new JTextField(MESSAGE_TO_BE_SENT,25); 
     messageText.addFocusListener(new FocusListener() { 

      @Override 
      public void focusLost(FocusEvent arg0) { 
       // TODO Auto-generated method stub 

      } 

      @Override 
      public void focusGained(FocusEvent arg0) { 
       if(messageText.getText().trim().equalsIgnoreCase(MESSAGE_TO_BE_SENT.trim())){ 
        messageText.setText(""); 
       } 

      } 
     }); 


     horozontalBox1.add(messageLabel); 
     horozontalBox1.add(messageText); 

     //Regular node attached to backbone nodes. 
     JLabel regularNodelabel = new JLabel("Number of Regular nodes to be attached to the backbone node. "); 
     regularNodelabel.setFont(new Font("Algerian",Font.BOLD,16)); 
     regularNodelabel.setForeground(new Color(176,23,31)); 
     regularNodelabel.setAlignmentX(Component.LEFT_ALIGNMENT); 

     //Regular Node text 
     final JTextField regularNodeText = new JTextField(ONE,5); 
     regularNodeText.addFocusListener(new FocusListener() { 

      @Override 
      public void focusLost(FocusEvent e) { 
       // TODO Auto-generated method stub 

      } 

      @Override 
      public void focusGained(FocusEvent e) { 
       if(regularNodeText.getText().trim().equalsIgnoreCase(ONE.trim())){ 
        regularNodeText.setText(""); 
        tableOfValues = new JTable(0,0); 

       } 


      } 
     }); 

     horozontalBox2.add(regularNodelabel); 
     horozontalBox2.add(regularNodeText); 

     //Button for Processing. 
     JButton processbutton = new JButton("Process"); 
     processbutton.setFont(new Font("Algerian",Font.BOLD,16)); 
     processbutton.setForeground(new Color(176,23,31)); 
     processbutton.setAlignmentX(Component.CENTER_ALIGNMENT); 

     //Processing on clciking process button 
     processbutton.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       isProcesed=false; 
       Runnable runThread = new Runnable() { 

        @Override 
        public void run() { 
         while(!isProcesed){ 
          try { 
           Thread.sleep(50); 
          } catch (InterruptedException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 
         } 
         verticalBox1.add(tableOfValues); 
         isProcesed =false; 

        } 
       }; 
       Thread processThread= new Thread(runThread); 
       processThread.start(); 


       regularNodeCount = Integer.parseInt(regularNodeText.getText().trim()); 
       regNodeThroughputMap = getThroughPutValues(regularNodeText.getText().trim()); 
       System.out.println("Map obtained = "+regNodeThroughputMap); 
       tableOfValues = populateTable(regNodeThroughputMap); 
       isProcesed=true; 
       JScrollPane scrollPane = new JScrollPane(tableOfValues); 
       scrollPane.add(tableOfValues); 
       scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
       verticalBox1.add(scrollPane,BorderLayout.CENTER); 
       // verticalBox1.add(scrollPane); 


      } 
     }); 

     verticalBox1.add(backBoneNodeID); 
     verticalBox1.add(verticalBox2forsep); 
     verticalBox1.add(horozontalBox1); 
     verticalBox1.add(verticalBox2forsep); 
     verticalBox1.add(horozontalBox2); 
     verticalBox1.add(verticalBox2forsep); 
     verticalBox1.add(processbutton); 



     heading.add(backBoneNodeLabel); 
     //body.add(backBoneNodeID); 
     body.add(verticalBox1); 

     serverPanel.add(heading); 
     serverPanel.add(body); 

     return serverPanel; 
    } 

    protected JTable populateTable(Map<String,Double> regNodeThroughputMap) { 

     /*{ { "Row1-Column1", "Row1-Column2", "Row1-Column3" }, 
      { "Row2-Column1", "Row2-Column2", "Row2-Column3" } }*/ 
     rowData = new Object[regularNodeCount+1][2]; 

     Set<Map.Entry<String, Double>> set = regNodeThroughputMap.entrySet(); 

     for (Map.Entry<String, Double> me : set) { 
      System.out.println("key ="+me.getKey()); 
      System.out.println("Value ="+me.getValue()); 
     } 

     String[] keys = new String[regularNodeCount+2]; 
     String[] values = new String[regularNodeCount+2]; 

     List<String> keyList = new LinkedList<String>(); 
     List<String> valueList = new LinkedList<String>(); 
     keyList.add(""); 
     valueList.add(""); 

     for(String key:regNodeThroughputMap.keySet()){ 
      keyList.add(key); 
     } 

     for(double value:regNodeThroughputMap.values()){ 
      System.out.println(value); 
      valueList.add(Double.toString(value)); 
     } 

     keyList.toArray(keys); 
     valueList.toArray(values); 

     System.out.println(Arrays.asList(keys)); 
     System.out.println(Arrays.asList(values)); 
     rowData[0][0] =columnNames[0]; 
     rowData[0][1] =columnNames[1]; 

     for(int i=1;i<=regularNodeCount;i++){ 
      for(int j=0;j<2;j++){ 
       if(j==0) 
        rowData[i][j]=keys[i]; 
       if(j==1) 
        rowData[i][j]=values[i]; 
      } 
     } 


     return new JTable(rowData, columnNames); 


      //Printing the array 
    /*  for (int i =0; i < regularNodeCount; i++) { 
       for (int j = 0; j < 2; j++) { 
       System.out.print(" " + rowData[i][j]); 
       } 
       System.out.println(""); 
       } 
*/ 


    } 

    protected Map<String, Double> getThroughPutValues(String regularNodeInput) { 
     return ThroughputUtility.generateMapofNodeAndThroughput(regularNodeInput); 
    } 

    protected static void createAndShowGUI() { 
     //Create and set up the window. 
     frame = new JFrame("Throughput Optimization for Mobile BackBone Networks"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     EntryPoint splitPaneDemo = new EntryPoint(); 
     frame.getContentPane().add(splitPaneDemo.jTabbedPane); 

     JScrollPane sp = new JScrollPane(tableOfValues); 
     sp.setBorder(BorderFactory.createEmptyBorder()); 
     sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
     sp.setHorizontalScrollBarPolicy(JScrollPane .HORIZONTAL_SCROLLBAR_AS_NEEDED); 
     frame.setResizable(false); 
     //Display the window. 
     frame.pack(); 
     frame.setVisible(true); 
     frame.setSize(800,600); 




    } 


    public static void main(String[] args) { 

     try { 
       for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { 
        if ("Nimbus".equals(info.getName())) { 
         UIManager.setLookAndFeel(info.getClassName()); 
         break; 
        } 
       } 
      } catch (UnsupportedLookAndFeelException e) { 
       e.printStackTrace(); 
      } catch (ClassNotFoundException e) { 
       e.printStackTrace(); 
      } catch (InstantiationException e) { 
       e.printStackTrace(); 
      } catch (IllegalAccessException e) { 
       e.printStackTrace(); 
      } 

      javax.swing.SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
        createAndShowGUI(); 
       } 
      }); 

    } 



} 

添加ThroughputUtility.java

package utils; 

import java.util.LinkedHashMap; 
import java.util.LinkedList; 
import java.util.List; 
import java.util.Map; 

/** 
* @author Nathan 
* 
*/ 
public class ThroughputUtility { 

    public static double MIN =5000; 
    public static double MAX =10000; 
    public static final double e =Math.E; 
    public static final double epsilon = 8.854187 *Math.pow(10,-12); 

    static int regularNodeCount; 
    static int counter ; 

    /**Generates the map of Node and ThroughPut values 
    * @param regularNodeInput 
    */ 
    public static Map<String,Double> generateMapofNodeAndThroughput(String regularNodeInput){ 
     regularNodeCount = Integer.parseInt(regularNodeInput); 
     List<Double> randNodeDistances =getRandDistanceOfNodes(regularNodeCount); 

     Map<String,Double> nodeAndThroughputmap = getThroughputValuesForNodes(randNodeDistances); 
     System.out.println(nodeAndThroughputmap); 
     return nodeAndThroughputmap; 

    } 

    /** Obtains the throughput value based on the distances between 
    * the regular nodes and the backend Nodes. 
    * @param randNodeDistances 
    * @return 
    */ 
    private static Map<String, Double> getThroughputValuesForNodes(
      List<Double> randNodeDistances) { 
     Map<String,Double> nodeAndThroughputmap = new LinkedHashMap<String, Double>(); 

     for(double i : randNodeDistances){ 
      double throughputValue = calculateThroughPut(i); 
      nodeAndThroughputmap.put("RegularNode :"+counter, throughputValue); 
      counter++; 
     } 

     return nodeAndThroughputmap; 
    } 

    private static double calculateThroughPut(double distanceij) { 

     double throughput = 1 /(e*regularNodeCount*distanceij*epsilon); 

     return throughput; 
    } 

    /**Generates the distance dij . 
    * @param regularNodeCount 
    * @return 
    */ 
    private static List<Double> getRandDistanceOfNodes(int regularNodeCount) { 
     List<Double> distnodeNumbers = new LinkedList<Double>(); 

     for(int i=0;i<regularNodeCount;i++){ 
      double randnodeNumber = MIN + (double)(Math.random() * ((MAX - MIN) + 1)); 
      distnodeNumbers.add(randnodeNumber); 

     } 
     return distnodeNumbers; 
    } 

    public static void main(String[] args) { 
     ThroughputUtility.generateMapofNodeAndThroughput("5"); 
     /*System.out.println(e); 
     System.out.println(epsilon);*/ 
    } 
} 
+0

我无法运行您的代码,因为_ThroughputUtility_类缺失。请发布一个更简约(但可运行)的代码部分,显示问题 – moeTi 2012-04-27 15:00:37

+1

..或换句话说,张贴[SSCCE](http://sscce.org/):) – COD3BOY 2012-04-27 15:02:42

回答

3

主要的问题,为什么你不能看到滚动条是你的表添加到多个容器。

点击按钮时,你重新创建了很多的swing对象(为什么?),然后你开始一个线程添加表到框中(为什么??如果你不知道什么是swing和多线程你在做)。之后(或之前,取决于线程运行的时间),将表添加到滚动窗格。

scrollpane不包含您的表格,因为您只能使用它一次。

一个快速修复会是这样的: 创建所有GUI界面的东西一次,远离任何动作监听器和东西。如果你启动应用程序,它应该只显示一个空表。不要将同一个对象添加到多个容器中!您可以通过使用

table.setPreferredSize(new Dimension(width, height)); 

如果单击按钮(也就是你的动作侦听器),让所有的新数据,并将其添加它到表控制你的表和滚动窗格的大小。例如通过使用这样的东西。

tableOfValues.getModel().setValueAt(value, row, column); 

或创建新的表格模型,如果你有:

tableOfValues.setModel(new DefaultTableModel(rowData, columnNames)); 

这就是我可以通过看代码告诉你现在...

编辑: 在方法populateTable(...)不要创建一个新表!如果需要,可以使用上述代码来设置新模型,或使用现有模型并修改其值。

+0

感谢一堆moeTi。我遵循你的指示。并让我的东西工作。谢谢 – 2012-04-28 19:28:42

2
  1. 你永远在滚动窗格到JFrame据我可以在 告诉咋一看
  2. 您更改TableModel中的数据(或替换JTable的 的TableModel)

http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

+0

我删除了该行,因为我已经将它添加到垂直框中,当我添加到框架中时,UI上没有显示任何内容 – 2012-04-27 15:17:56

+1

然后,您应该从createAndShowGUI()中删除所有这些行(使用表和滚动窗格)。 JTable只能添加到一个滚动窗格中(或者一般来说,任何组件在Swing中只能有一个父项)。 – 2012-04-27 15:23:14

+0

谢谢Walter。我已经删除它。你能帮我用垂直滚动条吗?如果你能帮上忙,那将是美好的。 – 2012-04-27 15:29:09

1

我有同样的问题,只需将JTable preferredsize设置为null,滚动条就会显示出来。

希望它有帮助

+0

为我工作,thx – 2017-10-01 09:42:39

相关问题