好吧标题解释了,基本上setBounds(int x, int y, int width, int height)
方法并不像我想要的那样工作,因为没有显示任何东西。这段代码的目的是从一些文本字段中获取文本,然后关闭该窗口,并将它们转换为JLabel
个对象以显示在屏幕上,但它并没有这样做。以下是一些代码片段:
public class Create implements ActionListener {
private JTextArea t1, t2, t3;
private String s1 = t1.getText();
private String s2 = t2.getText();
private String s3 = t3.getText();
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
dispose();
setVisible(false);
t1 = new JTextArea(7, 17);
t2 = new JTextArea(7, 17);
t3 = new JTextArea(7, 17);
JFrame frame2 = new JFrame();
frame2.add(new Test(s1,s2,s3));
frame2.setTitle("Title");
frame2.setSize(700,500);
frame2.setResizable(true);
frame2.setLocationRelativeTo(null);
frame2.setVisible(true);
}
}
}
新课程Test
:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
@SuppressWarnings("serial")
public class Test extends JPanel implements ActionListener {
private int w = 250, velx = 2, x = 330;
Timer tm = new Timer(50,this);
public Test(String s1, String s2, String s3) {
setText(s1, s2, s3);
}
public void setText(String s1, String s2, String s3) {
JLabel label1 = new JLabel(s1);
label1.setBounds(100, 100, 500, 500);
JLabel label2 = new JLabel(s2);
label2.setBounds(75, 20, 100, 20);
JLabel label3 = new JLabel(s3);
label3.setBounds(100, 20, 100, 20);
}
}
*****字符串不会在矩形*****上绘制
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("something", 300, 50);
g.drawString("something", 50, 100);
g.drawString("something", 50, 150);
}
public void paint(Graphics g){
tm.setInitialDelay(10000);
super.paint(g);
Graphics2D graph2 = (Graphics2D)g;
Shape Rect1 = new Rectangle2D.Float(330, 30, 250, 390);
graph2.setColor(Color.CYAN);
graph2.fill(Rect1);
Shape Rect2 = new Rectangle2D.Float(x, 30, w, 390);
graph2.setColor(Color.RED);
graph2.fill(Rect2);
tm.start();
}
答案 0 :(得分:0)
您实际上需要将这些标签添加到JPanel
,以便它们可以显示
public void setText(String s1, String s2, String s3) {
JLabel label1 = new JLabel(s1);
label1.setBounds(100, 100, 500, 500);
JLabel label2 = new JLabel(s2);
label2.setBounds(75, 20, 100, 20);
JLabel label3 = new JLabel(s3);
label3.setBounds(100, 20, 100, 20);
add(label1);// Add the label to your current JPanel
add(label2);
add(label3);
}
当您需要绝对定位时,您需要将布局明确设置为Null
JPanel#setLayout(null)
<强>更新强>
如何在JLabel上绘制矩形。
覆盖paintComponent
的{{1}}方法。它应该首先调用JLabel
,这样你就得到了JLabel包含的内容,然后在那之后添加你自己的绘图代码。
super.paintComponent