JComponent - 无法设置背景/边框

时间:2014-06-08 21:16:53

标签: java swing colors jpanel jcomponent

我想在我的基本JComponent中添加JFrame。我的问题是我无法为我的组件设置背景颜色或边框。

JFrame

JPanel drawPanel = new JPanel(new GridBagLayout());
drawPanel.add(new DrawingBoard());
JScrollPane scrollPane = new JScrollPane(drawPanel);
this.add(scrollPane, BorderLayout.CENTER);
this.setVisible(true);

JComponent

private class DrawingBoard extends JComponent {
        ...
        public DrawingBoard() {
        this.setPreferredSize(new Dimension(500, 500));
        this.setBackground(Color.WHITE);     //doesn't work
        this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); //doesn't work
        this.setOpaque(true);
        ...

2 个答案:

答案 0 :(得分:2)

基本上,因为JComponent没有UI委托,所以它永远不会描绘它的背景(它的paintComponent方法基本上什么都不做。)

您可以提供执行所需操作的UI委托,或者只使用JPanel,例如:

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;

public class TestComponent {

    public static void main(String[] args) {
        new TestComponent();
    }

    public TestComponent() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setBackground(Color.WHITE);
            setBorder(new CompoundBorder(
                            BorderFactory.createEmptyBorder(0,10,10,10),
                            BorderFactory.createLineBorder(Color.RED)
            ));
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

答案 1 :(得分:0)

我找到了解决问题的简单方法。我刚刚将Jcomponent添加到Jpanel,然后我将Jpanel添加到Jframe。

    JPanel outer = new JPanel(new GridBagLayout()); 
    JPanel drawPanel = new JPanel(new GridBagLayout());
    drawPanel.add(new DrawingBoard(500,500));
    drawPanel.setBackground(Color.WHITE);
    outer.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
    JScrollPane scrollPane = new JScrollPane(drawPanel);
    outer.add(scrollPane);
    this.add(outer, BorderLayout.CENTER);