我有一個JFrame和幾個按鈕和文本字段裏面。我正在使用絕對定位(空佈局)。我試圖創建一個畫布來繪製,但是當我嘗試將畫布添加到容器然後放入框架時,畫布會覆蓋所有按鈕。我想讓按鈕旁邊的畫布都可見。如何將按鈕和畫布放入jframe? (Java swing)
這是我的代碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui extends JFrame {
private JLabel labEnterWord;
private JTextField tfWord;
private JButton butOk;
public Gui(String title) {
super(title);
JPanel p = new JPanel();
p.setLayout(null);
//Create components and add them to the container
addComponents(p);
//Add containers to window
getContentPane().add(p);
getContentPane().add(new MyCanvas());
setWindowProperties();
}
private void addComponents(JPanel p) {
labEnterWord = new JLabel("Enter your word:");
labEnterWord.setBounds(100, 60, 200, 30);
labEnterWord.setFont(new Font("Arial", Font.PLAIN, 20));
p.add(labEnterWord);
tfWord = new JTextField();
tfWord.setBounds(100, 100, 100, 25);
tfWord.setFont(new Font("Arial", Font.PLAIN, 14));
p.add(tfWord);
butOk = new JButton("OK");
butOk.setBounds(220, 100, 51, 25);
butOk.addActionListener(new Event());
p.add(butOk);
}
private void setWindowProperties(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setSize(1280, 720);
setResizable(false);
setLocationRelativeTo(null);
}
}
MyCanvas類:
import javax.swing.*;
import java.awt.*;
public class MyCanvas extends JPanel {
public void drawing(){
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(500, 200, 200, 200);
}
}
主類只是調用GUI()。
提示:雖然它似乎很誘人使用絕對定位:不!而不是讓佈局經理學習最初的痛苦。但相信我:固定大小的幀是上一個千年;-) – GhostCat
使用[邊界](https://docs.oracle.com/javase/tutorial/uiswing/components/border.html)盧克! –
Java GUI必須在不同的語言環境中使用不同的PLAF來處理不同的操作系統,屏幕大小,屏幕分辨率等。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –