【发布时间】:2016-01-22 09:04:15
【问题描述】:
我对 Java 还是很陌生,对于我的课程,我们必须制作一个没有 JEditor 的 Web 浏览器。我只需要弄清楚当用户在 JTextField 中键入时如何使用套接字,然后将其转到该网站。另外,我只应该使用 http:// 而不是 https:// 如果这有影响的话。什么都有帮助!谢谢!
import javax.swing.*;
import java.awt.*;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.Socket;
import java.io.*;
public class WebPanel extends JPanel{
PrintWriter pw;
JTextField text = new JTextField("http://www.");
public WebPanel(){
//trying to connect to the website
try {
Socket s = new Socket(text, 80); //<<<---where the error is thrown
OutputStream os = s.getOutputStream();
pw = new PrintWriter(os, true);
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
//set layout
setLayout(null);
ButtonHandler bh = new ButtonHandler();
text.addActionListener(bh);
text.setBounds(185, 10, 315, 25);
add(text);
//buttons
JButton goButton = new JButton("GO");
goButton.addActionListener(bh);
add(goButton);
goButton.setBounds(500, 10, 75, 25);
JButton backButton = new JButton("BACK");
backButton.addActionListener(bh);
add(backButton);
backButton.setBounds(2, 10, 75, 25);
JButton forwardButton = new JButton("FORWARD");
forwardButton.addActionListener(bh);
add(forwardButton);
forwardButton.setBounds(80, 10, 100, 25);
}
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//buttons for later
if(e.getActionCommand().equals("GO")){
String input = text.getText();
System.out.println("You searched for: " + input);
pw.flush();
}else if(e.getActionCommand().equals("BACK")){
System.out.println("you pressed the back button");
pw.flush();
} else if(e.getActionCommand().equals("FORWARD")){
System.out.println("You pressed the forward button");
pw.flush();
}
}
}
}
}
【问题讨论】:
-
你的问题太宽泛了。这就像问工程师“如何制造汽车?”。把你的问题分解成碎片。获取用户输入。发出 HTTP 请求。显示页面。它有效吗?你在哪里卡住了?
-
分享一些你目前工作的代码,或者你正在尝试工作的代码的 sn-p。如果您可以发布更具体的问题/问题,其他人会更容易提供帮助。
-
我更新了,谢谢你的帮助!
-
那么为什么要把 JTextField 的变量放到 Socket 构造函数中,而不是使用
text.getText()从中获取 String 呢? -
另一件事是,当您使用 Socket 时,您不能使用您在
JTextField中定义的 URL(我的意思是“http://...”)。在 Socket 中,您定义主机名和端口。没有协议,没有相对资源路径。您应该通过写入套接字本身来提供所有这些。
标签: java