[英]How can I have textarea and graphics in the same jpanel?
我有两个类,一个用于图形,一个用于使用textarea通过文本输入的用户。 当我在同一个程序包中运行它们时,只能运行其中一个,如何才能同时运行它们,以便图形将随用户输入一起运行。
这是图形
package pack;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class gui extends JPanel implements Runnable{
Thread t = new Thread(this);
input inputObject = new input();
public int x;
public int y;
public static void main(String args[])
{
new gui();
}
public gui()
{
JFrame f = new JFrame();
System.out.println("::");
f.setTitle("Basic window");
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.add(this);
f.setVisible(true);
f.setFocusable(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.start(); System.out.println(":::");
}
public void run()
{
while(true)
{
try
{
t.sleep(10);
}
catch(Exception e){}
x++;
y++;
repaint();
}
}
public void paint (Graphics g)
{
System.out.println(":D");
g.setColor(Color.red);
g.drawString("hi",x,y);
}
}
这是文字
package pack;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class input extends JPanel implements ActionListener {
protected JTextField textField;
protected JTextArea textArea;
private final static String newline = "\n";
public input()
{
super(new GridBagLayout());
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(5, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
}
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
textArea.append(text + newline);
textField.selectAll();
textArea.setCaretPosition(textArea.getDocument().getLength());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TextDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new input());
frame.pack();
frame.setVisible(true);
}
public static void main (String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
如果要向gui添加输入,请在gui构造函数中创建另一个类的实例,然后将其添加到gui
// in gui()
input my_input = new input();
add(my_input);
提示:班级名称应以大写字母开头。 Tip2:您只能在一个类中拥有main方法,并向其添加其他类。
让我知道您是否了解或需要更多帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.