Trying to export project as Runnable Jar file - java

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);
}
}

Related

how to save data to a text file on java without a dialog box pop up having the user click save

I'm trying to save data from a GUI I made, to a text document. In the GUI I have a menubar with a menu for opening and saving. they both work just fine. the problem is with the finish button. The finish button has to save to a text document without that popup box showing (without this
https://gyazo.com/41fd2370025c7c49cb375c0f64936597).
It has to save in the background without the user having to click "ok" or "save" in my case. It has to save automatically basically. Here is my code:
public class Survey extends JFrame {
public JLabel label;
public JLabel age;
JPanel panel = new JPanel();
JComboBox<String> majorsList;
JTextField textField;
JRadioButton Male;
JRadioButton Female;
JCheckBox workButton;
JCheckBox homeButton;
JCheckBox pcButton;
Integer ageInfo;
int hasJob;
int isHome;
int hasPC;
int age1;
int workAns;
int homeAns;
int PCAns;
String majorsInfo;
String rbinfoMale;
String rbinfoFemale;
String sex;
File fileToSave;
String file_name;
String My_File;
JPanel rButton;
ButtonGroup bg1;
JFileChooser fileChooser;
File fileToOpen;
StringBuilder sb;
String fullcombo;
JFrame parentFrame;
JMenuItem openItem;
JMenuItem saveItem;
File file;
ArrayList<String> allInputs = new ArrayList<String>();
public Survey() {
fileChooser = new JFileChooser();
//JTextField textfield = new JTextField();
//textfield.add(textfield(), BorderLayout.NORTH);
JPanel finishButton = new JPanel();
finishButton.add(finish());
JPanel northPanel = new JPanel();
northPanel.add(age());
JPanel centerPanel = new JPanel();
centerPanel.add(Majors());
centerPanel.add(RadioButtons());
centerPanel.add(locationWork());
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(createFileMenu());
menuBar.add(createDrawMenu());
//ageInput.add(createTextField());
//createTextField();
//textField = new JTextField(10);
//textField.setBounds(5, 5, 280, 50);
//panel.add(textField, BorderLayout.NORTH);
add(northPanel, BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
add(finishButton, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 600);
}
public static void main(String args[]) {
Survey c = new Survey();
c.setTitle("Survey");
c.setVisible(true);
}
public JMenu createFileMenu() {
JMenu menu = new JMenu("File");
saveItem = new JMenuItem("Save");
openItem = new JMenuItem("Open");
JMenuItem quitItem = new JMenuItem("Quit");
ActionListener listener = new ExitItemListener();
quitItem.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
saveItem.addActionListener(listener2);
ActionListener listener3 = new OpenItemListener();
openItem.addActionListener(listener3);
menu.add(saveItem);
menu.add(openItem);
menu.add(quitItem);
return menu;
}
public JMenu createDrawMenu() {
JMenu menu = new JMenu("Draw");
saveItem = new JMenuItem("Save");
openItem = new JMenuItem("Open");
JMenuItem quitItem = new JMenuItem("Quit");
ActionListener listener = new ExitItemListener();
quitItem.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
saveItem.addActionListener(listener2);
menu.add(saveItem);
menu.add(openItem);
menu.add(quitItem);
return menu;
}
public JPanel finish() {
JButton finish = new JButton("Finish");
panel.add(finish);
ActionListener listener = new ExitItemListener();
finish.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
finish.addActionListener(listener2);
return panel;
}
public JPanel age() {
JPanel textf = new JPanel();
textf.add(age = new JLabel("Age: "));
textField = new JTextField(10);
textField.setBounds(5, 5, 280, 50);
textField.setFont(textField.getFont().deriveFont(20f));
textf.setBorder(new BevelBorder(0));
textf.add(textField);
return textf;
}
public JPanel Majors() {
JPanel majorPanel = new JPanel();
String[] majorsStrings = {"Biology", "Chemistry", "Computer Science", "Engineering"};
majorsList = new JComboBox<String>(majorsStrings);
majorsList.setBorder(new TitledBorder(new EtchedBorder(), "College"));
majorsList.setSelectedIndex(3);
majorsList.addActionListener(majorsList);
majorPanel.add(majorsList);
return majorPanel;
}
public JPanel RadioButtons() {
bg1 = new ButtonGroup();
rButton = new JPanel();
Male = new JRadioButton("Male");
Female = new JRadioButton("Female");
rButton.setLayout(new GridLayout(2, 1));
bg1.add(Male);
bg1.add(Female);
rButton.add(Male);
rButton.add(Female);
return rButton;
}
public JPanel locationWork() {
workButton = new JCheckBox("Work");
homeButton = new JCheckBox("Have Children");
pcButton = new JCheckBox("Own PC");
JPanel cButton = new JPanel();
workButton.setMnemonic(KeyEvent.VK_C);
homeButton.setMnemonic(KeyEvent.VK_G);
pcButton.setMnemonic(KeyEvent.VK_H);
cButton.setLayout(new GridLayout(3, 1));
cButton.add(workButton);
cButton.add(homeButton);
cButton.add(pcButton);
return cButton;
}
private String inputCombo(int age1, String major, String sex, int work, int kids, int comp) {
String newAge = Integer.toString(age1);
String hasWork = Integer.toString(work);
String hasKids = Integer.toString(kids);
String hasComp = Integer.toString(comp);
String combo = major + ", " + newAge + ", " + sex + ", " + hasWork + ", " + hasKids + ", " + hasComp;
return combo;
}
private ArrayList<String> inputData() {
boolean catcher = true;
try {
age1 = Integer.parseInt(textField.getText());
} catch (IllegalFormatException ex) {
catcher = false;
System.out.println("Not an integer");
}
majorsInfo = majorsList.getSelectedItem().toString();
if (Male.isSelected()) {
sex = "Male";
} else if (Female.isSelected()) {
sex = "Female";
} else {
sex = "";
catcher = false;
}
if (workButton.isSelected()) {
workAns = 1;
} else {
workAns = 0;
}
if (homeButton.isSelected()) {
homeAns = 1;
} else {
homeAns = 0;
}
if (pcButton.isSelected()) {
PCAns = 1;
} else {
PCAns = 0;
}
if (catcher) {
fullcombo = inputCombo(age1, majorsInfo, sex, workAns, homeAns, PCAns);
allInputs.add(fullcombo);
} else {
System.out.println("Fill out all fields please");
}
return allInputs;
}
class ExitItemListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
}
class SaveItemListener implements ActionListener {
public void actionPerformed(ActionEvent event1) {
try {
fileChooser.showSaveDialog(Survey.this);
if (fileChooser.showSaveDialog(Survey.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
StringBuilder sb = new StringBuilder();
FileWriter fw = new FileWriter(file, true);
for (String a : inputData()) {
sb.append(a);
sb.append("\r\n");
}
fw.write(sb.toString());
fw.flush();
fw.close();
}
} catch (IOException ex) {
}
}
}
class OpenItemListener implements ActionListener {
public void actionPerformed(ActionEvent event2) {
File file = fileChooser.getSelectedFile();
fileChooser.showOpenDialog(Survey.this);
}
}
}

Why Windows doesn't show the same output for ImageIcon on JButton as Ubuntu?

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!

cannot update in panel when i choose a file path

once a user selects the button "CLICK HERE TO UPLOAD", the3 file path is stored into a file, and these paths are read into an arraylist, which is shown on the JPanel. the problem is that once a file is selected, it is never updated automatically on the JPanel, unless the application is re runed, before the up to date number of information is displayed. How can this problem be rectified, because i have no clue where i have gone wrong. By the way the arraylists gets updated on runtime but the JPanel never gets updated.
public class Media2 extends JPanel {
private JPanel video_pnl, control_pnl;
private JButton play_btn;
private JLabel loc_lbl;
private int increment;
ArrayList<String> file_location;
ArrayList<JButton> button_lists;
private FileWriter file_writer;
private BufferedWriter buffered_writer;
private JFileChooser filechooser;
private File file;
private JButton btn_upload;
private BufferedReader br;
private FileReader fr;
public Media2(ArrayList<String> file_location) throws IOException {
btn_upload = new JButton("Click here to Upload Video");
String file_path = "C:\\Users\\goldAnthony\\Documents\\NetBeansProjects\\VDMS\\src\\VideoInfos.txt";
file = new File(file_path);
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
add(btn_upload);
Handlers handler = new Handlers();
btn_upload.addActionListener(handler);
this.file_location = file_location;
readFile(file_location, file_path);
}
private void readFile(ArrayList<String> file_location, String file_path) throws FileNotFoundException, IOException {
fr = new FileReader(file_path);
br = new BufferedReader(fr);
String text = "";
String line2;
line2 = br.readLine();
while (line2 != null) {
int i = 0;
file_location.add(i, line2);
line2 = br.readLine();
i++;
}
configurePanel(file_location);
//System.out.print(file_location.size() + "in the read file 1");
}
private void configurePanel(ArrayList<String> file_location) {
increment = 0;
while (increment < file_location.size()) {
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(file_location.get(increment));
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
video_pnl.add(loc_lbl);
control_pnl.add(createButton(increment));
video_pnl.add(control_pnl, BorderLayout.SOUTH);
video_pnl.revalidate();
add(video_pnl);
increment++;
}
}
private JButton createButton(final int i) {
play_btn = new JButton("Play");
play_btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// System.out.println(file_location.get(i));
play(i);
}
});
return play_btn;
}
public void play(int i) {
System.out.println(file_location.get(i));
}
private class Handlers implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_upload) {
try { //display the image in jlabel
file = new File("C:\\Users\\goldAnthony\\Documents\\NetBeansProjects\\VDMS\\src\\VideoInfos.txt");
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
buffered_writer = new BufferedWriter(file_writer);
//creating a file chooser
filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your Video");
// //below codes for select the file
int returnval = filechooser.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
String filename = file.getAbsolutePath();
buffered_writer.write(filename);
buffered_writer.newLine();
buffered_writer.close();
}
} catch (IOException | HeadlessException ex) {
System.out.println(ex.getMessage());
}
}
}
}
public static void main(String[] args) throws IOException {
//Declare and initialize local variables
ArrayList<String> file_location = new ArrayList<>();
//creates instances of the VlcPlayer object, pass the mediaPath and invokes the method "run"
Media2 mediaplayer = new Media2(file_location);
JFrame ourframe = new JFrame();
ourframe.setContentPane(mediaplayer);
ourframe.setLayout(new GridLayout(5, 1));
ourframe.setSize(300, 560);
ourframe.setVisible(true);
ourframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
When you add components to a visible GUI the basic code is:
panel.add(...);
panel.revalidate();
panel.repaint();
You are revalidating the wrong panel:
video_pnl.revalidate(); // wrong panel
add(video_pnl);
You should be doing:
//video_pnl.revalidate();
add(video_pnl);
revalidate();
repaint();
Your code needs some changes, try:
private void configurePanel(ArrayList<String> file_location) {
increment = 0;
while (increment < file_location.size()) {
addEntry(file_location.get(increment));//--------->New line
increment++;
}
}
private void addEntry(String location) {//--------->New constructor
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(location);
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
video_pnl.add(loc_lbl);
control_pnl.add(createButton(increment));
video_pnl.add(control_pnl, BorderLayout.SOUTH);
video_pnl.revalidate();
add(video_pnl);
}
and:
private class Handlers implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_upload) {
try { //display the image in jlabel
file = new File("C:\\VideoInfos.txt");
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
buffered_writer = new BufferedWriter(file_writer);
//creating a file chooser
filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your Video");
// //below codes for select the file
int returnval = filechooser.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
String filename = file.getAbsolutePath();
buffered_writer.newLine();
buffered_writer.write(filename);
buffered_writer.newLine();
buffered_writer.close();
addEntry(filename);//---------------->New Line
validate();//------------>New Line
}
} catch (IOException | HeadlessException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Now it's working. You have to make further changes, of course :)

Java Messenger Socket

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
}

reading name contact

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
}
}
}

Categories