I am currently trying to create a simple access panel which allows the user to click on the numbers and it will appear in the textfield above but when the button is clicked the textfield is being populated but the previous number is being overwritten! Below shows the code I currently have. It's btn1 & btn2 I am focusing on at the minute:
package securitySystem;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.awt.event.*;
public class accessPanel extends JFrame {
public static void main (String args[]){
accessPanel gui= new accessPanel ();
gui.setSize (360, 400);
gui.setLocationRelativeTo(null);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setTitle("Access Panel");
gui.setLayout(new BorderLayout());
gui.setBackground(Color.BLACK);
}
JButton btn1= new JButton("1");
JButton btn2= new JButton("2");
JButton btn3= new JButton("3");
JButton btn4= new JButton("4");
JButton btn5= new JButton("5");
JButton btn6= new JButton("6");
JButton btn7= new JButton("7");
JButton btn8= new JButton("8");
JButton btn9= new JButton("9");
JButton btn0= new JButton("0");
JTextField pin = new JTextField();
public accessPanel (){
setLayout(null);
pin.setBounds(0,0,340,40);
add(pin);
btn1.setBounds(0,40,100,70);
add(btn1);
btn2.setBounds(120,40,100,70);
add(btn2);
btn3.setBounds(240,40,100,70);
add(btn3);
btn4.setBounds(0,120,100,70);
add(btn4);
btn5.setBounds(120,120,100,70);
add(btn5);
btn6.setBounds(240,120,100,70);
add(btn6);
btn7.setBounds(0,200,100,70);
add(btn7);
btn8.setBounds(120,200,100,70);
add(btn8);
btn9.setBounds(240,200,100,70);
add(btn9);
btn0.setBounds(120,280,100,70);
add(btn0);
}
public void calcButtons()
{
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pin.setText(btn1.getText());
}
});
btn2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pin.setText(btn2.getText());
}
});
}
}
Have a global String that you can add the numbers to every time a button is clicked
public class accessPanel extends JFrame {
String word = "";
...
btn2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
word += btn2.getText();
pin.setText(word);
}
});
}
If you have a clear button, just set the string to "" in the its actionPerformed
Related
I am working on a TableView (FXML) where I want to have all the rows accompanied with a delete button at the last column.
Here's a video that shows what I mean: YouTube Delete Button in TableView
Here's what I have in my main controller class:
public Button del() {
Button del = new Button();
del.setText("X");
del.setPrefWidth(30);
del.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
int i = index.get();
if(i > -1) {
goals.remove(i);
list.getSelectionModel().clearSelection();
}
}
});
return del;
}
private SimpleIntegerProperty index = new SimpleIntegerProperty();
#Override
public void initialize(URL location, ResourceBundle resources){
//DateFormat df = new SimpleDateFormat("dd MMM yyyy");
sdate.setValue(LocalDate.now());
edate.setValue(LocalDate.now());
seq.setCellValueFactory(new PropertyValueFactory<Goals, Integer>("id"));
gol.setCellValueFactory(new PropertyValueFactory<Goals, String>("goal"));
sdt.setCellValueFactory(new PropertyValueFactory<Goals, Date>("sdte"));
edt.setCellValueFactory(new PropertyValueFactory<Goals, Date>("edte"));
prog.setCellValueFactory(new PropertyValueFactory<Goals, Integer>("pb"));
del.setCellValueFactory(new PropertyValueFactory<Goals, Button>("x"));
list.setItems(goals);
list.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Object>() {
#Override
public void changed(ObservableValue<?> observable,
Object oldValue, Object newValue) {
index.set(goals.indexOf(newValue));
System.out.println("Index is: "+goals.indexOf(newValue));
}
});
}
Each time I launch the application, I will try to click the delete button from random rows but it always delete the first row. I guess the addListener method I use for list is not properly implemented and indexOf(newValue) is always 0 at every initialisation.
However, it will work if I click a row first and then click the delete button. But this is not what I want. I want users to be able to delete any row if they press the delete button without selecting the row.
Appreciate your help guys!
You need a custom cell factory defined for the column containing the delete button.
TableColumn<Person, Person> unfriendCol = new TableColumn<>("Anti-social");
unfriendCol.setCellValueFactory(
param -> new ReadOnlyObjectWrapper<>(param.getValue())
);
unfriendCol.setCellFactory(param -> new TableCell<Person, Person>() {
private final Button deleteButton = new Button("Unfriend");
#Override
protected void updateItem(Person person, boolean empty) {
super.updateItem(person, empty);
if (person == null) {
setGraphic(null);
return;
}
setGraphic(deleteButton);
deleteButton.setOnAction(
event -> getTableView().getItems().remove(person)
);
}
});
Here is a sample app. It doesn't use FXML, but you could adapt it to work with FXML very easily. Just click on an "Unfriend" button in the "Anti-social" column to delete a friend. Do it a lot and you will soon run out of friends.
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class GestureEvents extends Application {
private TableView<Person> table = new TableView<>();
private final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("Jacob", "Smith"),
new Person("Isabella", "Johnson"),
new Person("Ethan", "Williams"),
new Person("Emma", "Jones"),
new Person("Michael", "Brown")
);
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
final Label label = new Label("Friends");
label.setFont(new Font("Arial", 20));
final Label actionTaken = new Label();
TableColumn<Person, Person> unfriendCol = new TableColumn<>("Anti-social");
unfriendCol.setMinWidth(40);
unfriendCol.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue()));
unfriendCol.setCellFactory(param -> new TableCell<Person, Person>() {
private final Button deleteButton = new Button("Unfriend");
#Override
protected void updateItem(Person person, boolean empty) {
super.updateItem(person, empty);
if (person == null) {
setGraphic(null);
return;
}
setGraphic(deleteButton);
deleteButton.setOnAction(event -> data.remove(person));
}
});
TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory<>("firstName"));
TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(
new PropertyValueFactory<>("lastName"));
table.setItems(data);
table.getColumns().addAll(unfriendCol, firstNameCol, lastNameCol);
table.setPrefHeight(250);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 10, 10, 10));
vbox.getChildren().addAll(label, table, actionTaken);
VBox.setVgrow(table, Priority.ALWAYS);
stage.setScene(new Scene(vbox));
stage.show();
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private Person(String fName, String lName) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
}
}
I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Put the ActionListener into the sim class.
public void actionPerformed(ActionEvent e)
{
JButton clicked = (JButton)e.getSource();
if(clicked == button)
{
JOptionPane.showMessageDialog(null, "this team will win");
}
}
You need to decrees the amount of code to just amount needed you dont need to show us all the raidio
Ok basically my problem is I don't know how to get my buttons and my labels to appear in the frame that I just created. I tried using frame.add(new JButton("VOTE1")); but that doesn't work and it says it's missing an identifier. Here is my code so far, your help is much appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class VotingMachine extends JFrame implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame("Voting Machine");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JLabel Candidate1 = new JLabel("My Name");
private JLabel Candidate2 = new JLabel("Jennifer Lawrence");
private JLabel Candidate3 = new JLabel("Cristiano Ronaldo");
private JButton VOTE1 = new JButton("VOTE FOR Bishoy Morcos");
private JButton VOTE2 = new JButton("VOTE FOR Jennifer Lawrence");
private JButton VOTE3 = new JButton("VOTE FOR Cristiano Ronaldo");
int countcandidate1;
int countcandidate2;
int countcandidate3;
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o == VOTE1)
countcandidate1++;
else if(o == VOTE2)
countcandidate2++;
else if(o == VOTE3)
countcandidate3++;
}
}
First you need to create a JPanel
JPanel welcomePanel = new JPanel();
Then add the buttons and labels to that panel
welcomePanel.add(Candidate1);
welcomePanel.add(VOTE1);
ETC.... for all of your buttons and labels
Lastly, add that JPanel to your JFrame
frame.add(welcomePanel);
If this answers your question, please mark it as answered so other viewers will be informed.
How to create a click event search button in Eclipse?? Can someone help me. This is the code im working with.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listContent1 = (ListView)findViewById(R.id.lFoodlist1);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[]{SQLiteAdapter.KEY_FOODNAME,SQLiteAdapter.KEY_CALORIES};
int[] to = new int[]{R.id.tv1, R.id.tv2};
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent1.setAdapter(cursorAdapter);
//listContent.setOnItemClickListener(listContentOnItemClickListener);*/
}
This code was taken from Here and was modified/commented to help the poseter with his scenario.
You can implement swing to help with the GUI aspect of your application. Others may prefer AWT
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.JOptionPane;
import javax.swing.JPanel;
public class myTest {
public static void main(String[] args) {
//This will create the JFrame/JPanel/JButton
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button1 = new JButton();
//Add your panel and button and make them visable
frame.add(panel);
panel.add(button1);
frame.setVisible(true);
//This adds the actionListener to the Button
button1.addActionListener(new ActionListener() {
//When the button is clicked this action will be performed
public void actionPerformed(ActionEvent arg0) {
//Add your code here.
}
});
}
}
I've tried a bunch of different ways to close the window, but since you can't send additional parameters to to Action Listener method I can't dispose the frame due to a pointer exception for the frame.
This is my current code.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class errorRequiredFieldMissing extends JDialog{
JLabel error;
JButton exit;
public static JFrame frame;
public errorRequiredFieldMissing() {
super(frame, "Error", true);
setLayout(new FlowLayout());
error = new JLabel ("Required field or fields missing, please fill in all fields to continue.");
add(error);
exit = new JButton ("OK");
add(exit);
System.out.println("chk1");
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
System.out.println("chk2");
frame.dispose();
}
});
}
public static void method2(){
System.out.print("success!");
errorRequiredFieldMissing gui = new errorRequiredFieldMissing();
gui.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
gui.setSize(400,100);
gui.setLocation(300,25);
gui.setVisible(true);
}
}
try this way:
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
and then
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}