开发者

Custom JLabel Cleanup

开发者 https://www.devze.com 2023-03-30 17:38 出处:网络
I need to clean my labelResult each time on textField Action, but on the first time it adds \'null\' in front of string and then - prints new string right after. Please help.

I need to clean my labelResult each time on textField Action, but on the first time it adds 'null' in front of string and then - prints new string right after. Please help.

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 JTe开发者_运维问答xtField("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();

    }
}


@Tim I know that in official tutorial about JComboBox is used ActionListener, but for any of actions from JComboBox to the GUI is better look for ItemListener, there you are two states (always be called twice, but you can filtering between thes two options SELECTED / DESELECTED by wraping to the if ... else)

and your code should be only

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


Without the code to EventProcessing.action() it's hard to determine, but I would guess you attempt to concatenate two strings, the first of which is null. Null strings get converted to the literal string "null."

0

精彩评论

暂无评论...
验证码 换一张
取 消