我创建了两个扩展JPanel的类,并希望在一个Frame中添加这两个类。但我无法做到。任何人都可以帮忙。
我的课程是 - >
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CalButton extends JPanel {
private JButton[] buttons;
private static final String[] buttonNames = { "7", "8", "9", "/", "4", "5",
"6", "*", "1", "2", "3", "-", "0", ".", "=", "+" };
private JPanel buttonPanel;
public CalButton() {
// TODO Auto-generated constructor stub
buttons = new JButton[buttonNames.length];
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 3, 3));
for(int i=0; i<buttonNames.length; i++){
buttons[i] = new JButton(buttonNames[i]);
buttonPanel.add(buttons[i]);
}
}
}
另一类 - &gt;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CalField extends JPanel {
private JPanel panelField;
private JTextField field;
public CalField() {
// TODO Auto-generated constructor stub
panelField = new JPanel();
panelField.setLayout(new GridLayout(1, 1,5,5));
field = new JTextField(20);
panelField.add(field);
}
}
主要课程 - &gt;
public class Calculator {
public static void main(String[] args) {
JFrame application = new JFrame("Calculator");
CalField calField = new CalField();
CalButton calButton = new CalButton();
application.setLayout(new GridLayout(2, 1));
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setSize(400, 450);
application.setVisible(true);
}
}
请任何人友好地解决这个问题。我遇到了这个问题。
答案 0 :(得分:1)
public CalButton() {
// TODO Auto-generated constructor stub
buttons = new JButton[buttonNames.length];
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 3, 3));
for(int i=0; i<buttonNames.length; i++){
buttons[i] = new JButton(buttonNames[i]);
buttonPanel.add(buttons[i]);
}
}
CalButton
类已经是“JPanel”,因为您扩展了JPanel,因此无需创建另一个JPanel。只需将您的按钮添加到课程中:
public CalButton() {
// TODO Auto-generated constructor stub
buttons = new JButton[buttonNames.length];
//buttonPanel = new JPanel();
//buttonPanel.setLayout(new GridLayout(4, 4, 3, 3));
setLayout(new GridLayout(4, 4, 3, 3));
for(int i=0; i<buttonNames.length; i++){
buttons[i] = new JButton(buttonNames[i]);
//buttonPanel.add(buttons[i]);
add(buttons[i]);
}
}
与您的CalcField
类相同,除非在这种情况下您可能不需要设置布局管理器。您可以使用默认的FlowLayout。
然后第二个问题是你永远不会将这些面板添加到框架中:
CalField calField = new CalField();
CalButton calButton = new CalButton();
//application.setLayout(new GridLayout(2, 1));
application.add(calField, BorderLayout.PAGE_START);
application.add(calButton, BorderLayout.CENTER);