我已将我的代码的相关部分包含在内以供审核。目前,当我运行它时,我看到的是一个没有我面板的大灰色JFrame。我之前有一个面板工作,但是当我添加另一个面板时,第一个面板会消失。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class StudyWindow
{
public StudyWindow()
{
//create frame to contain panels
JFrame frame = new JFrame("Leitner");
frame.setVisible(true);
frame.setSize(1000, 1000);
frame.setResizable(false);
//add main panel to house sub-panels
JPanel mainPanel = new JPanel();
BorderLayout mgr = new BorderLayout();
mainPanel.setLayout(mgr);
mainPanel.setSize(950, 950);
mainPanel.setBackground(Color.WHITE);
//add top text panel that shows either front or back of card
//not yet implemented
//add middle text panel for user to enter response
JPanel panel2 = new JPanel ();
JTextField response = new JTextField(10);
panel2.add(response);
mainPanel.add(panel2, BorderLayout.CENTER);
//add bottom panel with buttons and add action listeners to them
JPanel panel3 = new JPanel ();
JButton a = new JButton("Do not know");
JButton b = new JButton("Flip Card");
JButton c = new JButton("I know");
JButton d = new JButton("Exit");
panel3.add(a);
panel3.add(b);
panel3.add(c);
panel3.add(d);
a.addActionListener(new myActionListener());
b.addActionListener(new myActionListener());
c.addActionListener(new myActionListener());
d.addActionListener(new myActionListener());
mainPanel.add(panel3, BorderLayout.SOUTH);
}
}
答案 0 :(得分:1)
您需要在框架中添加mainPanel
。像,
mainPanel.add(panel3, BorderLayout.SOUTH);
frame.add(mainPanel); // <-- add this.
另外,正如@MadProgrammer在他的评论中指出的那样,frame.setVisible(true);
移动到构造函数的末尾。基本上,在完成添加元素并设置frame.setVisible(true);
之前,请不要致电Frame
。
答案 1 :(得分:1)
frame.setVisible(true);
并将其移至构造函数的末尾frame.add(mainPanel
)setSize
在面板上毫无意义,因为它们将根据布局管理员的需求进行更新pack
代替setSize
以获取更多内容,但请确保在调用之前先添加了所有组件。JPanel
不透明(panel2
覆盖mainPanel
的整个区域