未设置全局变量



我正在使用swing,并且有一个函数(CreateAndShowGUI()),它监听Up、Left、Right和amp;向下现在,每当按下这个键中的任何一个时,我都会将key_pressed标志设置为True。key_pressed标志是一个全局变量。

现在,当我运行程序并按下任何键(向上、向左、向右、向下)时,我都可以看到key_pressed变量被设置为True。但当我试图在main中访问相同的变量时,这个key_pressd的值是false。有人能帮我判断哪里错了吗?

public class table1  {
public static class Global {
   // public static boolean key_pressed=false;
    public static int[][] a={{2,8,32,64},{2,4,16,16},{16,128,8,64},{2,4,8,16}};
}
 public static boolean key_pressed=false;
 public static JTable table;
 public static JFrame frame=new JFrame("FrameDemo");
 public static void createAndShowGUI() {
        //Create and set up the window.
        //frame = 
        frame.setPreferredSize(new Dimension(875, 800));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setIconImage(new ImageIcon("menu.jpg").getImage());
        JLabel emptyLabel = new JLabel("");
        emptyLabel.setFocusable(true);
        Action left_action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                key_pressed=true;
                System.out.println("left");
                //do nothing
            }
        };
        Action right_action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                key_pressed=true;
                System.out.println("right");
                //do nothing
            }
        };
        Action up_action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                key_pressed=true;
                System.out.println("up");
                //do nothing
            }
        };
        Action down_action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("down");
                //do nothing
            }
        };
        emptyLabel.getInputMap().put(KeyStroke.getKeyStroke("LEFT"),"left");
        emptyLabel.getActionMap().put("left", left_action);
        emptyLabel.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"),"right");
        emptyLabel.getActionMap().put("right", right_action);
        emptyLabel.getInputMap().put(KeyStroke.getKeyStroke("UP"),"up");
        emptyLabel.getActionMap().put("up", up_action);
        emptyLabel.getInputMap().put(KeyStroke.getKeyStroke("DOWN"),"down");
        emptyLabel.getActionMap().put("down", down_action);
        emptyLabel.setPreferredSize(new Dimension(875, 800));

        //frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
        Font f = new Font("serif", Font.PLAIN, 15);
        JLabel score_area = new JLabel();
        score_area.setBounds(870-130,00, 130, 50);
        score_area.setText("sample text");
        emptyLabel.add(score_area);
        /*JTable t1=addtable(Global.a);
        emptyLabel.add(t1);
        t1.setBounds(0, 80, 875,875-80);*/
        //pnl.add(t1);
        frame.add(emptyLabel);
        frame.invalidate();
        frame.validate();
        frame.repaint();
        //Display the window.
        frame.pack();

        frame.setVisible(true);
    }
  public static JTable addtable(int[][] a)
  {
      System.out.println("add game_gui entered");
      //a[0][0] +=1;      
      System.out.println("a value "+a[0][0]);
      String[] columnNames = {"First Name",
              "Last Name",
              "Sport","sample"
              };
       Object[][] data1= new Object[4][4];
       for(int i=0;i<a.length;i++){
           for(int j=0;j<a.length;j++)
           {
               data1[i][j]=(Object)a[i][j];
           }
       }
       Font f = new Font("serif", Font.PLAIN, 55);
       table = new JTable( data1, columnNames);/*{
           Object x;
           JLabel label;
           @Override
           public Component prepareRenderer(TableCellRenderer renderer,
                     int row, int column) {
                x=table.getModel().getValueAt(row, column);
             //  System.out.println(x+","+row+","+column);
                   label = (JLabel) super.prepareRenderer(renderer, row, column);
                  if(x ==(Object)2)
                  {
                      System.out.println(x+" "+row+" " +column);
                     label.setBackground(Color.YELLOW);
                  } else if(x==(Object)32) {
                     label.setBackground(Color.gray);
                  }
                  else if(x==(Object)
                          16) {
                     label.setBackground(Color.blue);
                  }
                  return label;
               };
       };*/
       table.setRowHeight(125);
       table.setEnabled(false);
       DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();  
        dtcr.setHorizontalAlignment(SwingConstants.CENTER); 
        table.getColumnModel().getColumn(0).setCellRenderer(dtcr);
        int  x=((Integer)table.getValueAt(0, 0)).intValue();
        System.out.println("sdfsfsdfsfds"+x);
        if(x==55)
            System.out.println("hahahah "+x);
        table.getColumnModel().getColumn(1).setCellRenderer(dtcr);
        table.getColumnModel().getColumn(2).setCellRenderer(dtcr);
        table.getColumnModel().getColumn(3).setCellRenderer(dtcr);
        DefaultTableCellRenderer dtcr1 = new DefaultTableCellRenderer();
        dtcr1.setBackground(Color.cyan);

        table.repaint();
        table.setFont(f);
        return table;
  }
  public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
      //key_pressed=true;
      createAndShowGUI();
      while(true)
      {
          //System.out.println(key_pressed);
          if(key_pressed)
          {
              key_pressed=false;
              System.out.println("Hello");
          }
      }
     }}

正如@Lashane所提到的:使用volatile到key_pressed解决了这个问题。

即使使用volatile解决了问题,我认为在main中正确(和推荐)使用os实例和类也会解决问题。

当我看到你的代码时,我的第一个想法是"为什么他不使用类的名称来访问方法和类属性?"第二个想法是:"难道内部类不应该声明为singleton而不是static吗?"。我想知道我的第二个想法是否准确,因为我不知道使用静态还是单例是更有效还是"更好",但它肯定也解决了问题。

干杯

相关内容

  • 没有找到相关文章

最新更新