0

我试图让 JPanel 显示一系列按钮。在每个按钮上都是与我的数独板值关联的值之一。我已经创建了我的板添加了一个菜单,现在我试图在菜单下方但在板之前显示可选选项......在同一个 Jframe 中。我希望我可以把我所有的按钮放到 JPanel 上,然后把那个面板放到 Frame 上。它将显示 JPanel,但不显示任何按钮。有一次我让面板显示,但它们都没有尺寸,而且有很多。我必须更具体的问题是我使用正确的代码来在我的 JPanel 上显示我的一系列按钮,该代码放置在包含我的数独板的框架中,这也是一系列按钮。

这个最终的工具栏和按钮对于这个单一的 JFrame 来说是否太多了,这就是它不起作用的原因吗?无论如何,这里只是我的 JPanel 工具栏的代码。

class ToolBar extends JPanel {
    // instance initializer (constructor equivalent)

    public ToolBar() {
        super();
        this.setLayout(myLayout);

        myLayout.setAlignment(FlowLayout.TRAILING);
        Button[] panelButton = new Button[size];

        //Rectangle rec = new Rectangle(330,45,BUTTON, BUTTON);
        //setBounds(rec);
        setPreferredSize(new Dimension(330, 45));

        for(int i = 0; i < size; i++) {
            Rectangle r = new Rectangle(12, 12, 22, 22);
            center = new ImageIcon(view.drawSymbol(i));

            panelButton[i]= new Button();
            panelButton[i].setIcon(center);
            panelButton[i].setOpaque(true);
            panelButton[i].setBorder(BorderFactory.createLineBorder(Color.black));
            panelButton[i].setBounds(r);

            this.add(panelButton[i]);
            this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            this.setVisible(true);
        }
    }
};
4

2 回答 2

4

setBounds在工具栏上使用以使其可见,并将背景设置为红色只是为了测试它,用 Swing JButtons 替换 AWT 按钮,我还在按钮上设置了一些文本。我在我的测试代码上注释掉了一些东西以便编译,但把它们放回下面:

class ToolBar extends JPanel {
    // instance initializer (constructor equivalent)

    public ToolBar() {
        super();
        this.setLayout(myLayout);

        myLayout.setAlignment(FlowLayout.TRAILING);
        JButton[] panelButton = new JButton[5];
        this.setBackground(Color.red);
        this.setBounds(0, 0, 200, 200);

        //Rectangle rec = new Rectangle(330,45,BUTTON, BUTTON);
        //setBounds(rec);
        setPreferredSize(new Dimension(330, 45));

        for (int i = 0; i < 5; i++) {
            Rectangle r = new Rectangle(22, 22);                
            panelButton[i] = new JButton();
            panelButton[i].setText("       ");
            panelButton[i].setIcon(new ImageIcon(view.drawSymbol(i)));
            panelButton[i].setOpaque(true);
            panelButton[i].setBorder(BorderFactory.createLineBorder(Color.black));
            panelButton[i].setBounds(r);
            this.add(panelButton[i]);
            this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            this.setVisible(true);
        }
    }
};

我还在下面发布了整个测试代码:

import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author hahahaha
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
        this.add(new ToolBar());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    // End of variables declaration
    class ToolBar extends JPanel {
        // instance initializer (constructor equivalent)

        public ToolBar() {
            super();
            //this.setLayout(myLayout);

            //myLayout.setAlignment(FlowLayout.TRAILING);
            JButton[] panelButton = new JButton[5];
            this.setBackground(Color.red);
            this.setBounds(0, 0, 200, 200);

            //Rectangle rec = new Rectangle(330,45,BUTTON, BUTTON);
            //setBounds(rec);
            setPreferredSize(new Dimension(330, 45));

            for (int i = 0; i < 5; i++) {
                Rectangle r = new Rectangle(22, 22);
                //center = new ImageIcon(view.drawSymbol(i));
                panelButton[i] = new JButton();
                panelButton[i].setText("       ");
                //panelButton[i].setIcon(center);
                panelButton[i].setOpaque(true);
                panelButton[i].setBorder(BorderFactory.createLineBorder(Color.black));
                panelButton[i].setBounds(r);
                this.add(panelButton[i]);
                this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
                this.setVisible(true);
            }
        }
    };
}

查找this.add(new ToolBar());我实例化的行并将您的工具栏添加到我的 JFrame。

一个忠告:

尽可能避免使用 AWT 组件

于 2012-05-07T20:35:15.437 回答
2

不要使用 setPreferredSize 或 setBounds;让 LayoutManager 为您处理位置和尺寸。

根据您的需要,您可能需要考虑使用 JToolBar 而不是自己实现。

于 2012-05-07T20:27:36.683 回答