自定义JLabel清理

时间:2011-08-24 17:39:45

标签: java swing jlabel

我每次都需要在textField Action上清理labelResult,但是第一次在字符串前添加'null'然后 - 在之后打印新字符串。请帮忙。

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();

    }
}

2 个答案:

答案 0 :(得分:1)

@Tim我知道在关于JComboBox的官方教程中使用了ActionListener,但是对于从JComboBox到GUI的任何操作都更好地查找ItemListener,你有两个状态(总是被调用两次,但你可以通过包装到if ... else来过滤两个选项SELECTED / DESELECTED)

并且您的代码应该只是

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);

答案 1 :(得分:0)

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