【发布时间】:2019-07-19 17:09:37
【问题描述】:
我有这样的代码,我需要在其中创建一些按钮来自定义正方形。它可以工作,但是在卷起框架后,文本字段会在整个框架中移动,我不知道为什么。我的意思是,当我首先执行程序时,它位于我使用 setBounds() 方法提到的正确位置,但随后它位于正方形上方。那么我该如何解决呢?
import java.awt.*;
import java.awt.event.*;
import java.text.AttributedString;
import javax.swing.*;
import java.awt.font.TextAttribute;
public class Square extends JFrame implements ActionListener {
Button butt1 = new Button("Fill with yellow");
Button butt2 = new Button("Fill with red");
Button butt3 = new Button("Add label");
Button butt4 = new Button("");
Pan contentPane = new Pan();
public Square() {
super("Square");
this.setBounds(200, 100, 670, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(contentPane);
contentPane.setBounds(0, 0, 670, 275);
contentPane.setBackground(Color.BLACK);
add(butt1);
butt1.setBounds(25, 300, 190, 25);
butt1.addActionListener(this);
add(butt2);
butt2.setBounds(235, 300, 190, 25);
butt2.addActionListener(this);
butt3.setBounds(440, 300, 190, 25);
butt3.addActionListener(this);
add(butt3);
add(butt4);
}
@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == butt1) {
contentPane.draw(1);
}
else if (o == butt2) {
contentPane.draw(2);
}
else if (o == butt3) {
contentPane.draw(3);
}
}
public static void main(String[] args) {
Square w = new Square();
w.setVisible(true);
}
}
class Pan extends JPanel {
Graphics g;
Graphics2D g2;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GRAY);
g.drawRect(240, 70, 150, 150);
}
public void draw(int i) {
g = getGraphics();
super.paintComponent(g);
g2 = (Graphics2D) g.create();
switch(i) {
case 1: g2.setColor(Color.yellow);
g2.fillRect(240, 70, 150, 150);
break;
case 2: g2.setColor(Color.red);
g2.fillRect(240, 70, 150, 150);
break;
case 3:
g.setColor(Color.GRAY);
g.drawRect(240, 70, 150, 150);
JTextField text = new JTextField(25);
this.add(text);
Button add = new Button("Add");
add.setBounds(400, 230, 120, 25);
this.add(add);
text.setBounds(240, 230, 150, 25);
Font font = new Font("Veranda", Font.BOLD|Font.ITALIC, 24);
class AddButton extends JPanel implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
AttributedString label = new AttributedString(text.getText());
label.addAttribute(TextAttribute.FONT, font);
label.addAttribute(TextAttribute.FOREGROUND, Color.PINK);
g2.drawString(label.getIterator(), 240, 50);
}
}
AddButton listener = new AddButton();
add.addActionListener(listener);
break;
}
}
}
【问题讨论】:
-
g = getGraphics();在很多层面上都是个坏主意。在油漆通道之外调用super.paintComponent(g);也是一个坏主意。这不是应该如何进行自定义绘画。首先查看Performing Custom Painting 和Painting in AWT and Swing,了解绘画的工作原理以及您应该如何使用它 -
将重量级 (AWT) 组件与轻量级 (Swing) 组件混合也会给您带来问题
标签: java swing awt paintcomponent