为什么第一个代码没有在JPanel周围放置边框,而第二个代码呢?我看不到边框代码的任何差异。在第一个我正在研究蛇。第二个是我在这里发布的一个例子,但事实证明它有效。
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ts {
public static void main(String[] args) {
MyJFrame frame1 = new MyJFrame();
}
static class MyJFrame extends JFrame{
public MyJFrame (){
setTitle("Snake Build: Dev 0.2");
setBounds(200,100,600,500);
setResizable(false);
setLayout(null);
Container cp = getContentPane();
JPanel settings = new JPanel();
settings.setBounds(200, 100, 200, 200);
settings.setBorder(BorderFactory.createRaisedBevelBorder());
//exsists but cant be seen border working?
settings.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent arg0) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
System.out.println("entered");
}
@Override
public void mouseExited(MouseEvent arg0) {
System.out.println("exited");
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
cp.add(settings);
settings.setVisible(true);
JButton test = new JButton("test");
test.setBounds(10, 20, 30, 30);
settings.add(test);
test.setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g)
{
}
}
}
第二件确实给出了边框
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ts {
public static void main(String[] args) {
MyJF frame1 = new MyJF();
}
static class MyJF extends JFrame{
public MyJF(){
setBounds(50,50,500,200);
setLayout(null);
setResizable(false);
Container cp = getContentPane();
JPanel settings = new JPanel();
settings.setBounds(20,20,100,100);
settings.setBorder(BorderFactory.createRaisedBevelBorder());
JButton JB = new JButton("hey");
JB.setBounds(10, 10, 50, 50);
settings.add(JB);
add(settings);
settings.setVisible(true);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
}
答案 0 :(得分:3)
不想陈述显而易见但你用空代码块覆盖JFrame.paint(Graphics)
,因此你会发现问题。如果删除该部分,它将按预期工作。
考虑以下建议:
JFrame.paint(Graphics)
,而是覆盖JComponent.paintComponent(Graphics)
中包含的组件上的JFrame
以进行自定义绘画。在这两种情况下,您通常也应该调用super
方法LayoutManager
并忘记setBounds/setLocation/setSize
(并且不要尝试将其替换为set-Min/Max/Pref-Size
)JFrame
。只有在添加frame-behavior JFrame