Java 如何将带有按钮的1个图形添加到JFrame?
我的绘画课:例如,我只想画一条简单的线Java 如何将带有按钮的1个图形添加到JFrame?,java,swing,drawing,Java,Swing,Drawing,我的绘画课:例如,我只想画一条简单的线 public class DrawNot1 extends JPanel { private BasicStroke BS = new BasicStroke(2); private int x; private int y; public DrawNot1(int x, int y){ setSize(100, 100); this.x = x; this.y = y; } @Override protected void
public class DrawNot1 extends JPanel {
private BasicStroke BS = new BasicStroke(2);
private int x;
private int y;
public DrawNot1(int x, int y){
setSize(100, 100);
this.x = x;
this.y = y;
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(BS);
g2d.drawLine(x, y, x, y+10);
}
我的JFrame类:
public class Main extends JFrame{
private int x;
private int y;
public Main() {
initUI();
}
public void initUI() {
setSize(600, 500);
setTitle("Points");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new DrawNot1(20, 20));
add(new JButton("button1"));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Main ex = new Main();
ex.setVisible(true);
}
});
}
}
我想在按钮旁边显示我的图形,但没有显示。唯一显示的组件是按钮,我的图形没有
我的最终目标是,当我按下按钮时,我的图形将显示在按钮附近。
JFrame
默认使用边框布局
,将两个组件添加到默认(center
)位置意味着仅显示最后添加的一个组件
尝试将按钮添加到南部
位置
add(new JButton("button1"), BorderLayout.SOUTH);
您还可能会发现重写
DrawDot1
的getPreferredSize
方法并提供合适的值也会产生更好的输出@AltianoGerung是的,这是一个常见的问题;)