gpt4 book ai didi

java - JPanel 和 JButton,不知道如何布局 2 个简单的按钮

转载 作者:行者123 更新时间:2023-11-30 07:13:42 25 4
gpt4 key购买 nike

我从 JPanel 开始,我试图在框架上放置 2 个简单的按钮,我能够放置按钮但不能定位它们,这是我的代码:

JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton but = new JButton("text");
JButton but2 = new JButton("list");

JPanel panel= new JPanel(new GridLayout(1, 2));
panel.setSize(100, 100);
panel.add(but);
panel.add(but2);

frame.add(panel);
frame.setVisible(true);

这是我想要的草图:

what i want

最佳答案

寻找布局填充和边框来解决这个问题。

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

class TwoButtonLayout {

public static void main(String[] args) {
Runnable r = new Runnable() {

@Override
public void run() {
// adjust numbers to need..
JPanel panel = new JPanel(new GridLayout(1, 2, 40, 40));
// adjust numbers to need..
panel.setBorder(new EmptyBorder(20,30,20,30));
panel.setBackground(Color.WHITE);

JButton but = new JButton("text");
JButton but2 = new JButton("list");

panel.add(but);
panel.add(but2);

JOptionPane.showMessageDialog(null, panel);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}

关于java - JPanel 和 JButton,不知道如何布局 2 个简单的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19211153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com