I am creating a java chat application and am having issues with a TextArea and a list in the client GUI. I am using a cardlayout to have the login on one panel and the chat on another.
For some reason though, the TextArea and List are not filling up the center and east of the panel respectively leaving a lot of extra space below them all the way to the button panel I have.
I've tried to mess with the borderlayout for both the TextArea and the list but no success.
Id appreciate any help.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.SwingUtilities;
public class ChatFrame extends Frame{
public ChatFrame(){
//setTitle("Chat Frame");
setSize(700,700);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
add(new ChatPanel(), BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args){
ChatFrame ch = new ChatFrame();
}
}
class ChatPanel extends Panel implements ActionListener, Runnable{
Button connect;
Button disconnect;
int currentCard = 1;
CardLayout cl;
Panel cardPanel;
TextField tf2;
String name;
List l1 = new List();
TextField tf;
TextArea ta;
Socket s;
BufferedReader in;
PrintWriter out;
Thread t;
public ChatPanel(){
setLayout(new BorderLayout());
cardPanel = new Panel();
cl = new CardLayout();
cardPanel.setLayout(cl);
tf = new TextField(" ");
tf.addActionListener(this);
add(tf, BorderLayout.NORTH);
ta = new TextArea();
add(ta, BorderLayout.CENTER);
connect = new Button("Connect");
connect.addActionListener(this);
disconnect = new Button ("Disconnect");
disconnect.addActionListener(this);
disconnect.setEnabled(false);
Panel buttonPanel = new Panel();
buttonPanel.add(connect);
buttonPanel.add(disconnect);
add(buttonPanel, BorderLayout.SOUTH);
l1.addActionListener(this);
//l1.setSize(new Dimension(150, 400));
add(l1,BorderLayout.EAST);
Panel p1 = new Panel();
Panel p2 = new Panel();
tf2 = new TextField(" ");
tf2.addActionListener(this);
add(tf2, BorderLayout.NORTH);
p1.add(tf2);
p2.add(tf);
p2.add(ta);
p2.add(l1);
cardPanel.add(p1, BorderLayout.CENTER);
cardPanel.add(p2, BorderLayout.CENTER);
add(cardPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae){
if((ae.getSource()==connect)){
try{
s = new Socket("localhost", 3000);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(s.getOutputStream(), true);
t = new Thread(this,"Whatever");
t.start();
}catch(UnknownHostException uhe){
System.out.println(uhe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
connect.setEnabled(false);
disconnect.setEnabled(true);
cl.last(cardPanel);
name = tf2.getText();
out.println(name + " has entered the chat");
ChatFrame ch = (ChatFrame) SwingUtilities.getWindowAncestor(this);
ch.setTitle(name);
//l1.add(name);
}
else if(ae.getSource()== disconnect){
out.println(name + " has left the chat");
try{
s.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
disconnect.setEnabled(false);
connect.setEnabled(true);
cl.first(cardPanel);
}
else if (ae.getSource()== tf){
String temp = tf.getText();
tf.setText("");
out.println(name + ": " + temp);
}
}
public void run(){
try{
for(;;){
ta.append(in.readLine() + "\n");
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}
This section of code is incorrect.
add(l1,BorderLayout.EAST);
Panel p1 = new Panel();
Panel p2 = new Panel();
tf2 = new TextField(" ");
tf2.addActionListener(this);
add(tf2, BorderLayout.NORTH);
p1.add(tf2);
p2.add(tf);
p2.add(ta);
p2.add(l1);
A component (l1) can only have a single parent container. Try adding a background color to each panel to more easily check that components are added to a container with the expected layout.
Related
I am very new to Java, but I'm using it for a school project to make a student tracker. I'm just starting with the layout, and am adding students to a file right now. On line 138, I need a way to add a counter every time I click the add button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
File StudentNames = new File("StudentNames.txt");
File StudentGrades = new File("StudentGrades.txt");
File StudentScore = new File("StudentScore.txt");
FileWriter NameFileWriter = new FileWriter("StudentNames.txt");
FileWriter GradeFileWriter = new FileWriter("StudentGrades.txt");
FileWriter ScoreFileWriter = new FileWriter("StudentScore.txt");
FileReader NameFileReader = new FileReader(StudentNames);
FileReader GradeFileReader = new FileReader(StudentGrades);
FileReader ScoreFileReader = new FileReader(StudentScore);
String[] NamesString = new String[] {""};
List<String> NamesList = Arrays.asList(NamesString);
JFrame frame = new JFrame("Tyke Tracking");
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Adding a panel to center the buttons
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints Center = new GridBagConstraints();
Center.gridx = 0;
JButton StudentsButton = new JButton("Students");
panel.add(StudentsButton, Center);
Center.gridx = 1;
JButton PrizesButton = new JButton("Prizes");
panel.add(PrizesButton, Center);
frame.getContentPane().add(panel);
frame.setVisible(true);
//Student Section
JFrame StuFrame = new JFrame("Tyke Tracking Students");
StuFrame.setSize(500,500);
StuFrame.setResizable(false);
StuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel StuPanelLeft = new JPanel();
JTextArea StudentsListed = new JTextArea();
StudentsListed.setEditable(false);
StudentsListed.setPreferredSize((new Dimension(250,500)));
StuPanelLeft.add(StudentsListed);
JPanel StuPanelRight = new JPanel(new GridBagLayout());
GridBagConstraints StuRight = new GridBagConstraints();
StuRight.gridy = 0;
JButton AddStu = new JButton("Add Students");
StuPanelRight.add(AddStu, StuRight);
StuRight.gridy = 1;
JButton EditStu = new JButton("Edit Students");
StuPanelRight.add(EditStu, StuRight);
StuRight.gridy = 2;
JButton Report = new JButton("Get Report");
Report.setPreferredSize(new Dimension(130,23)); //Making it even to other buttons
StuPanelRight.add(Report, StuRight);
StuRight.gridy = 3;
JButton backButton = new JButton("Back");
backButton.setPreferredSize(new Dimension(130,23));
StuPanelRight.add(backButton, StuRight);
StuFrame.getContentPane().add(StuPanelLeft, BorderLayout.WEST);
StuFrame.getContentPane().add(StuPanelRight);
//Adding Students
JFrame Adding = new JFrame("Adding Students");
Adding.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Adding.setSize(200,150);
Adding.setResizable(false);
JPanel AddStuPanel = new JPanel(new GridBagLayout());
JPanel AddStuPanelTop = new JPanel(new GridBagLayout());
GridBagConstraints AddStuGBC = new GridBagConstraints();
AddStuGBC.gridy = 1;
AddStuGBC.fill = GridBagConstraints.HORIZONTAL;
JTextField addNameField = new JTextField();
addNameField.setPreferredSize(new Dimension(150,20));
AddStuPanelTop.add(addNameField, AddStuGBC);
AddStuGBC.gridy = 0;
JLabel nameLabel = new JLabel("Name:");
AddStuPanelTop.add(nameLabel, AddStuGBC);
AddStuGBC.gridy = 2;
JLabel gradeLabel = new JLabel("Grade %:");
AddStuPanelTop.add(gradeLabel, AddStuGBC);
AddStuGBC.gridy = 3;
JTextField addGradeField = new JTextField();
addGradeField.setPreferredSize(new Dimension(150,20));
AddStuPanelTop.add(addGradeField, AddStuGBC);
AddStuGBC.gridy = 4;
JButton addButton = new JButton("Add");
AddStuPanel.add(addButton, AddStuGBC);
AddStuGBC.gridx = 1;
JButton closeButton = new JButton("Close");
AddStuPanel.add(closeButton, AddStuGBC);
Adding.getContentPane().add(AddStuPanelTop, BorderLayout.CENTER);
Adding.getContentPane().add(AddStuPanel, BorderLayout.SOUTH);
Adding.setVisible(false);
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
NameFileWriter.append(addNameField.getText());
NameFileWriter.close();}
catch (IOException ignored) {}
try {
GradeFileWriter.append(addGradeField.getText());
GradeFileWriter.close();}
catch (IOException ignored) {}
//Way to count how many students there are, to write to correct line in files
}
});
closeButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Adding.setVisible(false);
}
});
StudentsButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
StuFrame.setVisible(true);
}
});
backButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
StuFrame.setVisible(false);
frame.setVisible(true);
}
});
AddStu.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Adding.setVisible(true);
}
});
}
}
I tried to name a variable and use a++, but I can't use it and keep adding since it's accessed within an inner variable. If I initiated it inside, then it would initiate it back every time i clicked the button.
Edit: As noted in the comments, Swing is single threaded so thread safety is not a concern with this solution. Nonetheless, using an AtomicInteger here is still an effective way of maintaining the click count from this anonymous class. A class member in the containing class would be a better solution but this is executed from a static context so I hesitate to suggest that.
AtomicInteger atomicInteger = new AtomicInteger(0);
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
NameFileWriter.append(addNameField.getText());
NameFileWriter.close();}
catch (IOException ignored) {}
try {
GradeFileWriter.append(addGradeField.getText());
GradeFileWriter.close();}
catch (IOException ignored) {}
// Way to count how many students there are, to write to correct line in files
// Every time this statement is called, one is added
// to the total and the total is returned
int totalClicks = atomicInteger.addAndGet(1);
}
});
I'm new to java and for some reason I don't know any other way to transfer the data from another frame after pressing submit. For example, it will show the output frame the label and textfield that the user wrote in the first frame like this "Name: "user's name". If you do know please post the code I should put, thank you!
package eventdriven;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDriven extends JFrame {
JPanel items = new JPanel();
JLabel fName = new JLabel("First Name: ");
JLabel lName = new JLabel("Last Name: ");
JLabel mName = new JLabel("Middle Name: ");
JLabel mNum = new JLabel("Mobile Number: ");
JLabel eAdd = new JLabel("Email Address: ");
JTextField fname = new JTextField(15);
JTextField lname = new JTextField(15);
JTextField mname = new JTextField(15);
JTextField mnum = new JTextField(15);
JTextField eadd = new JTextField(15);
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear All");
JButton okay = new JButton("Okay");
JTextArea infos;
JFrame output;
public EventDriven()
{
this.setTitle("INPUT");
this.setResizable(false);
this.setSize(230, 300);
this.setLocation(300, 300);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(fName);
this.add(fname);
this.add(lName);
this.add(lname);
this.add(mName);
this.add(mname);
this.add(mNum);
this.add(mnum);
this.add(eAdd);
this.add(eadd);
submit.addActionListener(new btnSubmit());
this.add(submit);
clear.addActionListener(new btnClearAll());
this.add(clear);
okay.addActionListener(new btnOkay());
this.add(items);
this.setVisible(true);
}
class btnSubmit implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submit)
{
submit.setEnabled(false);
output = new JFrame("OUTPUT");
output.show();
output.setSize(300,280);
output.setTitle("OUTPUT");
output.add(okay);
output.setLayout(new FlowLayout(FlowLayout.CENTER));
}
}
}
class btnClearAll implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == clear)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
class btnOkay implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == okay)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
public static void main(String[] args)
{
EventDriven window = new EventDriven();
}
}
It's not clear what problem you are having displaying a value from one field in another frame. But here's an example of doing that (with fields reduced to just one for demonstration):
public class EventDriven extends JFrame {
private final JTextField nameField = new JTextField(15);
private final JButton submit = new JButton("Submit");
private final JButton clear = new JButton("Clear All");
public EventDriven() {
setTitle("Input");
setLayout(new FlowLayout(FlowLayout.CENTER));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Name: "));
add(nameField);
submit.addActionListener(this::showOutput);
add(submit);
clear.addActionListener(this::clearInput);
add(clear);
pack();
}
private void showOutput(ActionEvent ev) {
submit.setEnabled(false);
JDialog output = new JDialog(EventDriven.this, "Output", true);
output.add(new Label("Name: " + nameField.getText()), BorderLayout.CENTER);
JButton okButton = new JButton("OK");
output.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(bv -> output.setVisible(false));
output.pack();
output.setVisible(true);
}
private void clearInput(ActionEvent ev) {
nameField.setText(null);
submit.setEnabled(true);
}
public static void main(String[] args) {
EventDriven window = new EventDriven();
window.setVisible(true);
}
}
You will also see that I've simplified your action listeners to demonstrate an easier way to respond to user driven event.s
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am getting an error when im trying to write a code to automatically select a tab from tabbed pane when condition is true, but im getting an error with null pointer exception in while im trying to execute the code after compiling it!!
The problem is in the loadData(); method on setSelectedTab();
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
public class GUI extends JFrame implements ActionListener{
private static final long serialVersionUID = 1;
ArrayList<Ship> shiplist= new ArrayList<Ship>();
private int shipcount = 0;
private int index = 0;
private Ship shipob;
private JTextField ShipYear;
private JTextField ShipName;
private JTextField CrewSize;
private JTextField ShipType;
private JTextField NoOfPass;
private JTextField NoOfCabins;
private JTextField PerFull;
private JTextField CabinRate;
private JTextField SizeCat;
private JTextField PerFilled;
private JTextField LiquidType;
private JTextField Capacity;
private ObjectInputStream inStream;
private ObjectOutputStream outStream;
private JTabbedPane tab;
private CruiseShip cruiseShip;
private DryCargoShip dryShip;
private LiquidCargoShip liquidShip;
JLabel message=new JLabel();
public GUI()
{
setSize(2000,300);
setTitle("Ship Data");
Container content= getContentPane();
content.setBackground(Color.GRAY);
content.setLayout(new BorderLayout());
JMenuBar menu=new JMenuBar();
JMenuItem menue= new JMenuItem("Exit");
menue.addActionListener(this);
menu.add(menue);
setJMenuBar(menu);
this.addWindowListener(new WindowDestroyer());
JPanel panel1= new JPanel();
panel1.setBackground(Color.YELLOW);
panel1.setLayout(new GridLayout(2,2));
panel1.add(new JLabel("Ship Name:"));
ShipName= new JTextField(50);
panel1.add(ShipName);
panel1.add(new JLabel("Ship Year:"));
ShipYear= new JTextField(50);
panel1.add(ShipYear);
panel1.add(new JLabel("Crew Size:"));
CrewSize= new JTextField(50);
panel1.add(CrewSize);
panel1.add(new JLabel("Ship Type:"));
ShipType= new JTextField(50);
panel1.add(ShipType);
content.add(panel1, BorderLayout.NORTH);
JPanel panel2= new JPanel();
panel2.setLayout(new BorderLayout());
JPanel panel3= new JPanel();
panel3.setBackground(Color.CYAN);
panel3.setLayout(new FlowLayout());
JButton Button1= new JButton("Next");
Button1.addActionListener(this);
panel3.add(Button1);
JButton Button2= new JButton("Previous");
Button2.addActionListener(this);
panel3.add(Button2);
panel2.add(panel3,BorderLayout.WEST);
panel2.add(message,BorderLayout.EAST);
JTabbedPane tab=new JTabbedPane();
content.add(panel2, BorderLayout.SOUTH);
JPanel cs= new JPanel();
//JPanel z= new JPanel();
cs.setBackground(Color.ORANGE);
cs.setLayout(new GridLayout(2,2));
cs.add(new JLabel("No of Passenger: "));
NoOfPass= new JTextField(25);
cs.add(NoOfPass);
cs.add(new JLabel("No of Cabins: "));
NoOfCabins= new JTextField(25);
cs.add(NoOfCabins);
cs.add(new JLabel("Percentage Full: "));
PerFull= new JTextField(25);
cs.add(PerFull);
cs.add(new JLabel("Cabin Rate: "));
CabinRate= new JTextField(25);
cs.add(CabinRate);
tab.addTab("Cruise Ship", cs);
JPanel ds= new JPanel();
//JPanel x= new JPanel();
ds.setBackground(Color.ORANGE);
ds.setLayout(new GridLayout(1,2));
ds.add(new JLabel("Size Category : "));
SizeCat= new JTextField(25);
ds.add(SizeCat);
ds.add(new JLabel("Percentage Filled : "));
PerFilled= new JTextField(25);
ds.add(PerFilled);
tab.addTab("Dry Cargo Ship", ds);
JPanel ls= new JPanel();
//JPanel y= new JPanel();
ls.setBackground(Color.ORANGE);
ls.setLayout(new GridLayout(1,2));
ls.add(new JLabel("Liquid Type : "));
LiquidType= new JTextField(25);
ls.add(LiquidType);
ls.add(new JLabel("Capacity : "));
Capacity= new JTextField(25);
ls.add(Capacity);
tab.addTab("Liquid Cargo Ship", ls);
content.add(tab,BorderLayout.CENTER);
}
public static void main(String[] args)
{
GUI Gui = new GUI();
Gui.readData();
Gui.loadData();
Gui.index = 0;
Gui.met();
//Gui.shipcount= shiplist.size();
Gui.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Container container = getContentPane();
String string = e.getActionCommand();
if (string.equals("Next"))
{
nextShip();
}
else if (string.equals("Previous"))
{
previousShip();
}
else if (string.equals("Exit"))
{
writeData();
System.exit(0);
}
else
{
System.out.println("Error");
}
}
public void readData()
{
inStream=null;
try
{
inStream= new ObjectInputStream(new FileInputStream("shipdata.dat"));
try {
this.shipcount = 0;
do {
shiplist.add((Ship)inStream.readObject());
shipcount++;
} while (true);
}
catch (EOFException obj1)
{
System.out.println("Entered EOF");
}
catch (ClassNotFoundException obj2)
{
System.out.println("Class Error: " + obj2.getMessage());
}
this.inStream.close();
}
catch (FileNotFoundException obj3)
{
System.out.println("File Error: " + obj3.getMessage());
}
catch (IOException obj4)
{
System.out.println("IO Error in read file data: " + obj4.getMessage());
}
}
public void met()
{
shipcount= shiplist.size();
}
public void loadData() {
shipob = shiplist.get(index);
ShipName.setText(shipob.getShipName());
ShipYear.setText(shipob.getYear());
String a=""+shipob.getCrewSize();
CrewSize.setText(a);
ShipType.setText(shipob.getShipType());
if (shipob.getShipType().equals("Cruise Ship"))
{
System.out.println("In Cruise ship");
cruiseShip = (CruiseShip)shipob;
String b=""+cruiseShip.getCabinRate();
CabinRate.setText(b);
NoOfPass.setText(Integer.toString(cruiseShip.getNoOfPass()));
NoOfCabins.setText(Integer.toString(cruiseShip.getNoOfCabins()));
PerFull.setText(Double.toString(cruiseShip.getPerFull() * 100.0));
tab.setSelectedIndex(0); // ERROR IN SELECT INDEX - NULL POINTER EXCEPTION
}
else if (shipob.getShipType().equals("Dry Cargo Ship"))
{
System.out.println("In Dry ship");
dryShip = (DryCargoShip)shipob;
SizeCat.setText(dryShip.getSize());
String c=" "+dryShip.getPerFilled()*100.0;
PerFilled.setText(c);
try{
tab.setSelectedIndex(1);}
catch(Exception e){
System.out.println(e);
}
}
else if (shipob.getShipType().equals("Liquid Cargo Ship"))
{
System.out.println("In LC ship");
liquidShip = (LiquidCargoShip)shipob;
LiquidType.setText(liquidShip.getLiqType());
Capacity.setText(Integer.toString(liquidShip.getCapacity()));
tab.setSelectedIndex(2);
}
}
public void nextShip() {
if (index == shipcount - 1) {
message.setText("Already at last record ");
}
else {
message.setText("");
index++;
loadData();
}
}
public void previousShip() {
if (index == 0)
{
message.setText("Already at first record ");
}
else
{
message.setText("");
index--;
loadData();
}
}
public void writeData()
{
try {
outStream = new ObjectOutputStream(new FileOutputStream("shipdata.dat", false));
for (Ship ship : shiplist)
{
outStream.writeObject(ship);
}
outStream.flush();
outStream.close();
}
catch (IOException obj1) {
System.out.println("IO Error in writing the data: " + obj1.getMessage());
}
}
}
In the constructor you are initializing a local JTabbedPane and not the one that is declared in the class and accessed in the method loadData.
Please initialize the variable tab in a proper way, i.e.
this.tab=new JTabbedPane();
instead of
JTabbedPane tab=new JTabbedPane();
I've tried different methods to fix this, but apparently nothing works. Because I am new to java I actually don't know if there's something wrong with my code.
I've tried setting the size of the text area that is supposed to go into the SOUTH part of the border layout, but the size is still to small to see.
Anyone know of a solution?
package package1;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SimpleDatabasePanel extends JFrame implements ActionListener {
private JMenuBar menuBar;
private JMenu file;
private JMenuItem save, load, quit;
private JButton add, undo, find, delete, display;
private JScrollPane pane;
private JTable table;
private JPanel panel;
private JTextArea tName, tGNum, tGPA, results;
private JLabel name, gNum, gpa;
private LinkedList list;
public SimpleDatabasePanel(){
setLayout(new BorderLayout());
setTitle("Simple Database");
//setSize(1000,1000);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
file = new JMenu("File");
quit = new JMenuItem("Quit");
save = new JMenuItem("Save");
load = new JMenuItem("Load");
add = new JButton("Add");
undo = new JButton("Undo");
find = new JButton("Find");
delete = new JButton("Delete");
display = new JButton("Display");
tName = new JTextArea();
tGNum = new JTextArea();
tGPA = new JTextArea();
results = new JTextArea(10,20);
name = new JLabel("Name");
gNum = new JLabel("G Number");
gpa = new JLabel("GPA");
list = new LinkedList();
panel = new JPanel();
panel.setLayout(new GridLayout(3, 4, 4, 4));
//frame = new JFrame();
pane = new JScrollPane();
pane.setSize(300, 60);
table = new JTable();
menuBar = new JMenuBar();
menuBar.add(file);
file.add(save);
file.add(load);
file.add(quit);
panel.add(name);
panel.add(tName);
panel.add(undo);
panel.add(add);
panel.add(gNum);
panel.add(tGNum);
panel.add(find);
panel.add(delete);
panel.add(gpa);
panel.add(tGPA);
panel.add(display);
pane.add(results);
add(menuBar, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(pane, BorderLayout.SOUTH);
this.pack();
ButtonListener listener = new ButtonListener();
file.addActionListener(file.getAction());
find.addActionListener(listener);
undo.addActionListener(listener);
save.addActionListener(this);
quit.addActionListener(this);
add.addActionListener(listener);
load.addActionListener(this);
delete.addActionListener(listener);
display.addActionListener(listener);
}
public void actionPerformed(ActionEvent e) {
JMenuItem file = (JMenuItem) e.getSource();
if(file == quit){
System.exit(0);
}
if(file == load){
String filename = JOptionPane.showInputDialog("Enter File Name: ");
(list).load(filename);
}
if(file == save){
String filename = JOptionPane.showInputDialog("Enter File Name: ");
(list).save(filename);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(event.getSource() == add){
}
if(event.getSource() == delete){
}
if(event.getSource() == display){
}
if(event.getSource() == find){
}
if(event.getSource() == undo){
}
}
}
public static void main(String[] args){
SimpleDatabasePanel s =new SimpleDatabasePanel();
s.setVisible(true);
s.setResizable(false);
}
}
change this
pane.add(results);
to this
pane.setViewportView(results);
or this
pane.getViewport().add(results, null);
use setViewportView or getViewport().add to set component to jscrollpane.also you can pass component (jtextarea ) to constructor of jscrollpane.read more about jscrollpane here
output
I have a problem with setting position for one of the elements (the image). I cannot align it to right-bottom of the screen. I tried to use different layouts but I can't make it to work exactly like I want it.
Below is the url to view how it looks now. The image is in the right-bottom but it's a new BorderLayout and it creates extra space on the bottom so I would prefer it to fit with the rest. Red square shows where image should be placed.
Below is the code of my program:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server extends JFrame implements ActionListener{
public static final int PORT = 8060;
private JButton reset, exit;
private JEditorPane messages;
private ImageIcon logo = new ImageIcon("C:src\\images\\logo.png");
private JLabel logoSpot;
Container box = getContentPane();
public static void main(String args[]){
new Server().Networking();
}
public void makeMenu(){
JPanel menu = new JPanel();
reset = new JButton("Reset messages");
exit = new JButton("Exit");
menu.add(reset);
menu.add(exit);
reset.addActionListener(this);
exit.addActionListener(this);
box.add(menu, BorderLayout.EAST);
}
public void setLogo(){
JPanel logoSpace = new JPanel(new BorderLayout());
logoSpot= new JLabel();
logoSpot.setIcon(logo);
logoSpace.add(logoSpot, BorderLayout.EAST);
box.add(logoSpace, BorderLayout.SOUTH);
}
public void makeScreen(){
JPanel screen = new JPanel();
messages = new JEditorPane();
messages.setPreferredSize(new Dimension(800,590));
screen.add(messages);
box.add(screen, BorderLayout.WEST);
}
public Server(){
makeMenu();
makeScreen();
setLogo();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(1024, 680);
setTitle("Emergency system");
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == exit){
super.dispose();
}
if(e.getSource() == reset){
messages.setText(" ");
}
}
public void Networking(){
String received=" ";
try{
ServerSocket ss = new ServerSocket(PORT);
while(true){
Socket sock = ss.accept();
BufferedReader in =
new BufferedReader(new InputStreamReader(
sock.getInputStream()));
received = in.readLine();
messages.setText(messages.getText() + received +
" \n\n");
OutputStreamWriter out =
new OutputStreamWriter(sock.getOutputStream());
BufferedWriter bw = new BufferedWriter(out);
bw.write(received);
bw.flush();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This should do the trick. It just needed some more panels to constrain the 2nd image (160x160px) to the PAGE_END and LINE_END of some BorderLayout instances.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server extends JFrame implements ActionListener{
public static final int PORT = 8060;
private JButton reset, exit;
private JEditorPane messages;
private ImageIcon logo = new ImageIcon(
new BufferedImage(140,140,BufferedImage.TYPE_INT_RGB));
private JLabel logoSpot;
Container box = getContentPane();
public static void main(String args[]){
new Server();
}
public void makeMenu(){
JPanel menu = new JPanel(new BorderLayout(5,5));
menu.setBackground(Color.RED);
reset = new JButton("Reset messages");
exit = new JButton("Exit");
JPanel buttons = new JPanel();
buttons.setBackground(Color.GREEN);
menu.add(buttons, BorderLayout.PAGE_START);
buttons.add(reset);
buttons.add(exit);
reset.addActionListener(this);
exit.addActionListener(this);
JLabel l = new JLabel(new ImageIcon(new BufferedImage(
160,160,BufferedImage.TYPE_INT_RGB)));
JPanel forceRight = new JPanel(new BorderLayout());
forceRight.add(l, BorderLayout.LINE_END);
forceRight.setBackground(Color.BLUE);
menu.add(forceRight, BorderLayout.PAGE_END);
box.add(menu, BorderLayout.EAST);
}
public void setLogo(){
JPanel logoSpace = new JPanel(new BorderLayout());
logoSpot= new JLabel();
logoSpot.setIcon(logo);
logoSpace.add(logoSpot, BorderLayout.EAST);
box.add(logoSpace, BorderLayout.SOUTH);
}
public void makeScreen(){
JPanel screen = new JPanel();
screen.setBackground(Color.YELLOW);
messages = new JEditorPane();
messages.setPreferredSize(new Dimension(800,590));
screen.add(messages);
box.add(screen, BorderLayout.WEST);
}
public Server(){
makeMenu();
makeScreen();
setLogo();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(1024, 680);
setTitle("Emergency system");
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == exit){
super.dispose();
}
if(e.getSource() == reset){
messages.setText(" ");
}
}
}
You should organize the structure of your code better. The constructor is typically found at the start of the class.
Instead of having 3 methods to create the GUI components you could probably have one. You don't need to use the getContentPane() method. When you use the add(...) method of a JFrame the components are added to the content pane. I would also use a JTextArea to display message. a JEdtitorPane should only be used for HTML. You also should add the text area to a JScrollPane so scrollbars will appear as more messages are added.
So the basic code would be something like:
JTextArea textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane( textArea );
add(scrollPane, BorderLayout.CENTER);
JPanel east = new JPanel( new BorderLayout() );
east.add(menuPanel, BorderLayout.NORTH);
east.add(logo, BorderLayout.SOUTH);
add(east, BorderLayout.EAST);