0

嘿,这是我的第二篇文章,所以不要生我的气,但我在 java 中遇到了 JPanel 的问题。我正在尝试设置大小和位置,但它不起作用,我尝试了 repaint(); 但这不起作用。有什么帮助吗?

这是我的代码:

package test.test.test;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.TextField;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame  {

  JPanel colorPanel = new JPanel();

  public Display(){
    super("JPanel test");
    setLayout(new FlowLayout());
    add(colorPanel);
    colorPanel.setBackground(Color.CYAN);
    colorPanel.setSize(300, 300);
    repaint();
  } 
}
4

2 回答 2

2

为了以后阅读此问题的任何人的利益,这里有一个简短的、自包含的、正确的示例,用于定义具有背景颜色的 JPanel。

几乎所有时候,您都应该让 Swing 组件布局管理器确定 Swing 组件的大小。在这种情况下,我们定义了 JPanel 的首选大小,因为 JPanel 不包含任何其他 Swing 组件。

JFrame 的默认布局管理器是 BorderLayout。JPanel 位于 BorderLayout 的中心。

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class SimplePanel implements Runnable {

    @Override
    public void run() {
        JFrame frame = new JFrame("JPanel Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel colorPanel = new JPanel();
        colorPanel.setBackground(Color.CYAN);
        colorPanel.setPreferredSize(new Dimension(300, 300));

        frame.add(colorPanel);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new SimplePanel());
    }

}
于 2013-08-07T15:54:16.447 回答
1

使用 Flowlayout 时,您应该设置(添加到面板的组件的)首选大小而不是大小,因为布局管理器将为您处理位置大小。

public class Test extends JFrame  {

  JPanel colorPanel = new JPanel();

  public Display(){
    super("JPanel test");
    getContentPane().setLayout(new FlowLayout());
    colorPanel = new JPanel
    colorPanel.setPreferedSize(new Dimension(300,300));
    colorPanel.setBackground(Color.CYAN);
    getContentPane().add(colorPanel);
    pack();
    repaint();
  } 
}

并且不要忘记将您的 JFrame 设置为可见和大小(使用 pack());)

于 2013-08-07T14:25:11.977 回答