gpt4 book ai didi

java - 需要一些有关 java 中 GUI 的帮助

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

我正在java中的GUI上工作,并且被移动对象卡住了。

请访问这个 YouTube 视频,我为你们制作了一个简短的演示,看看我正在尝试做什么。我对 GUI 很陌生,因为我从未被教过如何使用 GUI。

这是链接:http://www.youtube.com/watch?v=up1LV5r-NSg

最佳答案

我发现您正在使用 GUI 设计器。我强烈建议“手动”构建 GUI,在这种情况下,我的代码会更清晰(我并不是说所有 GUI 设计者都会生成糟糕的代码,但它几乎总是难以阅读,并且在不使用的情况下编辑它会很困难)完全相同的 GUI 设计器)。一旦您对手动 GUI 设计感到满意,就可以尝试 GUI 设计器,看看什么让您更舒服。

参见:http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

就您而言,您可以创建 BorderLayout ,在面板/框架的“南边”,您可以放置​​一个带有 FlowLayout 的面板。将其组件向左对齐。然后使用 FlowLayout 将按钮添加到面板。

一个小演示:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

public class LayoutDemo extends JFrame {

LayoutDemo() {
super("LayoutDemo");
super.setSize(400, 200);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createGUI();
super.setVisible(true);
}

private void createGUI() {
// set the layout of this frame
super.setLayout(new BorderLayout());

// create a panel to put the button on
final JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

// create a text area to put in the center
final JTextArea textArea = new JTextArea();

// create the search button
final JButton searchButton = new JButton("search");

// add a listener to the button that add some text to the text area
searchButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText(textArea.getText() + "pressed search on " + (new Date()) + "\n");
}
});

// add the button to the bottom panel
bottomPanel.add(searchButton);

// wrap a scroll-pane around the text area and place it on the center of this frame
super.add(new JScrollPane(textArea), BorderLayout.CENTER);

// put the bottom panel (containing the button) on the 'south' of this frame
super.add(bottomPanel, BorderLayout.SOUTH);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LayoutDemo();
}
});
}
}

产生:

alt text http://img689.imageshack.us/img689/5874/guiq.png

<小时/>

编辑

要将按钮向上移动一点,请使用构造函数new FlowLayout(FlowLayout.LEFT, int hgap, int vgap)

其中 hgap 是左右组件之间的间隙(以像素为单位),vgap 是上下组件之间的间隙(以像素为单位)。

尝试:

final JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 10));

请注意,按钮和文本区域之间的空间也略有增加!

关于java - 需要一些有关 java 中 GUI 的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2918743/

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