在java Jframe中我可以使用复选框从视图中添加/删除Jlabel吗?

时间:2016-03-25 07:28:33

标签: java swing jlabel jcheckbox

我正在创建一个允许我执行哈希的应用程序,在顶部我希望有一组复选框基本上说我有四种不同的哈希类型。选中复选框后,我希望标签显示为显示散列输入的文本。

我附上了一张图片,希望能让我更容易理解我的意思。我这样做的原因是,当最终程序用近10行文本框和标签制作时,它可以减少只显示用户希望看到的那些。This hopefully should explain what I mean.

我已经能够得到它,因此复选框使其可见或不可见但是这样只留下一个空格,其中一行标签曾经是一行而不是一行一行

我现在已添加了我的编码,以便人们可以看到我当前是如何做的,并帮助定义需要修改的位置

import java.awt.*;
import java.awt.event.*;
import java.security.*;
import javax.swing.*;

public class Hasher extends JFrame implements ActionListener {
    String UserInput;
    private JTextField textInputField;
    private static JLabel MD5Hashed,MD5Label;
    private static JCheckBox MD5Check, SHA1Check, SHA256Check, FileCheck;
    private JFrame contentPane;

public Hasher() {
    this.setTitle("Hasher");
    Container contentPane = this.getContentPane();
    contentPane.setLayout(new GridLayout(0,1) );
    contentPane.setBackground(new Color(88,148,202));

    //CheckBoxes
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        JPanel checkBoxPanel = new JPanel();
        MD5Check = new JCheckBox("MD5");
        MD5Check.addActionListener(new ActionListener() {
@Override
            public void actionPerformed(ActionEvent e) {
    boolean Visible = MD5Check.isSelected();
    MD5Hashed.setVisible(Visible);
    MD5Label.setVisible(Visible);
            }
        });
        checkBoxPanel.add(MD5Check);
        SHA1Check = new JCheckBox("SHA-1");
        checkBoxPanel.add(SHA1Check);
        SHA256Check = new JCheckBox("SHA-256");
        checkBoxPanel.add(SHA256Check);
        FileCheck = new JCheckBox("File Hashing");
        checkBoxPanel.add(FileCheck);
        mainPanel.add(checkBoxPanel);
        contentPane.add(mainPanel);


//Entered data to perform hash on
    contentPane.add(new JLabel ("   Enter text to hash"));
    textInputField = new JTextField();
    //HashingProcess inputListener = new HashingProcess( );
    //textInputField.addActionListener(inputListener);
    contentPane.add( textInputField);

//MD5 hash is completed 
    MD5Label = new JLabel( "   Using MD5 the hash is: " );
    contentPane.add( MD5Label);
    MD5Hashed = new JLabel( "??") ;
    contentPane.add( MD5Hashed );
    MD5Hashed.setVisible(false);
    MD5Label.setVisible(false);

}

public static void main(String[] args) {
    Hasher theWindow = new Hasher( );
    theWindow.setSize(400, 400 );
    theWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    theWindow.setVisible(true);

}

}

3 个答案:

答案 0 :(得分:3)

你有两个框架......

