我正在开发一个非常非常简单的Java浏览器。我已经完成了大部分工作,但是我无法获得“命中输入发送URL”部分。具体来说,当我使用keyTyped()方法时,我收到此错误:
Browser.java:34: error: ';' expected
public void keyTyped(KeyEvent e){
^
Browser.java:34: error: ';' expected
public void keyTyped(KeyEvent e){
^
我原本以为我在某个地方错过了几个'}'和'{'标签,但是我已经搜索了我的代码,一切似乎都应该是它应该的位置,所以我很难过。
我的代码:
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.*;
import java.net.*;
import java.io.*;
public class Browser extends JFrame {
public Browser(){
setTitle("The next Google Chrome");
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
setSize(600,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new BrowserPanel());
setVisible(true);
}
public String URL;
class BrowserPanel extends JPanel implements KeyListener{
public BrowserPanel()
{
JTextField field = new JTextField(20);
field.addKeyListener(this);
JTextArea area = new JTextArea(30, 50);
JTextArea dummy = new JTextArea();
JScrollPane scroll = new JScrollPane(area);
add(field);
add(scroll);
String response;
String checkTitle = "YA GOOFED.";
String mainBody = "REAL BAD.";
@Override
public void keyTyped(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
try
{
URL = field.getText();
String ind = "http://";
int check = URL.indexOf("http://");
int index = ind.length();
String sub = URL.substring(index);
String filepath = sub.substring(sub.lastIndexOf("/"));
String webaddress = URL.substring(index, URL.lastIndexOf("/"));
if(check == -1)
area.append("This is not a proper URL.\n Please add 'http://' to the beginning of your address and try again.");
else
{
Socket s = new Socket(webaddress, 80);
PrintWriter send = new PrintWriter(s.getOutputStream());
BufferedReader read = new BufferedReader(new InputStreamReader(s.getInputStream()));
send.print("GET " + filepath + " HTTP/1.1\r\n");
send.print("Host: " + webaddress + "\r\n");
send.print("\r\n");
send.flush();
while((response = read.readLine())!= null)
{
dummy.append(response + "\n");
}
checkTitle = dummy.getText();
int title1 = checkTitle.indexOf("<title>");
int title2 = checkTitle.indexOf("</title>");
int body1 = checkTitle.indexOf("<body class="+"\"innerpage\""+">");
int body2 = checkTitle.indexOf("</body>");
String preMainBody = checkTitle.substring(body1, body2);
String preTitle = checkTitle.substring(title1 , title2);
String title = preTitle.substring(7);
mainBody = preMainBody.replaceAll("\\<[^>]*>","");
area.append(mainBody);
setTitle(title);
System.out.println(title);
}
}
catch (IOException i)
{
i.printStackTrace();
}
}
}
}
}
public static void main (String[] args){
new Browser();
}
}
答案 0 :(得分:2)
您实际上是在尝试在构造函数中声明这些方法。
在方法声明开始之前,您需要在某处关闭}
。看起来你已经平衡了大括号,所以你也可能需要从类的末尾删除一个。
很难确切知道你的意图,但我怀疑它会在add(scroll)
和String response
行之间。