简体   繁体   English

如何更改 Jpanel 的背景颜色

[英]How to change background color of Jpanel

I have the following code, for a small gui.我有以下代码,用于小 gui。 There is supposed to be a visible Panel at the bottom of the screen but it is never colored when i run the program屏幕底部应该有一个可见的面板,但是当我运行程序时它从不着色

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.SwingUtilities;

public class GraphPanel extends JPanel implements ActionListener {

private Graphics g;

public void GraphPanel() {
    setOpaque(true);
    setBackground(Color.white);
    this.setBounds(0, 100, 1000, 325);
    this.paintComponent(g);

    setVisible(true);
}
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.black);
    g.drawLine(40, 120, 40, 300);
}
public void actionPerformed(ActionEvent e) {

}

Have i set this up all correctly?我是否正确设置了这一切?

You are missing a constructor.你缺少一个构造函数。

Implement a constructor like this:实现这样的构造函数:

public GraphPanel(){
     ...
     ...
}

You have a problem in the constructor .你的constructor有问题。

The constructor shall be like below without void :构造函数应如下所示,没有void

    public GraphPanel( )
    {
    ...
    }

If you want to add a colored panel in the bottom you could create new JPanel and setBackground(...) add it into the panel you have already with BorderLayout.SOUTH .如果你想在底部添加一个彩色面板,你可以创建新的JPanelsetBackground(...)将它添加到你已经使用BorderLayout.SOUTH的面板中。 You should set opaque as well.你也应该设置不透明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM