如何通过事件更新JTextArea的属性?

时间:2016-05-01 16:35:58

标签: java swing user-interface components updates

我已经制作了这个简单的文本编辑器程序,但是在程序运行时无法弄清楚如何更改GUI组件的属性。 假设这是我的文本编辑器源代码的一部分:

boolean wordwrap = false;

void mainFrame() {
  frame = new JFrame("Text Editor");
  textArea = new JTextArea(50,20);
  textArea.setLineWrap(wordwrap);

让我说我有一个事件源(JButton)被添加为Listener来改变 textArea的{​​{1}}。就像这样:

.setLineWrap(boolean)

但是这段代码不起作用!!那么,在程序运行时更新或编辑JAVA GUI组件的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

revalidate and validate() 

将更新框架。 您不需要使用repaint()。

最终方法:

public void actionPerformed(ActionEvent event) {
  if(wordwrap) wordwrap = false;
  else wordwrap = true;
  textArea.setLineWrap(wordwrap);
  frame.revalidate(); //is preferable but validate() also works.
}

您可以更新整个帧或只更新jComponent(插入TextArea而不是“frame”.revalidate();)

答案 1 :(得分:0)

仅供参考,在我有机会测试之后,没有revalidate()repaint(),它可以正常工作。我怀疑问题出在代码中的其他地方。

public class TestTextArea
{
   private final static String testLine = 
           "This is some rather long line that I came up with for testing a textArea.";

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

   private static void gui()
   {
      JFrame frame = new JFrame();

      final JTextArea textArea = new JTextArea();
      JPanel span = new JPanel();
      JButton toggle = new JButton( "Switch line wrap" );
      toggle.addActionListener( new ActionListener()
      {
         @Override
         public void actionPerformed( ActionEvent e )
         {
            textArea.setLineWrap( !textArea.getLineWrap() );
         }
      } );

      for( int i = 0; i < 10; i++ )
         textArea.append( testLine + testLine + "\n" );
      span.add( toggle );
      frame.add( span, BorderLayout.SOUTH );
      frame.add( textArea );

      frame.pack();
      frame.setSize( 500, 500 );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      frame.setLocationRelativeTo( null );
      frame.setVisible( true );
   }
}
相关问题