Java GUI重绘JPanel JFrame的问题

时间:2014-02-02 01:19:19

标签: java user-interface jframe jtextarea repaint

计划是在搜索另一首歌时让程序用不同的歌词替换屏幕上的歌词。

}public void lyricPrinter(){
    if(scroll != null){
    scroll.removeAll(); //--> temporary test
    System.out.println("removed scroll");
    scroll.repaint();
    }

    JTextArea textarea = new JTextArea(lyrics);
    textarea.setBackground(Color.LIGHT_GRAY);
    textarea.setEditable(false);


    scroll = new JScrollPane (textarea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    GUI.frame.remove(scroll);
    GUI.frame.add(scroll);
    GUI.frame.setVisible(true);




}

我认为使用removeall()可以解决这个问题,但最终会发生这种情况。

首次印刷歌词.. printing lyrics for the first time.. 我更改歌词后尝试替换以前的歌词.. After I change the lyrics and try to replace the previous lyrics..

3 个答案:

答案 0 :(得分:4)

  • 您为什么要添加和删除组件?这是实现目标的一种倒退和危险的方式。
  • 即使你的计划没问题,你也不会在任何地方删除原来的JScrollPane。此调用GUI.frame.remove(scroll);删除了 JScrollPane,即尚未添加的JScrollPane,而不是当前驻留在GUI中的旧版本。
  • 相反,为什么不专注于保留组件并交换他们持有的数据 - 他们的文本?这就是我要做的以及我强烈推荐的内容。
  • 您的GUI.frame....来电表明您可能误用了静态字段。您的JFrame不应该由静态字段保存,除非您不关心维护数据和行为的封装。

修改
我推荐的是

  • 你有一个JTextArea字段,一个包含你歌词的文字,
  • 它是类中的非静态字段,在整个类中都可见,因为它未在构造函数或方法中声明。
  • 在你想要交换歌词的事件代码中,你只需在这个JTextArea变量上调用setText(...),传入一个包含新歌词的字符串。

所以说你有一个名为songLyricsTextArea的JTextArea来交换文本,你要做的就是

String newLyrics = somehowGetNewLyricsToSong(); 
songLyricsTextArea.setText(newLyrics);

例如,在下面的演示程序中,我在Java代码中读取了Java Swing教程中的几个演示程序。我将程序名放在右边的JList中,并为JList提供一个ListSelectionListener,用于交换JTextArea中的文本(此处称为programTextArea),类似于我建议的那样。我的演示中的关键代码在这里的监听器中:

  demoList.addListSelectionListener(new ListSelectionListener() {

     @Override    // a new program has been selected
     public void valueChanged(ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
           if (demoList.getSelectedIndex() != -1) { // make sure selection valid
              DemoProgram demoProgram = demoList.getSelectedValue(); // get selection
              programTextArea.setText(demoProgram.getText());  // get text and pass into text area
           }
        }
     }
  });

整个程序,您应该编译并运行以查看它是如何工作的,因此:

import java.awt.BorderLayout;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

@SuppressWarnings("serial")
public class SwapTextExample extends JPanel {
   private static final String[][] DEMO_PROGS = {
         {     "BorderDemo.java",
               "http://docs.oracle.com/javase/tutorial/uiswing/examples/"
                     + "components/BorderDemoProject/src/components/BorderDemo.java" },
         {     "ButtonDemo.java",
               "http://docs.oracle.com/javase/tutorial/uiswing/examples/"
                     + "components/ButtonDemoProject/src/components/ButtonDemo.java" },
         {     "ButtonHtmlDemo.java",
               "http://docs.oracle.com/javase/tutorial/uiswing/examples/"
                     + "components/ButtonHtmlDemoProject/src/components/ButtonHtmlDemo.java" },
         {     "CheckBoxDemo.java",
               "http://docs.oracle.com/javase/tutorial/uiswing/examples/"
                     + "components/CheckBoxDemoProject/src/components/CheckBoxDemo.java" },
         {     "ComboBoxDemo.java",
               "http://docs.oracle.com/javase/tutorial/uiswing/examples/"
                     + "components/ComboBoxDemoProject/src/components/ComboBoxDemo.java" }, };

   private DefaultListModel<DemoProgram> model = new DefaultListModel<>();
   private JList<DemoProgram> demoList = new JList<DemoProgram>(model);
   private JTextArea programTextArea = new JTextArea(40, 70);

   public SwapTextExample() throws IOException {
      for (String[] demoProgText : DEMO_PROGS) {
         String name = demoProgText[0];
         String link = demoProgText[1];
         URL url = new URL(link);
         Scanner scanner = null;
         try {
            scanner = new Scanner(url.openStream());
            StringBuilder sb = new StringBuilder();
            while (scanner.hasNextLine()) {
               sb.append(scanner.nextLine() + "\n");
            }
            String text = sb.toString();
            DemoProgram demoProg = new DemoProgram(name, link, text);
            model.addElement(demoProg);
         } finally {
            if (scanner != null) {
               scanner.close();
            }
         }

      }

      demoList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      demoList.addListSelectionListener(new ListSelectionListener() {

         @Override    // a new program has been selected
         public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
               if (demoList.getSelectedIndex() != -1) { // make sure selection valid
                  DemoProgram demoProgram = demoList.getSelectedValue(); // get selection
                  programTextArea.setText(demoProgram.getText());  // get text and pass into text area
               }
            }
         }
      });

      setLayout(new BorderLayout());
      add(new JScrollPane(demoList), BorderLayout.WEST);
      add(new JScrollPane(programTextArea), BorderLayout.CENTER);
   }

   private static void createAndShowGui() {
      SwapTextExample mainPanel;
      try {
         mainPanel = new SwapTextExample();
         JFrame frame = new JFrame("Swap Text Example");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().add(mainPanel);
         frame.pack();
         frame.setLocationByPlatform(true);
         frame.setVisible(true);
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class DemoProgram {
   private String name;
   private String link;
   private String text;

   public DemoProgram(String name, String link, String text) {
      this.name = name;
      this.link = link;
      this.text = text;
   }

   public String getName() {
      return name;
   }

   public String getLink() {
      return link;
   }

   public String getText() {
      return text;
   }

   @Override
   public String toString() {
      return name;
   }
}

答案 1 :(得分:0)

您永远不会删除旧的滚动窗格。移动GUI.frame.remove(滚动);在创建新滚动窗格之前启动。

答案 2 :(得分:-1)

我通过简单地删除文本区域然后读取更新的文本区域来修复此问题。比从滚动窗格中删除文本更容易,但仍保留实际窗格,然后尝试在其上添加新文本..

}public void lyricPrinter(){
    if(scroll != null){
    //scroll.removeAll(); //--> temporary test
    //System.out.println("removed scroll");
    //scroll.repaint();
    GUI.frame.remove(scroll);
    }

    JTextArea textarea = new JTextArea(lyrics);
    textarea.setBackground(Color.LIGHT_GRAY);
    textarea.setEditable(false);


    scroll = new JScrollPane (textarea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);


    GUI.frame.add(scroll);
    GUI.frame.setVisible(true);




}