我很難弄清楚為什么其中的按鈕不會顯示?今天早些時候,當我測驗運行程式時,它們出現了,但現在我被困了 2 個小時,試圖讓按鈕再次出現。這也很奇怪,因為面板肯定出現了,因為“歡迎來到 BookListApp”這個短語出現了。
public BookListUI() {
textPrompt.setText("Welcome to the BookListApp, fellow bookworm. Start storing your books immediately!");
textPrompt.setBounds(WIDTH / 2 - 300, 50,500,100);
frame = new JFrame();
panel = new JPanel();
panel.setLayout(null);
panel.setSize(WIDTH, HEIGHT);
panel.add(textPrompt);
addButtons();
frame.setSize(WIDTH, HEIGHT);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("BookList Application");
frame.setVisible(true);
}
public void addButtons() {
panel.add(new JButton("Finished books"));
panel.add(new JButton("Favorite books"));
panel.add(new JButton("Search by genre"));
panel.add(new JButton("Save all your books!"));
panel.add(new JButton("Load your BookList Application"));
panel.add(new JButton("Exit application"));
}
public static void main(String[] args) {
new BookListUI();
}
uj5u.com熱心網友回復:
使用一個或多個適當的布局管理器。有關更多詳細資訊,請參閱
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class BookListUI {
JLabel textPrompt = new JLabel("Welcome to the BookListApp, fellow bookworm. Start storing your books immediately!", JLabel.CENTER);
public BookListUI() {
JFrame frame = new JFrame();
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(new EmptyBorder(32, 32, 32, 32));
frame.setContentPane(contentPane);
frame.add(textPrompt, BorderLayout.NORTH);
JPanel menuPane = new JPanel(new GridLayout(-1, 1));
menuPane.setBorder(new EmptyBorder(32, 32, 0, 32));
addButtons(menuPane);
frame.add(menuPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setTitle("BookList Application");
frame.setVisible(true);
}
public void addButtons(Container container) {
container.add(new JButton("Finished books"));
container.add(new JButton("Favorite books"));
container.add(new JButton("Search by genre"));
container.add(new JButton("Save all your books!"));
container.add(new JButton("Load your BookList Application"));
container.add(new JButton("Exit application"));
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new BookListUI();
}
});
}
}
uj5u.com熱心網友回復:
如果您使用絕對布局 (panel.setLayout(null);) 那么您必須指定按鈕的邊界可見:
button.setBounds(200, 200, 300, 30);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/445634.html
