GUI calclution in JGrasp - swing

I want to perform some calculation by clicking in convert button and the answer will be displayed in the number text field.
also, I have an Exception , I did not know how to solve it
this is the code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class MyEvent implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("Button Clicked ");
System.exit(0);
}
}
class Clacluting{
public static void main(String ar[]) throws IOException{
Frame frm = new Frame("TASK # 3");
TextField txt[] = { new TextField(15), new TextField(9),
};
Label lab[] ={new Label("number"), new Label("Amount")};
Button b = new Button("Convert");
Button b2 = new Button("Reset");
frm.setSize(200,250);
frm.setLayout(new FlowLayout());
double calculat=0;
calculat= Double.parseDouble(txt[0].getText()) * 0.381793;
txt[1].setText(String.valueOf(calculat));
b.addActionListener(new MyEvent());
b2.addActionListener(new MyEvent());
frm.setSize(200,250);
frm.add( lab[0]);
frm.add(txt[0]);
frm.add( lab[1]);
frm.add( txt[1]);
frm.add(b);
frm.add(b2);
frm.setVisible(true);
}
}

Related

How to set label text to JTextField input

I'm trying to get a user to input a name in one panel on CardLayout and for the input to then define a JLabels text in the next panel that it switches to. I used System.out.println(userName); to double check that it was picking up the text and it definitely is but I don't know how to get the 'user' text to be that of the JTextFields input.
Full working code below:
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class gameDataPanel {
private JFrame frame = new JFrame("Game Data Input");
private JPanel mainPanel, loginPanel, gameDataPanel;
private JLabel playerName, user;
private JTextField playerNameInput;
private JButton submit;
private CardLayout gameDataLayout = new CardLayout();
private String userName;
public gameDataPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(gameDataLayout);
playerName = new JLabel("Enter Player Name: ");
playerNameInput = new JTextField(30);
submit = new JButton("Submit");
loginPanel = new JPanel();
loginPanel.add(playerName);
loginPanel.add(playerNameInput);
loginPanel.add(submit);
gameDataPanel = new JPanel();
user = new JLabel();
user.setText(userName);
gameDataPanel.add(user);
mainPanel.add(loginPanel, "1");
mainPanel.add(gameDataPanel, "2");
gameDataLayout.show(mainPanel, "1");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
playerNameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
frame.add(mainPanel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
public static void main(String[] args) {
gameDataPanel gd = new gameDataPanel();
}
}
Thanks
I am not 100% sure, whether i understood you correctly: You want to display the users name, which is entered in "playerNameInput" to be displayed in the JLabel "user" ? In this case, you have to update your JLabel object in your event listener AFTER the user entered something and pressed the push button. Try something like this:
playerNameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
user.setText(userName);
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
I hope this helps :-)

How can i execute a method from tabpane when i click it in javafx

