只是一个简单的问题。Java Swing - 分组组件
我正在做一个涉及jTextfield,jButton,jLabels的GUI。 是否有可能将这3个组件分组并隐藏起来。只有一次jButton被点击后,这3个组件才会出现?
一个按钮用于创建新组件的类似用法,但在这种情况下,我希望在jButton上单击时隐藏和取消隐藏。
只是一个简单的问题。Java Swing - 分组组件
我正在做一个涉及jTextfield,jButton,jLabels的GUI。 是否有可能将这3个组件分组并隐藏起来。只有一次jButton被点击后,这3个组件才会出现?
一个按钮用于创建新组件的类似用法,但在这种情况下,我希望在jButton上单击时隐藏和取消隐藏。
您可以将所有组件添加到JPanel并更改面板的可见性。 当你这样做时,你应该考虑一个布局,当组件不可见时不使用空间。您可以使用MigLayout并设置hideMode 3.
下面是一个代码示例,显示如何显示/隐藏分组组件,其实现为其他人所建议的JPanel
。即使隐藏,GroupedComponent
也会保留它的大小。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class SimpleTest extends JFrame {
GroupedComponent test = new GroupedComponent("one", "two", "three");
public SimpleTest() {
super("GroupedComponent Example");
JPanel content = (JPanel)getContentPane();
content.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
final JButton hideButton = new JButton(test.getButtonText());
hideButton.setPreferredSize(new Dimension(100,hideButton.getPreferredSize().height));
hideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
test.toggle();
hideButton.setText(test.getButtonText());
}
});
content.add(hideButton);
content.add(test);
}
public static void main(String[] argv) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleTest c = new SimpleTest();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.pack();
c.setVisible(true);
}
});
}
class GroupedComponent extends JPanel {
boolean visible = true;
JTextField field;
JButton button;
JLabel label;
GroupedComponent(String fieldText, String buttonText, String labelText) {
super(new GridLayout(1, 3, 4, 4));
field = new JTextField(fieldText);
button = new JButton(buttonText);
label = new JLabel(labelText);
add(field);
add(button);
add(label);
setBorder(new CompoundBorder(new LineBorder(Color.lightGray), new EmptyBorder(4,4,4,4)));
}
void toggle() {
if(visible) {
visible = false;
field.setVisible(false);
button.setVisible(false);
label.setVisible(false);
} else {
visible = true;
field.setVisible(true);
button.setVisible(true);
label.setVisible(true);
}
}
String getButtonText() {
return visible ? "Hide" : "Show";
}
}
}
它们添加到JPanel并显示/隐藏面板。 – 2013-01-05 17:59:26