如何在JFrame上设置JPanel?

时间:2014-01-14 11:36:08

标签: java swing jframe jpanel

我有一个名为BoardGUI的类,从JFrame扩展而来,在构造函数中我创建了一个带有两个按钮的JPanel。我已将此面板添加到我的框架中。每当我运行这个程序时,按钮都会变得不可见。当我将鼠标光标放在按钮上时,它们会变得可见。代码如下:

public class BoardGUI extends JFrame {
Play pieces;
JButton a=new JButton("Undo");
JButton r=new JButton("replay");
JPanel jp=new JPanel();

public BoardGUI() {
    pieces = new Play();
    setTitle("Checkers Game");
    setSize(645, 700);
    setVisible(true);

    jp.setLayout(new FlowLayout());
    jp.setPreferredSize(new Dimension(645,35));
    a.setVisible(true);
    r.setVisible(true);
    jp.add(a);
    jp.add(r);
    add(jp,BorderLayout.SOUTH);

我也在我的程序中使用重绘方法。任何人都可以指出我的错误并为此提出任何解决方案吗?

1 个答案:

答案 0 :(得分:5)

  

我在JFrame中有一个名为BoardGUI的类,在构造函数中   制作了一个带有两个按钮的JPanel。我添加了这个面板   进入我的框架。每当我运行这个程序时,按钮都会变得不可见。如   我将鼠标光标放在可见的按钮上。

  • setVisible(true);应该是构造函数中的最后一行代码,因为您已将JComponents添加到已经可见的JFrame

  • 或在将revalidate()添加到可见的Swing GUI

  • 的情况下调用repaint()JComponents
  • 没有理由为标准a.setVisible(true);拨打r.setVisible(true);JComponents,因为JComponents默认与visible(true)进行比较Top Level Containers你需要调用JFrame/JDialog/JWindow.setVisible(true);

编辑

i used the very first suggestion you gave. problem remains the same.) - 例如

enter image description here

来自代码

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyGridLayout {

    private JFrame frame = new JFrame("GridLayout, JButtons, etc... ");
    private JPanel panel = new JPanel(new GridLayout(8, 8));

    public MyGridLayout() {
        for (int row = 0; row < 8; row++) {
            for (int col = 0; col < 8; col++) {
                JButton button = new JButton("(" + (row + 1) + " / " + (col + 1) + ")");
                button.putClientProperty("column", col);
                button.putClientProperty("row", row);
                button.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JButton btn = (JButton) e.getSource();
                        System.out.println(
                                "clicked column : "
                                + btn.getClientProperty("column")
                                + ", row : " + btn.getClientProperty("row"));
                    }
                });
                panel.add(button);
            }
        }
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MyGridLayout myGridLayout = new MyGridLayout();
            }
        });
    }
}