java jpanel 分层显示_java-JPanel上的组件未显示

我创建了一个JPanel,并对其进行了一些修改.我将其背景更改为渐变颜色,这是该类.

public class JGradientPanel extends JPanel {

private static final int N = 32;

private Color color1, color2;

public JGradientPanel(Color color1, Color color2) {

this.setBorder(BorderFactory.createEmptyBorder(N, N, N, N));

this.color1 = color1;

this.color2 = color2;

}

@Override

public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

//Color color1 = getBackground();

//Color color2 = color1.darker();

int w = getWidth();

int h = getHeight();

GradientPaint gp = new GradientPaint(

0, 0, color1, 0, h, color2);

g2d.setPaint(gp);

g2d.fillRect(0, 0, w, h);

}

}

现在我在面板上添加了一些组件,但是它什么都没有显示,这是代码

public JPanel getMenu() {

JGradientPanel menu = new JGradientPanel(Color.WHITE, Color.white.darker());

int menuHeight = (int) ((int) getHeight() * 0.07);

menu.setPreferredSize(new Dimension(screenWidth,menuHeight));

menu.setLayout(new GridLayout(1,10));

menu.setBackground(Color.LIGHT_GRAY);

//test

JGradientButton test = new JGradientButton("test",Color.GREEN, Color.BLUE);

menu.add(test);

JLabel space = new JLabel(); // first blank space on the menu

space.setBounds(0, 0, menu.getPreferredSize().width - 50, menu.getPreferredSize().height);

space.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.GREEN));

menu.add(space);

JLabel moreSpaces[] = new JLabel[6];

buttons = new JButton[buttonLabels.length];

for(int counter = 0; counter < moreSpaces.length + buttonLabels.length; counter ++ ) {

if(counter < 3) {

buttons[counter] = new JButton(buttonLabels[counter]); //menu buttons

} else {

moreSpaces[counter - 3] = new JLabel(); // the rest of the blank in the menu

}

}

// adding components to menu panel

for(int counter = 0; counter < moreSpaces.length + buttonLabels.length; counter ++){

if(counter < 3) {

buttons[counter].setFocusPainted(false);

menu.add(buttons[counter]);

} else {

menu.add(moreSpaces[counter - 3]);

}

}

return menu;

}

我错过了什么还是做错了吗?我的代码有什么问题?

解决方法:

>在公共类JGradientPanel中覆盖getPreferredSize扩展了JPanel {

> Painting in Swing,由public void paintComponent(Graphics g){默认情况下永远不会返回PreferredSize to JPanel,

> JPanel返回Dimension [0,0];

编辑

标签:paintcomponent,java,swing,jpanel,preferredsize

来源: https://codeday.me/bug/20191009/1878588.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值