首页 > 解决方案 > JTextField 不可编辑,JFrame 作为父级,JWindow 使方法不可绘制

问题描述

我有以下代码

private JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);
private JWindow hsWindow = new JWindow(frame);

hsWindow.setPreferredSize(new Dimension(400, 200));
    JButton btnSave = new JButton("Save");
    JButton btnCancel = new JButton("Cancel");
    JLabel lblName = new JLabel("Enter your name: ");
    JTextField txtName = new JTextField();
hsWindow.add(btnSave);
hsWindow.add(btnCancel);
hsWindow.add(lblName);
hsWindow.add(txtName);
     
hsWindow.setVisible(true);
hsWindow.setFocusable(true);
hsWindow.setLocationRelativeTo(frame);
     
btnSave.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
         hsName = txtName.getText();
         saveHighScores();
         hsWindow.setVisible(false);
         hsWindow.setFocusable(false);
         txtName.setText("");
         setHighScores();
         gameOver(g);
    }
});

有人能告诉我为什么 JTextField 不可编辑吗?该字段本身就在那里,但我无法输入。

此外,当我在没有出现JWindow的情况下调用我的方法gameOver(g)时,一切都很好。但是,如果我有JWindow出现并在按下按钮后调用它,我的gameOver方法没有正确绘制。这是为什么?

这是gameOver方法的重要部分

private void gameOver(Graphics g){
  int z = 25;
  score = dots - 3; //The amount of apples collected = your score
  String msg = "Game Over";
  String scoreS = "Final Score : " + score; //Displaying score
  Font small = new Font("Helvetica", Font.BOLD, 14);
  Font smallnb = new Font("Helvetica", Font.PLAIN, 12);
  FontMetrics metric = getFontMetrics(small); //FontMetrics is easier to use to position text
  g.setColor(Color.white);
  g.setFont(small);
  
  //Centers and Draws the Messages
  g.drawString(msg, (WIDTH - metric.stringWidth(msg)) / 2, HEIGHT / 2);
  g.drawString(scoreS, (WIDTH - metric.stringWidth(scoreS)) / 2, ((HEIGHT / 2) - 30));
  
  //Drawing High Scores
  metric = getFontMetrics(smallnb);
  g.setFont(smallnb);
  g.setColor(Color.red);
  for(String line : str.split("\n")){
     g.drawString(line, (WIDTH - metric.stringWidth(str)) - 110, z += 
     g.getFontMetrics().getHeight());
  }

标签: java

解决方案


推荐阅读