I'm trying execute a method when i change to a specific tab.
If is not selected, when i choose it i need to lauch it.
this is what i am actually doing:
class Graph{
#FXML private TabPane Graphics;
public void llenarResponsables() throws SQLException{
IDProceso=cbProceso.getSelectionModel().getSelectedItem().getIdProceso();
IDIndicador = cbIndicador.getSelectionModel().getSelectedItem().getIdIndicador();
List<Responsables> responsables = new ArrayList<Responsables>();
cdFormatoAnalisis oFormatoAnalisis = new cdFormatoAnalisis();
responsables = oFormatoAnalisis.listarResponsables();
ObservableList<Responsables> tvLlenar = FXCollections.observableArrayList(responsables);
tcNombre.setCellValueFactory(new PropertyValueFac`tory<Responsables,String>("Usuario"));
tcNombre.setResizable(false);
tcPuesto.setCellValueFactory(new PropertyValueFactory<Responsables,String>("Categoria"));
tcPuesto.setResizable(false);
tvResponsables.setItems(tvLlenar);
Graphics.setOnMouseClicked();
}
Well I am not sure what you are trying to do in the method mentioned about, but if you want to fire events on change of tabs, you can use the ChangeListener on your TabPane
A working example
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.stage.Stage;
public class FireEventsOnTabChange extends Application {
#Override
public void start(Stage stage) throws Exception {
TabPane tabPane = new TabPane();
Tab tab1 = new Tab("Tab1");
Tab tab2 = new Tab("Tab2");
Tab tab3 = new Tab("Tab3");
tabPane.getTabs().addAll(tab1, tab2, tab3);
Scene scene = new Scene(tabPane, 200, 200);
stage.setScene(scene);
stage.show();
tabPane.getSelectionModel().selectedItemProperty()
.addListener(new ChangeListener<Tab>() {
#Override
public void changed(ObservableValue<? extends Tab> old,
Tab oldTab, Tab newTab) {
//Check for Tab and call you method here
System.out.println("You have selected "
+ newTab.getText());
}
});
}
public static void main(String[] args) {
launch(args);
}
}

Updating Layout of Panel after changing label icon

I have created a project that will download the thumbnails of the images from a ftp server and display it in a panel using JLabel.
The images are being displayed but the layout of the panel only works if i call the panel once more (i.e using a button on the frame) then the layout corrects itself automatically. What am i doing wrong? Here is the code
EDIT- Updated the code with sscce
1. sscce.java
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* #author Rohn
*/
public class Sscce implements Interface{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setVisible(true);
//frame.add(sci.);
Container c=frame.getContentPane();
JButton button=new JButton("Recall ShowCategoryImagesFunction");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
sci.ShowCategoryImagesFunction("\\Nature\\Black And White"); //for testing purpose only
// if button is pressed then we get right layout and image load
}
});
c.setLayout(new FlowLayout());
c.add(button);
c.add(sci.ShowCategoryImagesFunction("\\Nature\\Black And White")); // default path for image load for first time
// problem in correctly loading images and text with layout
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
2. ShowCategoryImages.java
package sscce;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPFile;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ShowCategoryImages{
//FTPClient client=null;
JPanel panel=new JPanel();
JLabel label=new JLabel();
FTPClient client=new FTPConnection().FTPConnection();
FTPFile[] list;
File thumbnails;
File[] files;
ImageIcon icon;
public JPanel ShowCategoryImagesFunction(String path){
// delete all the components on reload
if(panel.getComponents().length>0){
System.out.println(panel.getComponents().length);
panel.removeAll();
panel.revalidate();
panel.repaint();
}
//panel.setLayout(new GridLayout(0,4,2,2));
//panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));
panel.setLayout(new FlowLayout());
panel.revalidate();
panel.repaint();
panel.updateUI();
try{
//images in /wallpapers/nature/black and white/thumb
client.changeDirectory("\\Wallpapers"+path+"\\thumb"); //path of thumbnails
//temporary folder for holding images
thumbnails=new File("Thumbnails");
list=client.list();
if(thumbnails.exists()){
files = thumbnails.listFiles();
if(files!=null) { //some JVMs return null for empty dirs
for(File f: files) {
f.delete();
}
}
}
else
thumbnails.mkdir();
for(int i=0;i<list.length;i++){
System.out.println("running");
icon=new ImageIcon(thumbnails.getAbsolutePath()+"\\"+list[i].getName());
icon.getImage().flush();
client.download(client.currentDirectory()+"\\"+list[i].getName(), new java.io.File(thumbnails.getAbsolutePath()+"\\"+list[i].getName()));
label=new JLabel(list[i].getName());
label.setIcon(icon);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
panel.add(label);
panel.revalidate();
panel.repaint();
label.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
JLabel la=(JLabel)e.getSource();
System.out.println(la.getIcon());
}
});
}
//client.disconnect(true);
}catch(Exception e){
System.out.println(e.getMessage());
}
return panel;
}
}
3. FTPConnection.java
import it.sauronsoftware.ftp4j.FTPClient;
public class FTPConnection {
//ftp connection on local host
public static FTPClient FTPConnection(){
String ftphost="127.0.0.1";
String ftpuser="newuser";
String ftppassword="wampp";
int ftpport=21;
FTPClient client=new FTPClient();
try{
if(client.isConnected()==true){
client.disconnect(true);
};
client.connect(ftphost, ftpport);
client.login(ftpuser, ftppassword);
}
catch(Exception e){
System.out.println(e.getMessage());
}
return client;
}
}
not entirely sure what you mean with not layout, but your code is missing a revalidate/repaint after adding the labels:
// adding all labels
forEach (thumb....) {
JLabel label = new JLabel(thumb);
panel.add(label);
}
panel.revalidate();
panel.repaint();

may i know why it is not reading the declaration?

Im writing the content of text field to a text file:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;
import java.io.FileNotFoundException;
import java.util.Formatter;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Payroll extends JFrame implements ActionListener{
private JButton btn1;
private JButton btn2;
private JButton btnadd;
// initialize the lbl with caption name is employee information.
JLabel lbl = new JLabel("Nilai University Payroll System");
public Payroll(){
super("Nilai University Payroll System");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
JLabel lblid,lblname,lblrank,lblclass,lbltype,lblpay;
JTextField txtid,txtname,txtrank,txtclass,txtEmployeeClass,txtEmployeeType;
JRadioButton rb1,rb2,rb3,rb4,rb5;
lbl.setBounds(200,50,500,100);
lbl.setHorizontalAlignment(lbl.CENTER );
lblid = new JLabel("Employee ID: ");
lblname = new JLabel("Employee Name: ");
lblrank = new JLabel("Employee Rank: ");
lblclass = new JLabel("Employee Class: ");
lbltype = new JLabel("Class Type: ");
lblpay = new JLabel("Employee Pay Rate: ");
// initialize all the label which are declared in the example above with its caption name
lblid.setBounds(300,140,100,20);
lblname.setBounds(300,180,100,20);
lblrank.setBounds(300,220,100,20);
lblclass.setBounds(300,260,100,20);
lbltype.setBounds(300,300,100,20);
lblpay.setBounds(300,340,100,20);
// add all the label on the frame
add(lblid);
add(lblname);
add(lblrank);
add(lblclass);
add(lbltype);
add(lblpay);
// initialize the text field with size
txtid=new JTextField(15);
txtname=new JTextField(15);
txtclass=new JTextField(15);
txtEmployeeClass=new JTextField(15);
txtEmployeeType=new JTextField(15);
// set a particular position on a screen with set bounds constructor
txtid.setBounds(400,140,100,20);
txtname.setBounds(400,180,100,20);
txtclass.setBounds(400,220,100,20);
txtEmployeeClass.setBounds(400,260,100,20);
txtEmployeeType.setBounds(400,300,100,20);
// add text field on a Frame
add(txtid);
add(txtname);
add(txtclass);
add(txtEmployeeClass);
add(txtEmployeeClass);
// initialize radio button with its caption
rb1 = new JRadioButton("1. Excellent");
rb2 = new JRadioButton("2. Good");
rb3 = new JRadioButton("3. Average");
rb4 = new JRadioButton("4. Fair");
rb5 = new JRadioButton("5. Poor");
// set a particular position on a Frame
rb1.setBounds(400,220,100,20);
rb2.setBounds(500,220,100,20);
rb3.setBounds(600,220,100,20);
rb4.setBounds(700,220,100,20);
rb5.setBounds(800,220,100,20);
// add button on a frame
add(rb1);
add(rb2);
add(rb3);
add(rb4);
add(rb5);
btnadd = new JButton("Add Employee");
btnadd.setToolTipText("Click this button to add employee details to a text file.");
btnadd.setBounds(400,320,150,20);
add(btnadd);
btnadd.addActionListener(this);
btnadd.setActionCommand("Add");
}
private BufferedWriter output;
public void actionPerformed(ActionEvent e){
String cmd = e.getActionCommand();
if(cmd.equals("Add"))
{
output.write("ID: "+txtid.getNume()+"\n");
}
}
public void WriteFile(){
try {
output = new BufferedWriter(new FileWriter("E:/EC3307/eclipse/Payroll.txt",true));
output.newLine();
output.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run()
{
Payroll f1=new Payroll();
// set frame size
f1.setSize(1000,600);
// set frame visible true
f1.setVisible(true);
}
});
}
}
The problem is that txtid is a local variable of your Payroll constructor and not a member of the Payroll class. Simply declare txtid as variable of your Payroll class and this will allow to access it in your actionPerformed method.
Declare txtid outside of Payroll() constructor

trouble executing actionlistener in swing applet embedded in html

Following is the applet code below:
import javax.swing.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.UnknownHostException;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ui extends JApplet implements ActionListener{
public static JPanel panel2;
private JTextField subnetField =null;
public static JPanel panel3;
public static Font fc;
public static String[] subn;
public static String searchnet;
boolean flag=false;
public void init()
{
String hostname = null;
String hostaddress=null;
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
hostaddress=addr.getHostAddress();
// Get hostname
hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
subn= hostaddress.split("\\.");
System.out.println(subn[2]);
searchnet=subn[2];
//WindowDestroyer listener=new WindowDestroyer();
//addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new GridLayout(3,0));
JPanel panel1 =new JPanel();
panel2 =new JPanel();
panel1.setBackground(Color.WHITE);
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
JLabel lb2 = new JLabel("You are at: "+hostname+" "+hostaddress+" ");
lb2.setFont(new Font("sans-serif",Font.BOLD,15));
lb2.setForeground(Color.RED);
JPanel panel1_1 =new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
panel1_1.setBackground(Color.WHITE);
panel1_1.add(lb2, c);
//lb2.setAlignmentX(Component.CENTER_ALIGNMENT);
//panel1_1.add(lb2, BorderLayout.EAST);
panel1_1.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.add(panel1_1);
panel3=new JPanel();
panel3.setLayout(new GridLayout(2,0));
panel3.setBackground(Color.WHITE);
panel1.add(panel3);
UIManager.put("Button.background", Color.white);
UIManager.put("Button.foreground", Color.red);
fc = new Font("sans-serif",Font.BOLD,15);
UIManager.put("Button.font", fc);
JButton searchButton= new JButton("Search");
//Border b = new SoftBevelBorder(BevelBorder.LOWERED) ;
//searchButton.setBorder(b);
searchButton.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.add(searchButton);
searchButton.addActionListener(this);
contentPane.add(panel1);
panel2.setBackground(Color.WHITE);
contentPane.add(panel2);
//contentPane.add(searchButton);
//JButton closeButton=new JButton("Close");
//contentPane.add(closeButton);
//closeButton.addActionListener(this);
contentPane.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand ().equals ("Close"))
{
System.exit(0);
}
if (e.getActionCommand ().equals ("Search"))
{
panel2.setVisible(false);
panel2.removeAll();
panel2.revalidate();
panel3.setVisible(false);
panel3.removeAll();
panel3.revalidate();
if(flag){
searchnet=subnetField.getText();
}
result(panel2);//puts panel 2&panel 3 in the ui
panel2.setVisible(true);
panel3.setVisible(true);
}
}
public boolean complete;
public JPanel call(){
return null;
}
public void result(JPanel pn){
.
.
.
}
}
}
private void addColumnName(JPanel pn) {
// TODO Auto-generated method stub
}
public void addDataToTable(JPanel p, String element, int type){
......
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (Exception e) {
// TODO: error handling
}
} else {
// TODO: error handling
}
}
public static void main(String[] args){
ui start=new ui();
start.setVisible(true);
JFrame f = new JFrame("Find Device");
ui applet=new ui();
applet.init();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,450);
f.setVisible(true);
}
}
then the html file looks like this:
<html>
<applet code=ui.class
archive="webapplet.jar"
width=800 height=450>
</applet>
</body>
</html>
when i run the program via eclipse as an applet it runs fine, but when i put it in the html file, the init() seems to show up but the actionlistener on the button never seems to work
Any help would be really appreciated. Thanks!!
ps: will be happy to share any additional details if required
Emm... you mean the code never works as
System.exit(0);
?
If you mean "Close" button inactivity so it shouldn't close Internet Browser ... so that's OK :)
And this one as
InetAddress addr = InetAddress.getLocalHost();
Hmm... As for applet, I guess you should use getCodeBase() instead
Good luck :)