2011-08-24 62 views
2

我需要每次在textField Action上清理我的labelResult,但第一次在字符串前面添加'null',然后 - 在后面打印新的字符串。请帮忙。自定义JLabel清理

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 


public class Frame extends JFrame implements ActionListener { 
    boolean isDirect = true; 
    String[] typeStr = {"direct", "invert"}; 
    JLabel labelTip = new JLabel("Choose 'direct' OR 'invert' to print your next line in direct order or inverted respectively."); 
    JTextField textField = new JTextField("Some text!", 40); 
    JComboBox comboBox = new JComboBox(typeStr); 
    EventProcessing eventProcessing = new EventProcessing(); 
    JLabel labelResult = new JLabel(); 

    public Frame() { 
     setLayout(new BorderLayout()); 
     getContentPane().add(labelTip, BorderLayout.PAGE_START); 
     getContentPane().add(comboBox, BorderLayout.CENTER); 
     getContentPane().add(textField, BorderLayout.AFTER_LINE_ENDS); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     textField.addActionListener(this); 

     pack(); 
    } 

    public void actionPerformed(ActionEvent e) { 
     getContentPane().remove(labelResult); 
     labelResult = new JLabel(); 
     labelResult.setText(""); 
     if (!(comboBox.getSelectedItem()).equals("direct")) { 
      isDirect = false; 
     } 
     else { 
      isDirect = true; 
     } 
     labelResult.setText(eventProcessing.action(isDirect, textField.getText())); 
     getContentPane().add(labelResult, BorderLayout.PAGE_END); 

     pack(); 

    } 
} 

回答

1

@Tim我知道,在官方教程的JComboBox使用ActionListener,但对于任何从JComboBox中的GUI操作是ItemListener更好看,你在两种状态(通常被称为两次,但你可以过滤之间THES两个选项选择/包木窗的IF ... ELSE)

,你的代码应该只

Runnable doRun = new Runnable() { 

    @Override 
    public void run() { 
     labelResult.setText(eventProcessing.action(isDirect, textField.getText())); 
     add(labelResult, BorderLayout.PAGE_END); 
     //1) this.pack(); if you want to re-layout with effect to size of JFrame too 

     //2a revalidate(); 
     //2b plus in most cases 
     //2b repaint(); relayout Container with fitting JComponents inside Container, 
     //2b but without resize of JFrame 
    } 
}; 
SwingUtilities.invokeLater(doRun); 
0

没有EventProcessing.action()的代码很难确定,但我猜你试图连接两个字符串,其中第一个为空。空字符串被转换为文字字符串“null”。

+0

它应该创建一个新的每次取消。 – UnknitSplash

+0

*每次应该创建一个新的*什么*每次调用'eventProcessing.action()'应该创建一个新的'String'? –

+0

textField上的每个动作 – UnknitSplash