我是编程新手,我目前只是处理一个小问题。我已经查看了我自己如何创建一个按钮,如何使用所有方法和什么不是,但我感到困惑的是,如何实际让按钮出现在屏幕上。这可能是非常容易的,我只是不明白。但有人可以帮助我吗?我创建了3个按钮。 `
Button balance = new Button("Check Balance");
Button deposit = new Button("Deposit");
Button withdraw = new Button("Withdraw");
System.out.println("1. " + balance.getLabel());
System.out.println("2. " + deposit.getLabel());
System.out.println("3. " + withdraw.getLabel());
System.out.print("What would you like to do? ");
我很困惑如何让按钮出现在屏幕上!谢谢。
答案 0 :(得分:4)
你需要
答案 1 :(得分:3)
这是一种丑陋(但很短)的做法 -
public static void main(String[] args) {
JButton balance = new JButton("Check Balance");
JButton deposit = new JButton("Deposit");
JButton withdraw = new JButton("Withdraw");
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
panel.add(balance, BorderLayout.WEST);
panel.add(withdraw, BorderLayout.EAST);
panel.add(deposit, BorderLayout.CENTER);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
答案 2 :(得分:2)
按钮必须放在JFrame
上。简而言之,JFrame
是用于Java Swing应用程序的基本容器或窗口。
公共类ButtonExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
JButton balance = new JButton("Check Balance");
JButton deposit = new JButton("Deposit");
JButton withdraw = new JButton("Withdraw");
frame.setLayout(new FlowLayout());
frame.add(balance);
frame.add(deposit);
frame.add(withdraw);
frame.setVisible(true);
}
});
}
}