java - 在 jFrame 的同一个 x 轴上创建 2 个按钮
问题描述
我下面的 java 代码具有一个图像和一个按钮,我只想添加另一个按钮,该按钮与当前按钮所在的 x 轴位于同一 x 轴上。我不知道该怎么做。我以为我试图操纵 abc.weightx 并对其进行更改,但没有任何效果。我在下面包含了我正在尝试做的事情的图片。
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Main extends JFrame {
public static void main(String[] args0) {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 0.5;
gbc.weighty = 0.4;
gbc.fill = GridBagConstraints.BOTH;
URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
ImageIcon image = new ImageIcon(url);
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel, gbc);
gbc.weightx = 0.9;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.NONE;
JButton b = new JButton("Click Here");
frame.add(b, gbc);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}}
解决方案
您没有设置gridx
and gridy
from your GridBagConstraint
,因此它们可能不会出现在您希望它们出现的位置。
我建议您遵循@AndrewThompson 的建议,将BorderLayout
您的主面板放在该BorderLayout.CENTER
位置,并将您的按钮与您放在该位置JPanel
的 default分开。FlowLayout
BorderLayout.SOUTH
如果你想坚持GridBagLayout
:
- 主面板:
gridx=0
gridy=0
gridwidth=2
weightx=1
weighty=1
- 左键:
gridx=0
gridy=1
- 右键:
gridx=1
gridy=1
我没有发布代码,因为如果您自己尝试一下,您会学到更多。
推荐阅读
- r - 如何避免内容相似的长链
- visual-studio-code - Vs代码未在颤动中显示小部件结束注释
- javascript - 控制层中的传单清洁复选框
- r - 如何在 R 中分组排序这个数据框?
- c++ - 如何定义运算符重载函数来比较来自两个不同类的两个对象?
- javascript - 在 Angular 中的单击和显示场景中使用集合 - Angular 与 Blazor 方法
- node.js - Mongoose FindByIdAndUpdate 的奇怪行为 - 为什么它删除文档而不是更新?
- direct3d12 - D3D12 功能级别 12_2/终极其他功能
- mongodb - 在 MongoDB 聚合中使用 $push 合并对象
- react-native - React Native Expo Animated _reactNative.Animated.interpolate 不是函数