我有一个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)。 –