我创建了一个自定义组件InOutList
,它扩展了JComponent
,并且我想将其添加到该JFrame
上。但是它没有出现。
这是自定义组件类:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class InOutLists extends JComponent{
GridBagConstraints gbc = new GridBagConstraints();
JPanel backPanel, p1;
JLabel label;
JButton btn;
InOutLists(){
setBackground(new Color(51, 102, 255));
setPreferredSize(new Dimension(100, 100));
backPanel = new JPanel(new GridBagLayout());
p1 = new JPanel();
label = new JLabel("Label 1");
btn = new JButton("Back");
p1.add(btn);
p1.add(label);
gbc.gridx = 0;
gbc.gridy = 0;
backPanel.add(p1, gbc);
}
}
这是主要班级:
import java.awt.Dimension;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class CCMain extends JFrame{
CCMain(){
super("League Management");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1080, 780);
setPreferredSize(new Dimension(1080, 700));
setMaximumSize(new Dimension(1080, 780));
setVisible(true);
InOutLists iol = new InOutLists();
add(iol, BorderLayout.CENTER);
}
public static void main(String[] args) {
new CCMain();
}
}
答案 0 :(得分:0)
如果出于某些原因您需要backPanel
和p1
,请使用:(请参阅评论更改)
class InOutLists extends JComponent{
InOutLists(){
setBackground(new Color(51, 102, 255));
setPreferredSize(new Dimension(100, 100));
setLayout(new FlowLayout()); //set a layout manager to JComponent
JPanel backPanel = new JPanel(new GridBagLayout());
JPanel p1 = new JPanel();
JLabel label = new JLabel("Label 1");
JButton btn = new JButton("Back");
p1.add(btn);
p1.add(label);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
backPanel.add(p1, gbc);
add(backPanel);//add backPanel to JComponent
}
}
否则,您可以在组件上添加标签和按钮:
class InOutLists extends JComponent{
InOutLists(){
setBackground(new Color(51, 102, 255));
setPreferredSize(new Dimension(100, 100));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JLabel label = new JLabel("Label 1");
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
JButton btn = new JButton("Back");
gbc.gridy = 1;
add(btn, gbc);
}
}