public class Hasher extends JFrame implements ActionListener {
    //...
    private JFrame contentPane;
    //..

这会立即引发一个问题,一个实际上是在屏幕上,哪一个你实际上正在与之交互?虽然这可能与您的问题没有直接关系,但这很令人困惑。

作为一般经验法则,不要从JFrame这样的顶级容器扩展,它会将您锁定在一个用例中,并且不会导致混淆。相反,请从JPanel开始,将其添加到JFrame的实例或您喜欢的任何其他容器中。

"主要概率"问题是,Swing很懒。在您告知UI或调整UI大小之前,它不会更新UI。

添加和删除组件时,您需要在容器上调用revalidaterepaint来触发更新 - 这是您的代码中实际出错的地方,您是'重新引用contentPaneprivate JFrame contentPane;而不是contentPane延伸JFrame的{​​{1}} ...请参阅,混淆。

在你的代码周围发生了一些事情,很明显你有很多重复的操作,唯一的核心区别是用于散列文本的算法。

因此,考虑到这一点,我们可以创建一些基本类来完成大部分工作,例如......

Hasher

这只是两个标签,显示提示和结果。结果通过插件算法生成,该算法用于生成所提供文本的散列

算法本身只是一个public class HashPane extends JPanel { private JLabel hashedLabel; private JLabel promptLabel; private HashAlgorithim algorithim; public HashPane(String labelText, HashAlgorithim algorithim) { setOpaque(false); this.algorithim = algorithim; setLayout(new FlowLayout(FlowLayout.LEFT)); promptLabel = new JLabel(labelText); add(promptLabel); hashedLabel = new JLabel("??"); add(hashedLabel); } public void setText(String text) { hashedLabel.setText(algorithim.generateHash(text)); } } ,它定义了基本合同......

interface

然后,您需要创建要使用的每个算法的实现

现在,让一个面板可见/不可见只需将public interface HashAlgorithm { public String generateHash(String from); } JCheckBox相关联,这可以通过一个简单的HashPane来实现......

Map

然后,您可以使用一个public class Hasher extends JPanel { //... private Map<JCheckBox, HashPane> mapPanes; public Hasher() { //... HashPane md5Pane = new HashPane("MD5 hash = ", new NotAMD5Alorithim()); //... HashPane sha1Pane = new HashPane("SHA-1 hash = ", new NotAMSHA1Alorithim()); //.. mapPanes = new HashMap<>(25); mapPanes.put(MD5Check, md5Pane); mapPanes.put(SHA1Check, sha1Pane); //... 来管理所有ActionListener s

JCheckBox

因为我几乎诅咒你的代码......

Hide and Show

public class Hasher extends JPanel {
    //...
    private Map<JCheckBox, HashPane> mapPanes;

    public Hasher() {
        //...
        ActionHandler listener = new ActionHandler();
        for (Entry<JCheckBox, HashPane> entry : mapPanes.entrySet()) {
            entry.getKey().addActionListener(listener);
            entry.getValue().setVisible(false);
        }

    }

    protected class ActionHandler implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JCheckBox cb = (JCheckBox) e.getSource();
            HashPane hashPane = mapPanes.get(cb);
            hashPane.setVisible(cb.isSelected());
            revalidate();
            repaint();
        }

    }

说完这一切之后,我可能想要 import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class Hasher extends JPanel { String UserInput; private JTextField textInputField; private static JCheckBox MD5Check, SHA1Check, SHA256Check, FileCheck; private Map<JCheckBox, HashPane> mapPanes; public Hasher() { setLayout(new BorderLayout()); setBackground(new Color(88, 148, 202)); //CheckBoxes JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); JPanel checkBoxPanel = new JPanel(); MD5Check = new JCheckBox("MD5"); checkBoxPanel.add(MD5Check); SHA1Check = new JCheckBox("SHA-1"); checkBoxPanel.add(SHA1Check); SHA256Check = new JCheckBox("SHA-256"); checkBoxPanel.add(SHA256Check); FileCheck = new JCheckBox("File Hashing"); checkBoxPanel.add(FileCheck); mainPanel.add(checkBoxPanel); add(mainPanel, BorderLayout.NORTH); JPanel centerPane = new JPanel(new BorderLayout()); centerPane.setOpaque(false); JPanel inputPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); inputPane.setOpaque(false); //Entered data to perform hash on inputPane.add(new JLabel("Enter text to hash: ")); textInputField = new JTextField(20); inputPane.add(textInputField); centerPane.add(inputPane, BorderLayout.NORTH); JPanel output = new JPanel(new GridBagLayout()); output.setOpaque(false); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; gbc.gridwidth = GridBagConstraints.REMAINDER; HashPane md5Pane = new HashPane("MD5 hash = ", new NotAMD5Alorithim()); output.add(md5Pane, gbc); gbc.gridx = 0; gbc.gridy++; HashPane sha1Pane = new HashPane("SHA-1 hash = ", new NotAMSHA1Alorithim()); output.add(sha1Pane, gbc); // last pane gbc.gridy++; gbc.weighty = 1; output.add(new JLabel(), gbc); centerPane.add(output); add(centerPane); mapPanes = new HashMap<>(25); mapPanes.put(MD5Check, md5Pane); mapPanes.put(SHA1Check, sha1Pane); //... ActionHandler listener = new ActionHandler(); for (Entry<JCheckBox, HashPane> entry : mapPanes.entrySet()) { entry.getKey().addActionListener(listener); entry.getValue().setVisible(false); } } protected class ActionHandler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { JCheckBox cb = (JCheckBox) e.getSource(); HashPane hashPane = mapPanes.get(cb); hashPane.setVisible(cb.isSelected()); revalidate(); repaint(); } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new Hasher()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public interface HashAlgorithm { public String generateHash(String from); } public class NotAMD5Alorithim implements HashAlgorithm { @Override public String generateHash(String from) { return "bananas"; } } public class NotAMSHA1Alorithim implements HashAlgorithm { @Override public String generateHash(String from) { return "bananas"; } } public class HashPane extends JPanel { private JLabel hashedLabel; private JLabel promptLabel; private HashAlgorithm algorithim; public HashPane(String labelText, HashAlgorithm algorithim) { setOpaque(false); this.algorithim = algorithim; setLayout(new FlowLayout(FlowLayout.LEFT)); promptLabel = new JLabel(labelText); add(promptLabel); hashedLabel = new JLabel("??"); add(hashedLabel); } public void setText(String text) { hashedLabel.setText(algorithim.generateHash(text)); } } } 中的JCheckBox并让HashPane始终可见,只需禁用输出文字......或者根本不打扰并始终拥有所有可用的算法

答案 1 :(得分:0)

更改

public void actionPerformed(ActionEvent e) {
   boolean Visible = MD5Check.isSelected();
   MD5Hashed.setVisible(Visible);
   MD5Label.setVisible(Visible);
}

为:

public void actionPerformed(ActionEvent e) {
    boolean Visible = MD5Check.isSelected();
    MD5Hashed.setVisible(Visible);
    MD5Label.setVisible(Visible);
    contentPane.validate();
    contentPane.repaint();
 }

如果你想删除MD5Hashed和MD5Label,那么就像这样:

{
if(MD5Check.isSelected()){
    MD5Hashed.remove();
    MD5Label.remove();
}
else{
    contentPane.add( MD5Label);
    contentPane.add( MD5Hashed );
}

    contentPane.validate();
    contentPane.repaint();
}

答案 2 :(得分:0)

您需要为所有Events

处理check-box while check/uncheck,
public void actionPerformed(ActionEvent actionEvent) {
       if(all check-box un-checked){
            // someLable.setVisible(false);
       }else if(MD5 checked){
           // peform operation based upon MD5
           // someLable.setVisible(true);
       }
       // likewise for all others
      }