【发布时间】:2017-08-29 12:15:24
【问题描述】:
我有一个 JFrame,里面有几个按钮和文本字段。我正在使用绝对定位(空布局)。我尝试创建一个画布来绘制,但是当我尝试将画布添加到容器然后添加到框架中时,画布会覆盖所有按钮。我想让按钮旁边的画布都可见。
这是我的代码:
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()。
【问题讨论】:
-
提示:尽管使用绝对定位似乎很诱人:不要!而是允许学习布局管理器的最初痛苦。但请相信我:固定尺寸的框架是上个千年的 ;-)
-
使用borders卢克!
-
Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同的语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
-
@Peacetoletov 你的问题解决了吗?
标签: java swing canvas layout-manager null-layout-manager