2016-05-01 10 views
0

私はこの簡単なテキストエディタプログラムを作ったが、プログラムがを実行中にGUIコンポーネントのプロパティを変更する方法を理解することはできません。これは私のテキストエディタのソースコードの一部であると仮定し :イベントによってJTextAreaのプロパティを更新するにはどうすればよいですか?

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コンポーネントを更新または編集する正しい方法は何ですか?

+0

フレームで再描画の代わりに 'textArea.revalidate()'を試してください。 – markspace

+0

@markspaceまあ、ありがとう.revalidate() 'はうまく動作しています! –

答えて

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を更新し、私が得た後、ちょうどFYI

+0

ありがとう!!それは今働いている.. –

0

(代わりに "フレーム" .revalidate(ののTextAreaを挿入))テストする機会は、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); 
    } 
} 
関連する問題