您好我正在尝试为我的java程序制作一个gui但是我被卡住了。我已经制作了我的buttonPanel,但我不知道下一步该怎么做。
我设法制作了我的buttonPanel,但我不知道如何继续。请帮帮我。
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@SuppressWarnings("serial")
public class MySwingTry extends JFrame {
JPanel buttonPanel;
public MySwingTry() {
buttonPanel = new JPanel(new GridLayout(8,0,5,0));
JButton addButton = new JButton("Add student");
JButton deleteButton = new JButton("Delete student");
JButton printAllButton = new JButton("Print all");
JButton printNrOfStudentsButton = new JButton("Print nr.");
JButton writeButton = new JButton("Write File");
JButton readButton = new JButton ("Read File");
JButton serializeButton = new JButton("Serialize File");
JButton deserializeButton = new JButton("DeserializeButton");
BoxLayout boxLayout1 = new BoxLayout (buttonPanel, BoxLayout.Y_AXIS);
buttonPanel.setLayout(boxLayout1);
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(printAllButton);
buttonPanel.add(printNrOfStudentsButton);
buttonPanel.add(writeButton);
buttonPanel.add(readButton);
buttonPanel.add(serializeButton);
buttonPanel.add(deserializeButton);
this.add(buttonPanel);
}
// public void actionPerformed(ActionEvent event) {
// if (event.getSource() == myButton)
// myLabel.setText("My button clicked");
// }
public static void main(String[] args) {
MySwingTry first = new MySwingTry();
first.setTitle("First try");
first.setSize(300,500);
first.setDefaultCloseOperation(EXIT_ON_CLOSE);
first.setVisible(true);
}
}
答案 0 :(得分:4)
回答问题的第一部分:
首先,我希望我的所有按钮大小相同,并且它们之间有一点空间。
将JButtons添加到使用带有4个参数的GridLayout的JPanel。前两个参数是行数和列数,接下来的两个参数是水平和垂直间隙。
如,
JPanel buttonPanel = new JPanel();
// below: create a grid layout with 1 row, variable number of columns
// with a 5 points horizontal gap between each component and no vertical gap
buttonPanel.setLayout(new GridLayout(1, 0, 5, 0));
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
//... etc
// now add the buttonPanel to the main GUI
正如我在评论中所述,您似乎试图一次性解决太多问题,而应集中精力尝试解决 一个 小问题一时间,孤立其他人。首先是间隔按钮,然后尝试解决下一步。如果卡住了每一步,请随时来到这里,但请告诉我们您尝试解决这一步,并就您的误解和一步问题提出具体问题。