【问题标题】:Positioning JButton on JFrame won't show up [duplicate]在 JFrame 上定位 JButton 不会显示 [重复]
【发布时间】:2014-07-23 06:09:18
【问题描述】:

我知道这是可怕的编码,但我迫切需要解决这个问题。我尝试了多种方法来尝试定位按钮,但按钮仍然保持在顶部中心,所有其他按钮都排在其后。

import javax.imageio.ImageIO;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.io.IOException;
import java.net.URL;

public class Template extends JFrame {
/**
* @param args
*/

public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
    JFrame frame = new JFrame("The Impossible Quiz");//Construct JFrame
    frame.setLayout(null);//manual setting for button placement
    frame.setContentPane(new JPanel() {//sets panel as background
        BufferedImage image = ImageIO.read(new URL("https://pbs.twimg.com/media/BoyFVfXIUAA0Tik.png"));//uses url image 
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, 1360, 690, this);//sets image as jframe background
        }
    });


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//closes jframe when press exit
    frame.setSize(1365, 730);//sets size of jframe

    JPanel buttonpanel = new JPanel();//sets panel for all buttons
    buttonpanel.setBounds(0, 0, 1460, 690);//sets placing and sizing of panel
    buttonpanel.setOpaque(false);//makes panel transparent

    JButton next = new JButton ("Start");//contructs correct start button
    next.setBounds(10, 5, 40, 50);
    buttonpanel.add(next);//adds button to panel

    next.addActionListener(new ActionListener()//adds actionlistener to button
    {
        public void actionPerformed(ActionEvent e)
        {
            new Introduction();//continues to next question
        }
    });
    JButton wrongstart = new JButton("Start!!");//constructs wrong start button
    wrongstart.setSize(100, 400);//setes size of button
    buttonpanel.add(wrongstart);//adds button to panel
    wrongstart.addActionListener(new ActionListener()//adds actionlistener to button
    {
        public void actionPerformed(ActionEvent e)
        {
            new Wrong();//direct user to wrong panel

        }
    });

    frame.add(buttonpanel);//adds panel to jframe
    frame.setVisible(true);//sets jframe as visible
}

}

【问题讨论】:

    标签: java swing layout-manager null-layout-manager


    【解决方案1】:

    您的问题是您尝试使用绝对定位将组件(您的 JButton)定位在默认使用 FlowLayout 的容器(包含 JPanel)中,而 FlowLayout 完全忽略了组件边界。一个快速的解决方案是将 JPanel 的布局设置为 null 以允许绝对定位。正确的解决方案是始终避免空布局和绝对定位,而是嵌套 JPanel,每个 JPanel 都使用自己的布局,以创建复杂但灵活且令人愉悦的 GUI。


    您也将 JFrame contentPane 的布局设置为 null ——也不要这样做。
    然后添加一个 JPanel 作为使用默认 FlowLayout 的 contentPane - 不要那样做。让 contentPane 的布局为 BorderLayout。


    编辑
    例如,如果我们将 contentPane 与它的 BorderLayout 分开,并在其顶部添加另一个图像面板,一个使用 GridBagLayout 的图像面板,如果需要,我们可以轻松地将 JButton 定位到 GUI 的左上角。 ....

    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.image.BufferedImage;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class Template2 extends JPanel {
       private static final int PREF_W = 1460;
       private static final int PREF_H = 690;
       private BufferedImage img;
       private JButton startButton = new JButton("Start");
    
       public Template2() {
          setLayout(new GridBagLayout());
    
          // TODO: .... read in your image here
    
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridx = 1;
          gbc.gridy = 1;
          gbc.gridwidth = 1;
          gbc.gridheight = 1;
          gbc.insets = new Insets(5, 10, 0, 0);
          gbc.anchor = GridBagConstraints.NORTHWEST;
          gbc.fill = GridBagConstraints.NONE;
          gbc.weightx = 1.0;
          gbc.weighty = 1.0;
          add(startButton, gbc);
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       @Override
       public void paintComponents(Graphics g) {
          super.paintComponents(g);
          if (img != null) {
             g.drawImage(img, 0, 0, this);
          }
       }
    
       private static void createAndShowGui() {
          Template2 mainPanel = new Template2();
    
          JFrame frame = new JFrame("Some Horrendous Program");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    

    【讨论】:

    • 我已经尝试过这样做,但是一旦我将其设置为 null,我的按钮就会消失。你知道我做错了什么吗?
    • @user3701400:是的,你没有像我建议的那样使用布局管理器。您应该放弃这种绝对定位的概念并使用布局管理器。教程可以在here找到。
    猜你喜欢
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多