gpt4 book ai didi

java - 如何使用 Jbutton 添加多个按钮

转载 作者:行者123 更新时间:2023-12-02 04:46:58 25 4
gpt4 key购买 nike

我使用 jbutton 编写了这段代码并进行了编译。但是当我运行此代码时,仅显示“buttoneone”,而“quibutton”不显示。这很奇怪,我不明白为什么会发生这种情况。请帮忙。

import java.awt.EventQueue;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.*;

public class SimpleEx extends JFrame {

/**
* Default constructor
* Will be invoked when we create an instance of this class
*/
public SimpleEx() {

initializeUserInterface();
}

/**
* Set up the window/frame just the way we want it
*/
private void initializeUserInterface() {

// set up the frame
setTitle("Frame Title");
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);

// create the buttons
createButtons();

}

/**
* In this method we'll create ALL the buttons we'll use in the application
*/
private void createButtons(){
// Create a button with the label "Quit" and
JButton quitButton = new JButton("Quit");
// set up the action listener
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JButton buttonOne = new JButton("Button 1");
// set up the action listener
buttonOne.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {

}
});
// place the button onto the window
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
GroupLayout g2 = new GroupLayout(pane);
pane.setLayout(gl);
pane.setLayout(g2);

gl.setAutoCreateContainerGaps(true);
g2.setAutoCreateContainerGaps(true);

gl.setHorizontalGroup(gl.createSequentialGroup()
.addComponent(quitButton)
);

gl.setVerticalGroup(gl.createSequentialGroup()
.addComponent(quitButton)
);
g2.setHorizontalGroup(g2.createSequentialGroup()
.addComponent(buttonOne)
);

g2.setVerticalGroup(g2.createSequentialGroup()
.addComponent(buttonOne)
);
}

/**
* Main method called when the application starts up
*/
public static void main(String[] args) {

// Set up the GUI event queue
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
// create the main frame/window and make it visible
SimpleEx ex = new SimpleEx();
ex.setVisible(true);
}
});
}
}

最佳答案

本声明

pane.setLayout(g2);

替换包含退出按钮的布局gl,因为容器只能有一个布局管理器。您可以删除它并执行

gl.setHorizontalGroup(gl.createSequentialGroup()
.addComponent(quitButton).addComponent(buttonOne));
gl.setVerticalGroup(gl.createParallelGroup()
.addComponent(quitButton).addComponent(buttonOne));

关于java - 如何使用 Jbutton 添加多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29594426/

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