我如何设计/编码该程序流程?
CardLayout
,但它不能满足我的需求。 JPanel
,当用户单击按钮时,我更改了相关setVisible()
的JPanel
。但这不起作用,或者我无法成功使用它。 JFframe
(左部分始终相同),根据用户选择关闭和打开窗口。这似乎很荒谬... 那么,您能帮我找到解决方案吗?
最佳答案
这是我做的。
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class Imagination extends JFrame {
private JPanel [] contentPanes ;
private JPanel buttonsPanel, stuffPanel ;
private GridLayout layout ;
private JButton [] consecutiveButtons ;
Imagination() {
layout = new GridLayout(0, 2, 0, 1);
setLayout(new GridLayout(1, 2));
contentPanes = new JPanel[3];
for ( int i = 0 ; i < contentPanes.length ; i++ ) {
contentPanes[i] = new JPanel(layout);
contentPanes[i].setBorder(new BevelBorder(BevelBorder.RAISED));
}
addToAllPanes();
buttonsPanel = new JPanel(new GridLayout(0, 1, 0, 5));
consecutiveButtons = new JButton[3];
for ( int i = 0 ; i < consecutiveButtons.length ; i++) {
consecutiveButtons[i] = new JButton("Sample Button "+i);
buttonsPanel.add(consecutiveButtons[i]);
//We will set the name of the button so that
//we can change the panels
consecutiveButtons[i].setName(i+"");
consecutiveButtons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
consecutiveButtonActionPerformed(e);
}
});
}
stuffPanel = new JPanel(new GridLayout(0, 2, 0, 5));
stuffPanel.add(contentPanes[0]);
setSize(450, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(buttonsPanel);
add(stuffPanel);
pack();
}
public static void main(String [] args) {
Imagination i = new Imagination();
i.setVisible(true);
}
private void addToAllPanes() {
for ( int i = 0 ; i <= 10 ; i ++) {
contentPanes[0].add(new JLabel("A Sample Label"));
contentPanes[0].add(new JTextField("A Sample Text Field"));
contentPanes[1].add(new JLabel("Demo Label"));
contentPanes[1].add(new JTextField("A Sample Text Field"));
contentPanes[2].add(new JLabel("Stack"));
contentPanes[2].add(new JTextField("Overflow"));
}
}
private void consecutiveButtonActionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
int id = Integer.parseInt(b.getName());
stuffPanel.removeAll();
stuffPanel.add(contentPanes[id]);
stuffPanel.repaint();
}
}
我使用数组制作了三个按钮和三个面板,并将它们添加到主JFrame中的两个不同面板中。
所有按钮都添加在一个面板中,而包含JTextFields和JTextLabels的面板添加在另一个面板中。
为了控制单击按钮时显示的面板,我设置了按钮的名称并为其添加了一个通用的动作监听器。在其中,我确实删除了所有组件并添加了所需的面板。
然后,我调用repaint()使其在按下按钮时显示。
我是为了提示您的答案。如果您认为找到了答案,请接受