I am attempting to make a "messenger"(just for learning really) and am pretty new to Socket/ServerSocket and am currently stuck in making the networking part.
Also, I do know that the ClientNetworking isn't complete. I have tried to finish it but I am stumped.
ServerMain:
public class ServerMain extends JFrame {
int WIDTH = 480;
int HEIGHT = 320;
String writeToConsole;
JPanel mainPanel, userPanel, consolePanel;
JTabbedPane tabbedPane;
JButton launchButton;
JTextArea console;
JTextField consoleInput;
JScrollPane consoleScroll;
public ServerMain() {
super("Messenger Server");
mainPanel = new JPanel();
mainPanel.setLayout(null);
Networking();
createConsolePanel();
userPanel = new JPanel();
userPanel.setLayout(null);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(userPanel, "Users");
tabbedPane.add(consolePanel, "Console");
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ServerMain frame = new ServerMain();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
public void Networking() {
ServerNetworking net;
try {
net = new ServerNetworking();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createConsolePanel() {
consolePanel = new JPanel();
consolePanel.setLayout(null);
console = new JTextArea();
console.setFont(new Font("", Font.PLAIN, 13 + 1/2));
console.setBounds(0, 0, WIDTH, HEIGHT - 100);
console.setEditable(false);
console.setLineWrap(true);
consoleInput = new JTextField(20);
consoleInput.setBounds(0, 0, WIDTH, 25);
consoleInput.setLocation(0, 240);
consoleInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
String input = consoleInput.getText();
if(input.equalsIgnoreCase("/sendmessage")) {
//console.append(input);
console.append("Input who you would like to send the message to:");
consoleInput.setText("");
} if (input.equalsIgnoreCase("/ban")) {
console.append("Who you would like to ban");
consoleInput.setText("");
}
}
});
consolePanel.add(console);
consolePanel.add(consoleInput);
}
public void consoleWrite(String write) {
console.append(write);
}
}
ServerNetworking(Thread):
public class ServerNetworking extends Thread {
private static ServerSocket servSock;
private static final int PORT = 1234;
private static void handleClient() {
Socket link = null;
try {
link = servSock.accept();
Scanner input = new Scanner(link.getInputStream());
PrintWriter output =
new PrintWriter(link.getOutputStream(),true);
int numMessages = 0;
String message = input.nextLine();
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " +
numMessages + ": " + message);
message = input.nextLine();
}
output.println(numMessages + " messages received.");
} catch(IOException ioEx) {
ioEx.printStackTrace();
} finally {
try {
System.out.println( "\n* Closing connection... *");
link.close();
} catch(IOException ioEx) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
public void run() {
System.out.println("Opening port...\n");
try {
servSock = new ServerSocket(PORT);
} catch(IOException ioEx) {
System.out.println("Unable to attach to port!");
System.exit(1);
} do {
handleClient();
} while (true);
}
}
ClientMain:
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane;
JSplitPane friendsPane;
JTextArea messageArea, testArea;
JTextField testField;
Box box;
public ClientMain() {
super("Messenger Client");
Networking();
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void getFriends(String username) {
}
}
ClientNetworking(Thread):
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane;
JSplitPane friendsPane;
JTextArea messageArea, testArea;
JTextField testField;
Box box;
public ClientMain() {
super("Messenger Client");
Networking();
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void getFriends(String username) {
}
}
This is the error I get when I launch the server, then the client:
It shouldn't be saying "Message received" cause I don't actually send a message
Opening port...
Message received.
* Closing connection... *
Exception in thread "Thread-1" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Server.ServerNetworking.handleClient(ServerNetworking.java:29)
at Server.ServerNetworking.run(ServerNetworking.java:53)
I think the problem is the following loop in the ServerNetworking class:
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " +
numMessages + ": " + message);
message = input.nextLine();
}
The problem with this code is that after recieving the complete message from the client the last line of code
message = input.nextLine();
looks for another next line from the message, but since the message has already been consumed, it throws the following exception:
NoSuchElementException - if no line was found
So before reading for the next line you need to make sure that there is next line to be read. This you can do using the
hasNextLine()
method, which will return true if there is next line otherwise false.
if(input.hasNextLine()) {
message = input.nextLine(); // read the next line
} else {
break; // exit the loop because, nothing to read left
}
Related
Below is my full code, it compiles properly within the eclipse IDE, but when I try and export it as a runnable JAR file, it says it exported with errors. Then When I try to run the Jar file, none of the labels or text fields show up, nor does my event handler on the button work. I'm not sure what to change since it compiled properly before it was exported.
public class TaskFrame extends JFrame implements ActionListener {
private JPanel taskPanel, buttonPanel, viewPanel, titlePanel;
private JButton editButton;
private String[] labelNames = {"Notes", "Paging", "Event Mgmt - Early", "Event Mgmt - Late", "Airhub 2DA",
"Airhub 1DA", "GSSD", "GSSI", "GSSRR", "Holdovers", "Radio", "PTI", "Phones 1300", "Publishing"};
private JLabel[] labelArray = new JLabel[labelNames.length];
private JLabel titleLabel = new JLabel("Task Dashboard");
private JTextField[] textArray = new JTextField[labelNames.length];
private String[] namesArray = new String[labelNames.length];
private Font titleFont = new Font("Helvetica", Font.BOLD, 24);
private Color backgroundColor = new Color(255,250,245);
#Override
public void actionPerformed(ActionEvent arg0) {
}
public static void main(String[] args) {
TaskFrame frame = new TaskFrame();
frame.setTitle("Task List");
frame.setSize(300, 450);
frame.setResizable(false);
frame.setVisible(true);
}
public TaskFrame() {
//Create the locked task panel
taskPanel = new JPanel(new GridLayout(14,2,1,2));
buttonPanel = new JPanel(new FlowLayout());
titlePanel = new JPanel(new FlowLayout());
titleLabel.setFont(titleFont);
titlePanel.add(titleLabel, SwingConstants.CENTER);
viewPanel = new JPanel(new FlowLayout());
//create the button object and assign the event handler
editButton = new JButton("Edit Tasks");
editButton.setPreferredSize(new Dimension(100,25));
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!textArray[0].isEditable()) {
for(int i = 0; i < labelNames.length; i++) {
textArray[i].setEditable(true);
}
editButton.setText("Save Tasks");
} else {
try {
PrintWriter writeNames = new PrintWriter("Techs.txt", "UTF-8");
for(int i = 0; i < labelNames.length; i ++) {
writeNames.println(textArray[i].getText());
textArray[i].setEditable(false);
}
writeNames.close();
} catch (FileNotFoundException e1) {
e1.getMessage();
} catch (UnsupportedEncodingException e1) {
e1.getMessage();
}
}
}
});
buttonPanel.add(editButton);
//Loop to create all the viewPanel objects, JLabels and JTextFields
try {
FileReader fr = new FileReader("Techs.txt");
BufferedReader br = new BufferedReader(fr);
for(int i = 0; i < labelNames.length; i++) {
labelArray[i] = new JLabel(labelNames[i] + ": ", SwingConstants.LEFT);
textArray[i] = new JTextField(10);
namesArray[i] = new String();
namesArray[i] = br.readLine();
textArray[i].setText(namesArray[i]);
textArray[i].setEditable(false);
taskPanel.add(labelArray[i]);
taskPanel.add(textArray[i]);
}
} catch (FileNotFoundException e1) {
e1.getMessage();
} catch (IOException e1) {
e1.getMessage();
}
//Assign the defined background color to all panels
titlePanel.setBackground(backgroundColor);
taskPanel.setBackground(backgroundColor);
buttonPanel.setBackground(backgroundColor);
viewPanel.setBackground(backgroundColor);
viewPanel.add(titlePanel, BorderLayout.NORTH);
viewPanel.add(taskPanel, BorderLayout.CENTER);
viewPanel.add(buttonPanel, BorderLayout.SOUTH);
add(viewPanel);
viewPanel.setVisible(true);
}
}
I am trying to make an image gallery just like in the following image but Windows shows images' unnecessary background whereas in Ubuntu it shows correctly.
I use the following code...
public class CommonGalleryPanel extends JPanel implements ActionListener {
public static boolean isGallaryAllowed = false;
private int counter = 0;
private InputStream binaryStream;
private BufferedImage img;
private ImageIcon iconImg;
private JButton[] btns;
private JCheckBox[] checkBox;
private JButton nextButton;
private JButton prevButton;
private ResultSet rs;
private String imageID;
private long lastRecordWas;
private long selectedOrnamentType;
private JPanel[] panels;
private JButton okButton;
private JPanel centerPanel;
private JPanel eastPanel;
private JPanel northPanel;
private JPanel southPanel;
private JComboBox<String> itemsCombo;
private String[] itemsList;
private JButton load;
private JPanel westPanel;
private int rsLen = 0;
private int noOfRows;
private BufferedImage nextButtonImage;
private BufferedImage prevButtonImage;
private static List<Long> listOfSelectedOrnaments;
private Administrator admin;
public static List<Long> getListOfSelectedOrnaments() {
return listOfSelectedOrnaments;
}
public static void setListOfSelectedOrnaments(
List<Long> listOfSelectedOrnaments) {
CommonGalleryPanel.listOfSelectedOrnaments = listOfSelectedOrnaments;
}
public CommonGalleryPanel(Administrator admin) {
this.admin = admin;
try {
setLayout(new BorderLayout());
centerPanel = new JPanel(new FlowLayout());
eastPanel = new JPanel(new GridLayout());
westPanel = new JPanel(new GridLayout());
northPanel = new JPanel(new GridBagLayout());
southPanel = new JPanel(new GridBagLayout());
listOfSelectedOrnaments = new ArrayList<Long>();
itemsList = DatabaseHandler.getOrnamentTypesInString();
itemsCombo = new JComboBox<String>(itemsList);
load = new JButton("Load");
load.addActionListener(this);
load.setActionCommand("loadButton");
northPanel.setBackground(Color.LIGHT_GRAY);
eastPanel.setBackground(Color.LIGHT_GRAY);
westPanel.setBackground(Color.LIGHT_GRAY);
southPanel.setBackground(Color.LIGHT_GRAY);
centerPanel.setBackground(Color.GRAY);
northPanel.add(itemsCombo);
northPanel.add(new JLabel(" "));
northPanel.add(load);
northPanel.add(Box.createRigidArea(new Dimension(0, 50)));
add(northPanel, BorderLayout.NORTH);
try {
nextButtonImage = Utility
.getMyResource("/buttons/next-btn.png");
prevButtonImage = Utility.getMyResource("/buttons/pre-btn.png");
} catch (Exception ex) {
ex.printStackTrace();
}
prevButton = new JButton(new ImageIcon(
prevButtonImage.getScaledInstance(40, 100,
BufferedImage.SCALE_AREA_AVERAGING)));
prevButton.setSize(getMaximumSize());
westPanel.add(prevButton);
add(eastPanel, BorderLayout.EAST);
nextButton = new JButton(new ImageIcon(
nextButtonImage.getScaledInstance(40, 100,
BufferedImage.SCALE_AREA_AVERAGING)));
eastPanel.add(nextButton);
add(westPanel, BorderLayout.WEST);
okButton = new JButton("Demonstrate");
southPanel.add(Box.createRigidArea(new Dimension(0, 50)));
southPanel.add(okButton);
add(southPanel, BorderLayout.SOUTH);
add(centerPanel, BorderLayout.CENTER);
repaint();
revalidate();
setVisible(true);
nextButton.addActionListener(this);
okButton.addActionListener(this);
prevButton.addActionListener(this);
nextButton.setActionCommand("nextButton");
okButton.setActionCommand("okButton");
prevButton.setActionCommand("prevButton");
revalidate();
repaint();
setVisible(true);
} catch (Exception backException) {
backException.printStackTrace();
}
}
public void getImages(ResultSet rs) {
try {
rsLen = 0;
while (rs.next()) {
counter++;
rsLen++;
}
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
noOfRows = DatabaseHandler
.getRowCountOfGivenSubOrnamentType(selectedOrnamentType);
} else {
noOfRows = DatabaseHandler
.getRowCountOfGivenOrnamentType(selectedOrnamentType);
}
checkBox = new JCheckBox[noOfRows + 1];
List<String> listOfImageIds = new ArrayList<String>(counter);
rs.beforeFirst();
while (rs.next()) {
listOfImageIds.add(rs.getString(1));
}
rs.beforeFirst();
int i = 0;
centerPanel.removeAll();
btns = new JButton[10];
panels = new JPanel[10];
while (rs.next()) {
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
binaryStream = rs.getBinaryStream(2);
} else {
binaryStream = rs.getBinaryStream(2);
}
img = ImageIO.read(binaryStream);
iconImg = new ImageIcon(img.getScaledInstance(290, 180,
BufferedImage.TYPE_INT_ARGB));
btns[i] = new JButton(iconImg);
checkBox[i] = new JCheckBox();
checkBox[i].setActionCommand(String.valueOf(rs.getLong(1)));
panels[i] = new JPanel();
btns[i].setBorderPainted(false);
btns[i].setActionCommand(String.valueOf(rs.getLong(1)));
btns[i].setBackground(new Color(0, 0, 0, 0));
btns[i].addActionListener(this);
//btns[i].setOpaque(true);
panels[i].add(btns[i]);
panels[i].add(checkBox[i]);
panels[i].setBackground(Color.LIGHT_GRAY);
centerPanel.add(panels[i]);
lastRecordWas = rs.getLong(1);
System.out.println("lastRecordWas = " + lastRecordWas);
i++;
}
for (int j = 0; j < i; j++) {
final int k = j;
checkBox[j].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (checkBox[k].isSelected()) {
System.out.println("Selected image..."
+ checkBox[k].getActionCommand());
listOfSelectedOrnaments.add(Long
.parseLong(checkBox[k].getActionCommand()));
} else {
System.out.println("Deselected image..."
+ checkBox[k].getActionCommand());
listOfSelectedOrnaments.remove(Long
.parseLong(checkBox[k].getActionCommand()));
}
System.out.println("Selected items list = "
+ listOfSelectedOrnaments);
}
});
}
System.out.println("counter = " + counter);
if (rsLen == 0) {
centerPanel.add(new JLabel("No more images available...."),
BorderLayout.CENTER);
repaint();
revalidate();
}
} catch (SQLException | IOException ex) {
ex.printStackTrace();
}
add(centerPanel, BorderLayout.CENTER);
repaint();
revalidate();
setVisible(true);
}
public String getImageID() {
return imageID;
}
public void setImageID(String imageID) {
this.imageID = imageID;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("nextButton")) {
System.out.println("next button clicked...");
rs = DatabaseHandler.getNext9ItemsByType(lastRecordWas,
selectedOrnamentType);
getImages(rs);
revalidate();
repaint();
} else if (e.getActionCommand().equals("prevButton")) {
System.out.println("prev button clicked...");
rs = DatabaseHandler.getPrev9ItemsByType(lastRecordWas,
selectedOrnamentType);
getImages(rs);
revalidate();
repaint();
} else if (e.getActionCommand().equals("okButton")) {
try {
if (listOfSelectedOrnaments.isEmpty()) {
JOptionPane
.showMessageDialog(null,
"Please Select at least any one ornament to demonstrate...");
} else {
this.admin.setListOfSelectedOrnaments(
listOfSelectedOrnaments, selectedOrnamentType);
System.out.println("list is setteled with Selected images "
+ listOfSelectedOrnaments);
this.setVisible(false);
}
} catch (Exception ee) {
ee.printStackTrace();
}
} else if (e.getActionCommand().equals("loadButton")) {
try {
this.selectedOrnamentType = DatabaseHandler
.getOrnamentIdFromOrnamentName(itemsCombo
.getSelectedItem().toString());
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
rs = DatabaseHandler.getNext9EaringsByType(0l,
this.selectedOrnamentType);
} else {
rs = DatabaseHandler.getNext9ItemsByType(0l,
this.selectedOrnamentType);
}
getImages(rs);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
try {
System.out.println("Selected image = " + e.getActionCommand());
ImageViewer.showImage(Long.parseLong(e.getActionCommand()),itemsCombo.getSelectedItem().toString());
setImageID(e.getActionCommand());
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
}
Basically it works well with Ubuntu then why not on Windows ?
Just a suggestion:
put this lines first in your Main-Method:
public static void main(String[] args)
{
String propertyName = "sun.java2d.noddraw";
System.setProperty(propertyName, "true");
propertyName = "sun.java2d.d3d";
System.setProperty(propertyName, "false");
//YOUR CODE HERE...
}
By doing this, you will TURN OFF usage of direct3D and directDraw.
You can also try to use a different LookAndFeel: (here as example MetalLookAndFeel)
public static void main(String[] args)
{
String propertyName = "sun.java2d.noddraw";
System.setProperty(propertyName, "true");
propertyName = "sun.java2d.d3d";
System.setProperty(propertyName, "false");
try
{
javax.swing.UIManager.setLookAndFeel(MetalLookAndFeel.class.getName());
}
catch (Exception ex)
{
ex.printStackTrace();
}
//YOUR CODE HERE...
}
By default, SystemLookAndFeel will return "WindowsLookAndFeel" (when using Windows)
but on Linux it will return MetalLookAndFeel (or GTKLookAndFeel).
To force Windows to use MetalLookAndFeel (instead of SystemLookAndFeel (which is WindowsLookAndFeel)), you have to use the code above!
When I run the client program I get this error. I checked to see if the port number is being used and already tried changing the port multiple times.
the server uses three classes:
the main and gui
class ServerGui extends Server implements ActionListener
{
public ServerGui() throws Exception
{
JFrame jfrm = new JFrame("Check in Desk");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(500, 500);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);
//menu bar
JMenuBar jmb = new JMenuBar();
JMenu jmView = new JMenu("View");
// items
JMenu jmEdit = new JMenu("Edit");
// items
JMenu jmHelp = new JMenu("Help");
// items
jmb.add(jmView);
jmb.add(jmEdit);
jmb.add(jmHelp);
//add menuBar
jfrm.setJMenuBar(jmb);
}
public void actionPerformed(ActionEvent ae)
{
String comString = ae.getActionCommand();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try{
new ServerGui();
}
catch(Exception e)
{
System.out.println(e + "damn");
}
}
});
}
}
The server class
public class Server extends Thread
{
public Server() throws IOException
{
this.start();
}
public void run()
{
try
{
while(true)
{
ServerSocket socketOnWhichToListenForClients= new ServerSocket(9876);
Socket socketBackToClient = socketOnWhichToListenForClients.accept();
new ClientHandler(socketBackToClient);
}
}
catch(Exception e)
{
System.out.println(e + "in server run class");
}
}
}
client handler
public class ClientHandler extends Thread
{
private Socket socketBackToClient;
public ClientHandler(Socket socket)
{
socketBackToClient = socket;
this.start();
}
public void run()
{
try
{
InputStream is = socketBackToClient.getInputStream();
BufferedReader message = new BufferedReader(new InputStreamReader(is));
String input = message.readLine();
System.out.println(input);
socketBackToClient.close();
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
The client gui
public class ClientGui extends Client implements ActionListener
{
//private String name = "";
public ClientGui() throws Exception
{
name = JOptionPane.showInputDialog("Enter your name.");
if(name.equals(""))
return;
JFrame jfrm = new JFrame("Check in Desk");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(300, 170);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);
jfrm.setResizable(false);
//buttons
Font font1 = new Font("SansSerif",Font.PLAIN, 24);
Font font2 = new Font("SansSerif",Font.PLAIN, 20);
JButton jb1 = new JButton("Help");
jb1.setPreferredSize(new Dimension(100, 100));
jfrm.add(jb1);
JButton jb2 = new JButton("Check In");
jb2.setPreferredSize(new Dimension(125, 100));
jfrm.add(jb2);
jb1.setFont(font1);
jb2.setFont(font2);
//menu bar
JMenuBar jmb = new JMenuBar();
JMenu jmTools = new JMenu("Tools");
JMenuItem jmiName = new JMenuItem("Name");
JMenuItem jmiIP = new JMenuItem("Your IP");
jmTools.add(jmiName);
jmTools.add(jmiIP);
// items
JMenu jmEdit = new JMenu("Edit");
// items
JMenu jmHelp = new JMenu("Help");
JMenuItem jmiAbout = new JMenuItem("About");
jmHelp.add(jmiAbout);
// items
jmb.add(jmTools);
jmb.add(jmEdit);
jmb.add(jmHelp);
//add menuBar
jfrm.setJMenuBar(jmb);
jmiName.addActionListener(this);
jmiIP.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String confirmHelp = "";
String confirmCheckIn = "";
if(ae.getActionCommand().equals("Name"))
JOptionPane.showMessageDialog(null,"Your name is " + getClientName());
if(ae.getActionCommand().equals("Your IP"))
JOptionPane.showMessageDialog(null,"Your IP is " + getIpAddress());
if(ae.getActionCommand().equals("Help"))
{
confirmHelp = JOptionPane.showInputDialog("Are You Sure You Want Help?");
if(confirmHelp != null && confirmHelp.equalsIgnoreCase("yes"))
{
Help();
}
}
if(ae.getActionCommand().equals("Check In"))
{
confirmCheckIn = JOptionPane.showInputDialog("Are You Sure You Want To Check In?");
if(confirmCheckIn != null && confirmCheckIn.equalsIgnoreCase("yes"))
{
CheckIn();
}
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try{
new ClientGui();
Socket socket = new Socket(InetAddress.getLocalHost(), 9876); //new Client(); // add constructor with name or pc numb
}
catch(Exception e)
{
System.out.println("client closed");
}
}
});
}
}
The client
public class Client
{
public String name = "";
Socket clientSocket;
public Client() throws Exception
{
try
{
// clientSocket = new Socket(InetAddress.getLocalHost(), 9);
OutputStream os = clientSocket.getOutputStream();
PrintWriter pwrite = new PrintWriter(os, true);
pwrite.print("yolo");
}
catch(Exception e)
{
//System.out.println("Error cant connect"); add later
}
}
public void Help()
{
System.out.println("you pressed help");
}
public void CheckIn()
{
System.out.println("you pressed Check In");
}
public String getIpAddress()
{
String str = "";
try{
InetAddress ip = InetAddress.getLocalHost();
str = ip.toString();
}
catch(UnknownHostException e)
{
System.out.println("can not find IP address");
}
return str;
}
public String getClientName()
{
return name;
}
}
The problem is that you keep recreating the ServerSocket inside the while loop. Create it once, before the loop.
The problem is at below lines where same port is used in loop to create ServerSocket that results into below exception.
try {
while (true) {
ServerSocket socketOnWhichToListenForClients = new ServerSocket(9876);
}
} catch (Exception e) {
System.out.println(e + "in server run class");
}
Look at at the exception:
java.net.BindException: Address already in use: JVM_Bindin server run class
Don't forget to close the ServerSocket in the end. Use finally block to close it.
i have made an application that loads image from specific directory, loads all images in stack, when i am clicking on next button next image loads.
i have also added JSlider that change Brightness of Loaded Image but it doesn't work.
i don't know why but i am not getting exact problem.
my code :
public class PictureEditor extends JFrame
{
private static final long serialVersionUID = 6676383931562999417L;
String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
Stack<File> pictures ;
JLabel label = new JLabel();
BufferedImage a = null;
float fval=1;
public PictureEditor()
{
JPanel panel = new JPanel();
JMenuBar menubar = new JMenuBar();
JMenu toolsmenu = new JMenu("Tools");
final JSlider slider1;
slider1 = new JSlider(JSlider.HORIZONTAL,0,4,1);
slider1.setToolTipText("Slide To Change Brightness");
slider1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
slider1.setMajorTickSpacing(1);
slider1.setPaintLabels(true);
slider1.setPaintTicks(true);
slider1.setPaintTrack(true);
slider1.setAutoscrolls(true);
slider1.setBounds(50, 55, 200, 50);
slider1.addChangeListener(new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent e)
{
System.out.println("Before");
fval=slider1.getValue();
chgBrt(fval);
repaint();
}
});
TitledBorder title;
title = BorderFactory.createTitledBorder("Operations");
title.setTitleJustification(TitledBorder.LEFT);
JButton RT90 = new JButton("");
JButton RT180 = new JButton("");
JButton RTM90 = new JButton("");
JButton RTM180 = new JButton("");
JButton NEXT = new JButton("");
Image img = null;
Image imgn = null;
try
{
img = ImageIO.read(getClass().getResource("/images/images_Horizontal.png"));
imgn = ImageIO.read(getClass().getResource("/images/next12.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
RT90.setIcon(new ImageIcon(img));
RT180.setIcon(new ImageIcon(img));
RTM90.setIcon(new ImageIcon(img));
RTM180.setIcon(new ImageIcon(img));
NEXT.setIcon(new ImageIcon(imgn));
JPanel buttonPane = new JPanel();
buttonPane.add(slider1);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
buttonPane.setBorder(title);
buttonPane.add(RT90);
buttonPane.add(RT180);
buttonPane.add(RTM90);
buttonPane.add(RTM180);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
NEXT.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
nextImage();
}
});
buttonPane.add(NEXT);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
final File dir = new File("");
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(panel);
String path = file.getSelectedFile().getAbsolutePath();
System.out.println(path);
pictures= getFilesInFolder(path.toString());
Action nextpictureaction = new AbstractAction("Next Picture")
{
private static final long serialVersionUID = 2421742449531785343L;
#Override
public void actionPerformed(ActionEvent e)
{
nextImage();
}
};
setJMenuBar(menubar);
menubar.add(toolsmenu);
toolsmenu.add(nextpictureaction);
panel.add(label,BorderLayout.CENTER);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(1000, 700);
setTitle("PictureEditor");
setVisible(true);
}
public Stack<File> getFilesInFolder(String startPath)
{
File startFolder = new File(startPath);
Stack<File> picturestack = new Stack<File>();
String extension;
int dotindex;
// Go through the folder
for (File file : startFolder.listFiles())
{
extension = "";
dotindex = file.getName().lastIndexOf('.'); // Get the index of the dot in the filename
if (dotindex > 0)
{
extension = file.getName().substring(dotindex + 1);
// Iterate all valid file types and check it
for (String filetype : validpicturetypes)
{
if (extension.equals(filetype))
{
picturestack.add(file);
}
}
}
}
return picturestack;
}
public void nextImage()
{
try
{
a=ImageIO.read(pictures.pop().getAbsoluteFile());
}
catch (IOException e1)
{
e1.printStackTrace();
}
final ImageIcon image = new ImageIcon(a);
label.setIcon(image);
repaint();
}
#SuppressWarnings("null")
public void chgBrt(float f)
{
Graphics g = null;
Graphics2D g2d=(Graphics2D)g;
try
{
BufferedImage dest=changeBrightness(a,(float)fval);
System.out.println("Change Bright");
int w = a.getWidth();
int h = a.getHeight();
g2d.drawImage(dest,w,h,this);
ImageIO.write(dest,"jpeg",new File("/images/dest.jpg"));
System.out.println("Image Write");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public BufferedImage changeBrightness(BufferedImage src,float val)
{
RescaleOp brighterOp = new RescaleOp(val, 0, null);
return brighterOp.filter(src,null); //filtering
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PictureEditor();
}
});
}
}
anyone who can guide me and tell me where i am wrong ??
You may be able to adapt the approach shown in this RescaleTest, which varies the scaleFactor passed to RescaleOp to a value between zero and twice the slider's maximum.
Im making a contact list, and my code compiles and runs, when you add the contact, type or email or phone its supposed to read them to you, the problem I have here is when I add the contacts and press next or previous, first or last it doesnt read the Name Contact, but it reads everything else...does it have to do something with spacing ? here is what I have...thanks
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ContactSystem extends JFrame{
//Specify the size of five string fields in the record
final static int NAME_SIZE = 32;
final static int TYPE_SIZE = 32;
final static int CITY_SIZE = 20;
final static int PHONE_SIZE = 15;
final static int EMAIL_SIZE = 15;
final static int RECORD_SIZE =
(NAME_SIZE + TYPE_SIZE + CITY_SIZE + PHONE_SIZE + EMAIL_SIZE);
//access contact.dat using RandomAccessFile
private RandomAccessFile raf;
//Text Fields
private JTextField jbtName = new JTextField(NAME_SIZE);
private JTextField jbtType = new JTextField(TYPE_SIZE);
private JTextField jbtCity = new JTextField(CITY_SIZE);
private JTextField jbtPhone = new JTextField(PHONE_SIZE);
private JTextField jbtEmail = new JTextField(EMAIL_SIZE);
//Buttons
private JButton jbtAdd = new JButton("Add");
private JButton jbtFirst = new JButton("First");
private JButton jbtNext = new JButton("Next");
private JButton jbtPrevious = new JButton("Previous");
private JButton jbtLast = new JButton("Last");
public ContactSystem(){
//open or create a random access file
try {
raf = new RandomAccessFile("contact.txt", "rw");
}
catch(IOException ex) {
System.out.print("Error: " + ex);
System.exit(0);
}
//Panel p1 for holding labels Name , Type, Email or phone
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3,1));
p1.add(new JLabel("Name Contact"));
p1.add(new JLabel("Email Address"));
p1.add(new JLabel("Type of Contact"));
//Panel jpPhone for holding Phone
JPanel jpPhone = new JPanel();
jpPhone.setLayout(new BorderLayout());
jpPhone.add(new JLabel("Phone"), BorderLayout.WEST);
jpPhone.add(jbtPhone, BorderLayout.CENTER);
//Panel jpEmail for holding Phone
JPanel jpEmail = new JPanel();
jpEmail.setLayout(new BorderLayout());
jpEmail.add(new JLabel("Phone"), BorderLayout.WEST);
jpEmail.add(jbtEmail, BorderLayout.CENTER);
// Panel p2 for holding jpPhone and jpEmail
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(jpPhone, BorderLayout.WEST);
p2.add(jpPhone, BorderLayout.CENTER);
JPanel p3 = new JPanel();
p3.setLayout(new BorderLayout());
p3.add(jbtCity, BorderLayout.CENTER);
p3.add(p2, BorderLayout.EAST);
//panel p4 for holding jtfName, jtfType, and p3
JPanel p4 = new JPanel();
p4.setLayout(new GridLayout(3,1));
p4.add(jbtName);
p4.add(jbtType);
p4.add(p3);
//place p1 and p4 into jpContact
JPanel jpContact = new JPanel(new BorderLayout());
jpContact.add(p1, BorderLayout.WEST);
jpContact.add(p4, BorderLayout.CENTER);
//set panel with line border
jpContact.setBorder(new BevelBorder(BevelBorder.RAISED));
//add buttons to a panel
JPanel jpButton = new JPanel();
jpButton.add(jbtAdd);
jpButton.add(jbtFirst);
jpButton.add(jbtNext);
jpButton.add(jbtPrevious);
jpButton.add(jbtLast);
//add jpContact and jpButton to the frame
add(jpContact, BorderLayout.CENTER);
add(jpButton, BorderLayout.SOUTH);
jbtAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writeContact();
}
});
jbtFirst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (raf.length() > 0) readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtNext.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if (currentPosition < raf.length())
readContact(currentPosition);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
jbtPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if(currentPosition - 2 * RECORD_SIZE > 0)
//why 2 * 2 * RECORD_SIZE? see the the follow-up remarks
readContact(currentPosition - 2 * 2 * RECORD_SIZE);
else
readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long lastPosition = raf.length();
if(lastPosition > 0)
//why 2 * RECORD_SIZE? see the follow up remarks
readContact(lastPosition - 2 * RECORD_SIZE);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
try {
if (raf.length() > 0) readContact(0);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//write a record at the end of file
public void writeContact() {
try {
raf.seek(raf.length());
FixedLengthStringIO.writeFixedLengthString(
jbtName.getText(), NAME_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtType.getText(), TYPE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtCity.getText(), CITY_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtPhone.getText(), PHONE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtEmail.getText(), EMAIL_SIZE, raf);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//read a contact at the specific position
public void readContact(long position) throws IOException{
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtName.setText(phone);
jbtName.setText(email);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ContactSystem frame = new ContactSystem();
frame.pack();
frame.setTitle("Contact System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
fixedlengthstringIO class
import java.io.*;
public class FixedLengthStringIO {
//read fixed number of characters from datainput stream
public static String readFixedLengthString(int size,
DataInput in) throws IOException {
//declare an array of characters
char[] chars = new char[size];
//read fixed number of characters to the array
for(int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String (chars);
}
//write fixed number of characters to a dataoutput stream
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException {
char[] chars = new char[size];
//fill an array of characters from the string
s.getChars(0, Math.min(s.length(), size), chars, 0);
//fill in blank characters in the rest of the array
for (int i = Math.min(s.length(), size); i < chars.length; i++)
chars[i] = ' ';
//create and write a new string padded with blank characters
out.writeChars(new String(chars));
}
}
here is when I type in contact name, type, email etc into the list
and when I press next or previous, or first or last, it doesnt read the name..
Glitch is in your readContact method, change this
public void readContact(long position) throws IOException {
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtPhone.setText(phone);
jbtEmail.setText(email);
}
Also instead of adding separate ActionListner command button you can implement like
public class ContactSystem extends JFrame implements ActionListener
{
.....
jbtAdd.addActionListener(this);
jbtFirst.addActionListener(this);
.....
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Add")) {
//do add stuff
} else if (actionCommand.equals("First")) {
// move first
}
}
}