只是一個簡單的問題。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