gpt4 book ai didi

java - 如何更改 JPanel 中 JButton 的大小,整个 JFrame 的大小为 "spread"

转载 作者:行者123 更新时间:2023-12-01 19:12:43 25 4
gpt4 key购买 nike

所以我有一个问题,因为我的 JButton 太大了,我需要更改它们的大小,例如小矩形或正方形。现在它们看起来像钢琴键。

这是我的粘贴,你们能帮忙吗? :)我尝试了 SetSize 或 SetDimension 或所有可用的方法,但没有成功。我还没有在溢出这里找到相关主题。你怎么认为?

package sg;

import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SG extends JFrame {

JPanel pn1;
JPanel pn2;
JPanel pn3;
JPanel pn4;
JButton[] buttony = new JButton[12];
JButton start;

SG() {

super();


setSize(1000, 900);
setResizable(false);

pn1 = new JPanel();
pn2 = new JPanel();

pn1.setLayout(new GridBagLayout());
pn2.setLayout(new GridLayout(2,6));

start = new JButton("Start");
start.addActionListener(new B1());
pn1.add(start);


for (int i = 0; i < 12; i++) {
buttony[i] = new JButton(Integer.toString(i + 1));
buttony[i].setSize(10, 10);
pn2.add(buttony[i]);
}

add(pn1,BorderLayout.NORTH);
add(pn2,BorderLayout.CENTER);

}

public static void main(String[] args) {
SG adam = new SG();
adam.setVisible(true);
}
private class B1 implements ActionListener {

public void actionPerformed(ActionEvent e) {

Random s = new Random();
int a = s.nextInt(5);
System.out.println(a);
}

}
}

最佳答案

pn2 添加到另一个 JPanel,然后使用 setContentPane 将该面板设置为 JFrame .

完整代码如下:

import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

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

public class SG extends JFrame {

JPanel pn1;
JPanel pn2;
JPanel pn3;
JPanel pn4;
JButton[] buttony = new JButton[12];
JButton start;

SG() {

super();

setSize(1000, 900);
setResizable(false);

pn1 = new JPanel();
pn2 = new JPanel();
JPanel contentPane = new JPanel();

pn1.setLayout(new GridBagLayout());
pn2.setLayout(new GridLayout(2, 6));

start = new JButton("Start");
start.addActionListener(new B1());
pn1.add(start);

for (int i = 0; i < 12; i++) {
buttony[i] = new JButton(Integer.toString(i + 1));
buttony[i].setSize(10, 10);
pn2.add(buttony[i]);
}
contentPane.add(pn2);
setContentPane(contentPane);
add(pn1, BorderLayout.NORTH);
add(pn2, BorderLayout.CENTER);

}

public static void main(String[] args) {
SG adam = new SG();
adam.setVisible(true);
}

private class B1 implements ActionListener {

public void actionPerformed(ActionEvent e) {

Random s = new Random();
int a = s.nextInt(5);
System.out.println(a);
}

}
}

关于java - 如何更改 JPanel 中 JButton 的大小,整个 JFrame 的大小为 "spread",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59457480/

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