我正在尝试使用复选框,以便可以通过使用 jframe 中窗口顶部的文本框来完全删除或添加 2 个标签(或其他对象)。我可以设法做到这一点,使它们不可见,但希望它们被删除,并且所有其他东西都可以移动到位。这是我到目前为止的代码...
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();
if (Visible == true);{
contentPane.add(MD5Label);
contentPane.revalidate();
contentPane.repaint();
}
if (Visible == false);{
contentPane.remove(MD5Label);
contentPane.revalidate();
contentPane.repaint();
}
}
});
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);
//Row One : 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);
//Row Three: MD5 hash is completed
MD5Label = new JLabel( " Using MD5 the hash is: " );
//contentPane.add( MD5Label);
MD5Hashed = new JLabel( "??") ;
contentPane.add( MD5Hashed );
}
public static void main(String[] args) {
Hasher theWindow = new Hasher( );
theWindow.setSize(400, 400 );
theWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
theWindow.setVisible(true);
}
}
最佳答案
你的问题是,你的 if
语句被忽略,因为它们有一个尾随 ;
if (Visible == true); // <-- This be bad
{
contentPane.add(MD5Label);
contentPane.revalidate();
contentPane.repaint();
}
if (Visible == false);
{
contentPane.remove(MD5Label);
contentPane.revalidate();
contentPane.repaint();
}
所以,基本上每次调用它时,它都会添加和删除组件
相反,你应该做一些更像......的事情
if (Visible)
{
contentPane.add(MD5Label);
contentPane.revalidate();
contentPane.repaint();
}
else
{
contentPane.remove(MD5Label);
contentPane.revalidate();
contentPane.repaint();
}
事实上,它应该只是......
MD5Label.setVisible(Visible);
contentPane.revalidate();
contentPane.repaint();
这与添加/删除组件具有相同的效果
您可能想通读Code Conventions for the Java TM Programming Language ,这将使人们更容易阅读您的代码,也让您更轻松地阅读其他人
在任何人询问之前,我仍然推荐我在您的previous question中建议的结构性改变。
关于java - 尝试通过使用复选框将 jlabel 完全删除/添加到 jframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36305544/