【问题标题】:How can a JTextArea's properties be updated by an event?事件如何更新 JTextArea 的属性?
【发布时间】:2016-08-26 10:19:06
【问题描述】:

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

boolean wordwrap = false;

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

假设我添加了一个事件源(JButton)作为监听器进行更改 textArea 的.setLineWrap(boolean)。就像这样:

public void actionPerformed(ActionEvent event) {
  if(wordwrap) wordwrap = false;
  else wordwrap = true;
  textArea.setLineWrap(wordwrap);
  frame.repaint();
}

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

【问题讨论】:

  • 尝试textArea.revalidate(),而不是在框架上重绘。
  • @markspace 好吧,谢谢.revalidate() 工作正常!!!

标签: java swing user-interface components updates


【解决方案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();)

【讨论】:

    【解决方案2】:

    仅供参考,在我有机会对其进行测试后,没有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 );
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      • 2012-09-22
      相关资源
      最近更新 更多