in my company we got a task to implement an autoexpandable textfield.
As this functionality is not provided by default we had to develop it from scratch. There are many posibilities across web, how it can be achived, but no one worked for as, so we decided to put our code on SO, so other devs can also use it.
As it is not possbile to expand a textfield the solution is textarea based:
public class TextFieldExpandable extends TextArea {
private final double DEFAULT_HEIGHT = 17.0;
public TextFieldExpandable() {
setMinHeight(DEFAULT_HEIGHT);
setPrefHeight(DEFAULT_HEIGHT);
setMaxHeight(DEFAULT_HEIGHT);
disableEnter();
}
#Override
protected void layoutChildren() {
super.layoutChildren();
setWrapText(true);
setPadding(new Insets(0, 0, 0, 0));
ScrollPane scrollPane = (ScrollPane)lookup(".scroll-pane");
scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollBarPolicy.NEVER);
scrollPane.setPadding(new Insets(0, 0, 0, 0));
StackPane viewport = (StackPane) scrollPane.lookup(".viewport");
viewport.setPadding(new Insets(0, 0, 0, 0));
Region content = (Region) viewport.lookup(".content");
content.setPadding(new Insets(-1, 1, 0, 1));
Text text = (Text) content.lookup(".text");
text.textProperty().addListener((property) -> {
double textHeight = text.getBoundsInLocal().getHeight();
if (textHeight < DEFAULT_HEIGHT) {
textHeight = DEFAULT_HEIGHT;
}
textHeight = textHeight + 1;
setMinHeight(textHeight);
setPrefHeight(textHeight);
setMaxHeight(textHeight);
});
}
private void disableEnter() {
setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
event.consume();
}
}
});
}
}
I hope it helps you :)
that's work for me fine
field.setMinWidth(40);
field.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
int len = newValue.length();
field.setPrefWidth(len*10);
if(newValue.isEmpty() || oldValue.isEmpty()){
field.setPrefWidth(40);
}
});
you can set PrefWidth in the listener of the text field.
// add listner
'textField.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
textField.setPrefWidth(textField.getText().length());
}
});'
Related
Note: this is an updatet version of the initial question.
Whats now beeing asked is how I can get access to the values of a certain row for calculations purposes. For example how can I calculate the difference betweeen values of the expensesColumn and the earningsColumn? (Because there was to much code within my questions, I deleted most of the imports)
package application;
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {Table.create(primaryStage);}
catch(Exception e) {e.printStackTrace();}
}
public static void main(String[] args) {
launch(args);
}
}
package application;
public class UserJava {
private String member;
private double expenses;
private double earnings;
//Getter und Setter
public String getMember() {
return member;
}
public void setMember(String member) {
this.member = member;
}
public double getExpenses() {
return expenses;
}
public void setExpenses(double expenses) {
this.expenses = expenses;
}
public double getEarnings() {
return earnings;
}
public void setEarnings(double earnings) {
this.earnings = earnings;
}
}
package application;
import javafx.stage.Stage;
public class Table {
static TableView<UserJava> table;
public static void create (Stage primaryStage){
try {
GridPane primarygridpane = new GridPane();
HBox hboxTable = new HBox(10);
//Definition der Tabelle
TableColumn<UserJava, String> userColumn = new TableColumn<>("Name");
userColumn.setCellValueFactory(new PropertyValueFactory<>("member"));
userColumn.setMinWidth(200);
TableColumn<UserJava, Double> expensesColumn = new TableColumn<>("Ausgaben");
expensesColumn.setCellValueFactory(new PropertyValueFactory<>("expenses"));
expensesColumn.setMinWidth(100);
TableColumn<UserJava, Double> earningsColumn = new TableColumn<>("Pfand");
earningsColumn.setCellValueFactory(new PropertyValueFactory<>("earnings"));
earningsColumn.setMinWidth(100);
table = new TableView<>();
table.getColumns().addAll(userColumn, expensesColumn, earningsColumn);
TextField tfMember = new TextField();
tfMember.setMinWidth(200);
tfMember.setPromptText("Name");
TextField tfExpenses = new TextField();
tfExpenses.setMinWidth(100);
tfExpenses.setPromptText("Ausgaben");
TextField tfEarnings = new TextField();
tfEarnings.setMinWidth(100);
tfEarnings.setPromptText("Pfand");
Button btnAdd = new Button("Hinzufügen");
Button btnDelete = new Button("Löschen");
hboxTable.getChildren().addAll(tfMember, tfExpenses, tfEarnings, btnAdd, btnDelete);
table.setEditable(true);
userColumn.setCellFactory(TextFieldTableCell.forTableColumn());
// table.setItems(getUser());
//Sonstiges
Scene scene = new Scene(primarygridpane,725,400);
Text titel = new Text("Application");
titel.setFont(Font.font("Arial", FontWeight.BOLD, 28));
primarygridpane.add(titel, 0, 0, 2, 1);
primarygridpane.add(table, 0, 2);
primarygridpane.add(hboxTable, 0, 3);
// scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
//Funktionen
btnAdd.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e) {
try {
UserJava user = new UserJava();
user.setMember(tfMember.getText());
user.setExpenses(Double.parseDouble(tfExpenses.getText()));
user.setEarnings(Double.parseDouble(tfEarnings.getText()));
table.getItems().add(user);
tfMember.clear();
tfExpenses.clear();
tfEarnings.clear();
System.out.println(table.getItems());
}
catch (NumberFormatException Ausnahme) {}
}
});
btnDelete.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e) {
try {
ObservableList<UserJava> userSelected, userAll;
userAll = table.getItems();
userSelected = table.getSelectionModel().getSelectedItems();
userSelected.forEach(userAll::remove);
System.out.println();
}
catch (java.util.NoSuchElementException Ausnahme) {}
}
});
}
catch (Exception e) {e.printStackTrace();}
}
public ObservableList<UserJava> getUser(){
ObservableList<UserJava> user = FXCollections.observableArrayList();
user.add(new UserJava());
return user;
}
public void changeCell(CellEditEvent<?, ?> ediditedCell) {
UserJava personSelected = table.getSelectionModel().getSelectedItem();
personSelected.setMember(ediditedCell.getNewValue().toString());
}
}
I am writing a program, where I'd like to open a class by the press of a button. I have two buttons on a window, the first one works perfectly, but I can't seem to be able to move the second one (called "Teacher"). Here is the code. I am desperately looking for the solution. Thanks!
class MyHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
class MyFrame extends JFrame {
private int size;
private String font;
MyFrame (String name){
super (name);
setBounds(500,500,600,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//log in text
JLabel lbl = new JLabel("Log in");
lbl.setBounds(250, 60, 600, 50);
size = 40;
font = "Arial";
lbl.setFont(new Font(name,Font.PLAIN,size));
add(lbl);
//adding button
JButton btn = new JButton("Student");
btn.setBounds(150, 260, 60, 40);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
new Frame("StudentLogIn");
}
});
add(btn);
//adding second button
JButton teach = new JButton("Teacher");
teach.setBounds(100,260,60,40);
teach.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
new FrameTeach("TeacherLogIn");
}
});
add(teach);
setVisible(true);
}
}
public class StartingWindow {
public static void main(String[] args) {
new MyFrame("Starting Window");
}
}
I need to know how to change the text color of a textfield. If the input is invalid, the text should change to red. If it's valid, it should change to back to black. The color needs to change when I click off the textfield.
I have tried using an EventHandler, which does sort of work, but there's a delay when I click off the textfield. My professor says to use bindings, but I'm not sure what to bind what to.
import javafx.application.Application;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.stage.*;
import org.junit.Test;
public class DataEntryGUI extends Application{
#Override
public void start(Stage primaryStage){
GridPane root = new GridPane();
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(30, 30, 30, 30));
root.setHgap(5.5);
root.setVgap(5.5);
// TextFields
NameTextField firstName = new NameTextField();
firstName.setPromptText("Name");
firstName.setOnMouseExited(e -> NameTextField.nameIsValid(firstName));
NameTextField secondName = new NameTextField();
secondName.setPromptText("Name");
secondName.setOnMouseExited(e -> NameTextField.nameIsValid(secondName));
NameTextField thirdName = new NameTextField();
thirdName.setPromptText("Name");
thirdName.setOnMouseExited(e -> NameTextField.nameIsValid(thirdName));
PhoneTextField firstNumber = new PhoneTextField();
firstNumber.setPromptText("(###) ###-####");
firstNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(firstNumber));
PhoneTextField secondNumber = new PhoneTextField();
secondNumber.setPromptText("(###) ###-####");
secondNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(secondNumber));
PhoneTextField thirdNumber = new PhoneTextField();
thirdNumber.setPromptText("(###) ###-####");
thirdNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(thirdNumber));
// "Create Profiles" button
StackPane btnPane = new StackPane();
Button btn = new Button("Create Profiles");
btnPane.getChildren().add(btn);
StackPane.setAlignment(btn, Pos.CENTER);
//Enable/Disable button depending on if any TextField is empty
btn.disableProperty().bind(firstName.textProperty().isEmpty()
.or(secondName.textProperty().isEmpty()).or(thirdName.textProperty().isEmpty())
.or(firstNumber.textProperty().isEmpty()).or(secondNumber.textProperty().isEmpty())
.or(thirdNumber.textProperty().isEmpty()));
// Layout of window
root.add(firstName, 0, 0);
root.add(secondName, 0, 1);
root.add(thirdName, 0, 2);
root.add(firstNumber, 1, 0);
root.add(secondNumber, 1, 1);
root.add(thirdNumber, 1, 2);
root.add(btnPane, 0, 3, 2, 3);
// Creating scene
Scene scene = new Scene(root);
primaryStage.setTitle("Data Entry GUI");
primaryStage.setScene(scene); primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
import javafx.scene.control.TextField;
public class NameTextField extends TextField{
public NameTextField(){
super();
}
public NameTextField(String text){
super(text);
}
public static void nameIsValid(NameTextField input) {
String text = input.getText();
if (text.split(" ").length != 2)
input.setStyle("-fx-text-inner-color: red;");
else
input.setStyle("-fx-text-inner-color: black;");
}
}
import javafx.scene.control.TextField;
import javax.xml.soap.Text;
public class PhoneTextField extends TextField {
public PhoneTextField(){
super();
}
public PhoneTextField(String text){
super(text);
}
public static void phoneIsValid(PhoneTextField input){
String text = input.getText();
if (text.split(" ").length != 2)
input.setStyle("-fx-text-inner-color: red;");
else
return;
}
}
You could do it on the textProperty of the field:
textField.textProperty().addListener((ObservableValue<? extends String> o, String oldValue, String newValue) ->
{
if (!isStringValidPhoneNumber(newValue))
{
textField.setStyle("-fx-border-color: red ; -fx-border-width: 1px ;");
} else
{
textField.setStyle(null);
}
}
public static boolean isStringValidPhoneNumber (String field)
{
// do the validating here
return false;
}
So to start off there is a few things you should re-think such as individually setting the setPromptText(...); to the same thing if you are constantly re-typing the same thing there is a good chance it can be done more efficiently so I created an initialize method that does the things you are re-typing this means when the class is initialized it will run is whatever's in that method I also removed static from the nameIsValid() method as it was not needed as well as the textfield input parameter. Then I fire the name is valid method on the textfield loosing focus as it is a better design. Take a look at the end result below
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
GridPane root = new GridPane();
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(30, 30, 30, 30));
root.setHgap(5.5);
root.setVgap(5.5);
// TextFields
NameTextField firstName = new NameTextField();
// firstName.setPromptText("Name");
// firstName.setOnMouseExited(e -> NameTextField.nameIsValid(firstName));
NameTextField secondName = new NameTextField();
// secondName.setPromptText("Name");
// secondName.setOnMouseExited(e -> NameTextField.nameIsValid(secondName));
NameTextField thirdName = new NameTextField();
// thirdName.setPromptText("Name");
// thirdName.setOnMouseExited(e -> NameTextField.nameIsValid(thirdName));
PhoneTextField firstNumber = new PhoneTextField();
// firstNumber.setPromptText("(###) ###-####");
// firstNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(firstNumber));
PhoneTextField secondNumber = new PhoneTextField();
// secondNumber.setPromptText("(###) ###-####");
// secondNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(secondNumber));
PhoneTextField thirdNumber = new PhoneTextField();
// thirdNumber.setPromptText("(###) ###-####");
// thirdNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(thirdNumber));
// "Create Profiles" button
StackPane btnPane = new StackPane();
Button btn = new Button("Create Profiles");
btnPane.getChildren().add(btn);
StackPane.setAlignment(btn, Pos.CENTER);
//Enable/Disable button depending on if any TextField is empty
btn.disableProperty().bind(firstName.textProperty().isEmpty()
.or(secondName.textProperty().isEmpty()).or(thirdName.textProperty().isEmpty())
.or(firstNumber.textProperty().isEmpty()).or(secondNumber.textProperty().isEmpty())
.or(thirdNumber.textProperty().isEmpty()));
// Layout of window
root.add(firstName, 0, 0);
root.add(secondName, 0, 1);
root.add(thirdName, 0, 2);
root.add(firstNumber, 1, 0);
root.add(secondNumber, 1, 1);
root.add(thirdNumber, 1, 2);
root.add(btnPane, 0, 3, 2, 3);
// Creating scene
Scene scene = new Scene(root);
primaryStage.setTitle("Data Entry GUI");
primaryStage.setScene(scene); primaryStage.show();
}
public static void main(String[] args) { launch(args); }
public class NameTextField extends TextField {
public NameTextField(){
super();
initialize();
}
public NameTextField(String text){
super(text);
initialize();
}
// public static void nameIsValid(NameTextField input) {
private void nameIsValid() {
String text = this.getText();
if (text.split(" ").length != 2)
this.setStyle("-fx-border-color: red; -fx-text-inner-color: red;");
else
this.setStyle("-fx-text-inner-color: black;");
}
private void initialize() {
this.setPromptText("Name");
this.focusedProperty().addListener((arg0, oldPropertyValue, newPropertyValue) -> {
if (oldPropertyValue)
nameIsValid();
});
}
}
public class PhoneTextField extends TextField{
public PhoneTextField(){
super();
initialize();
}
public PhoneTextField(String text){
super(text);
initialize();
}
// public static void phoneIsValid(PhoneTextField input){
private void phoneIsValid(){
String text = this.getText();
if (text.split(" ").length != 2)
this.setStyle("-fx-border-color: red; -fx-text-inner-color: red;");
else
this.setStyle("-fx-text-inner-color: black;");
}
private void initialize() {
this.setPromptText("(###) ###-####");
this.focusedProperty().addListener((arg0, oldPropertyValue, newPropertyValue) -> {
if (oldPropertyValue)
phoneIsValid();
});
}
}
}
i am customizing JavaFX TableView's header.
therefore i add a Graphic to the Label. By clicking the Label of the header i toggle my custom header(two lined). all this is working fine.
The header gets automatically resized so the custom headerfits in.
BUT, when i hide my custom headerthe headerstays large.
What am i missing so the headershrinks again?
i created a MCVE to demonstrate my problem:
public class TableViewHeaderMCVE extends Application {
private final TableView<Person> table = new TableView<>();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
final VBox root = new VBox();
Scene scene = new Scene(root);
stage.setWidth(218);
stage.setHeight(216);
TableColumn colName = new TableColumn("name");
colName.setMinWidth(100);
colName.setSortable(false);
TableColumn colProfession = new TableColumn("profession");
colProfession.setMinWidth(100);
colProfession.setSortable(false);
table.getColumns().addAll(colName, colProfession);
root.getChildren().addAll(table);
stage.setScene(scene);
stage.show();
// apply this after show!
TableViewHeader.installMod(table);
}
public static class TableViewHeader {
public static void installMod(TableView table) {
for (Node n : table.lookupAll(".column-header > .label")) {
if (n instanceof Label) {
new CustomHeaderLabel((Label) n);
}
}
}
}
public static class CustomHeaderLabel extends BorderPane {
protected Label customNode = null;
BooleanProperty expanded = new SimpleBooleanProperty(this, "expanded", false);
public CustomHeaderLabel(final Label parent) {
Label label = new Label(parent.getText());
// custom MenuButton
Button btn = new Button();
btn.setGraphic(new Label("\u2261"));
btn.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ae) {
System.out.println("Hello World");
}
});
TextField filterTextField = new TextField();
filterTextField.promptTextProperty().set("type here to filter");
setCenter(label);
setRight(btn);
setBottom(filterTextField);
EventHandler<MouseEvent> toggleHeader = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
expanded.set(!expanded.get());
}
};
parent.setOnMouseClicked(toggleHeader);
expanded.addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> obs, Boolean oldValue, Boolean value) {
showCustomHeader(value);
}
});
label.textProperty().bind(parent.textProperty());
parent.setGraphic(this);
customNode = parent;
showCustomHeader(expanded.get());
}
protected void showCustomHeader(Boolean value) {
if (value) {
customNode.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
customNode.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
public static class Person {
private final SimpleStringProperty name;
private final SimpleStringProperty profession;
private Person(String name, String profession) {
this.name = new SimpleStringProperty(name);
this.profession = new SimpleStringProperty(profession);
}
public String getName() {
return name.get();
}
public String getProfession() {
return profession.get();
}
}
}
thanks to #James_D for his reply.
after his reply i tested the code on another computer
works on:
JDK 1.8.0_161 on Windows 10
JDK 9.0.4 and JDK 10 on Mac OS X
fails on:
JDK 1.8.0_66-b18 on Windows 7
I have a problem with my current libGDX project.
The game starts with a main menu, where you can click on two buttons. After starting the game, you can pause it through Esc and get to the pause screen, which is very similar to the main menu.
I don't know why, but the buttons in the pause screen are not clickable.
Here is the code of the game screen with the problem:
public class GameScreen implements Screen{
private Texture[] monsterTextures = {Assets.manager.get(("Ressources/DemonHunter.jpg"), Texture.class), Assets.manager.get(("Ressources/WingedDemon.jpg"), Texture.class),
Assets.manager.get(("Ressources/Viking.jpg"), Texture.class), Assets.manager.get(("Ressources/DemonWarrior.jpg"), Texture.class)};
private Image[] monsterImages = {new Image(monsterTextures[0]), new Image(monsterTextures[1]), new Image(monsterTextures[2]), new Image(monsterTextures[3])};
private Stage gameStage = new Stage(), pauseStage = new Stage();
private Table table = new Table();
private Skin menuSkin = Assets.menuSkin;
private TextButton buttonContinue = new TextButton("Continue", menuSkin),
buttonExit = new TextButton("Exit", menuSkin);
private Label title = new Label ("Game", menuSkin);
private int randomMonster;
private int currentMonsterLife = 1 + (int)(Math.random() * ((5-1) + 1));
public static final int GAME_CREATING = 0;
public static final int GAME_RUNNING = 1;
public static final int GAME_PAUSED = 2;
private int gamestatus = 0;
#Override
public void show() {
randomMonster = 0 + (int)(Math.random() * ((3-0) + 1));
gameStage.addActor(monsterImages[randomMonster]);
}
public void newMonster() {
monsterImages[randomMonster].remove();
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
randomMonster = 0 + (int)(Math.random() * ((3-0) + 1));
currentMonsterLife = 1 + (int)(Math.random() * ((5-1) + 1));
gameStage.addActor(monsterImages[randomMonster]);
}
#Override
public void render(float delta) {
if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)) pauseGame();
if(gamestatus == GAME_CREATING) {
buttonContinue.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gamestatus = GAME_RUNNING;
}
});
buttonExit.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.add(title).padBottom(40).row();
table.add(buttonContinue).size(150, 60).padBottom(20).row();
table.add(buttonExit).size(150, 60).padBottom(20).row();
table.setFillParent(true);
pauseStage.addActor(table);
Gdx.input.setInputProcessor(pauseStage);
Gdx.input.setInputProcessor(gameStage);
gamestatus = GAME_RUNNING;
}
if(gamestatus == GAME_RUNNING) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gameStage.act();
gameStage.draw();
if(Gdx.input.justTouched())currentMonsterLife -= 1;
if(currentMonsterLife == 0)newMonster();
}
if(gamestatus == GAME_PAUSED) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
pauseStage.act();
pauseStage.draw();
}
}
public void pauseGame() {
gamestatus = GAME_PAUSED;
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
pauseGame();
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
for(int i = 0; i < monsterTextures.length; i++) {
monsterTextures[i].dispose();
}
gameStage.dispose();
pauseStage.dispose();
menuSkin.dispose();
}
}
And here is the code of the main menu, where the buttons are working:
public class MainMenu implements Screen {
private Stage stage = new Stage();
private Table table = new Table();
private Skin menuSkin = Assets.menuSkin;
private TextButton buttonPlay = new TextButton("Play", menuSkin),
buttonExit = new TextButton("Exit", menuSkin);
private Label title = new Label ("Hunt for Power", menuSkin);
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
#Override
public void show() {
buttonPlay.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
((Game)Gdx.app.getApplicationListener()).setScreen(new GameScreen());
}
});
buttonExit.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.add(title).padBottom(40).row();
table.add(buttonPlay).size(150, 60).padBottom(20).row();
table.add(buttonExit).size(150, 60).padBottom(20).row();
table.setFillParent(true);
stage.addActor(table);
Gdx.input.setInputProcessor(stage);
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
stage.dispose();
}
}
I really hope someone is able to find the solution to this.
Greetings, Joshflux
There is something weird with how you set the InputProcessor:
in the show() method you set the Stage stage as the InputProcessor:
Gdx.input.setInputProcessor(stage);
so far so good, but in the render() method you set it to different stages than the one where your buttons are!
Gdx.input.setInputProcessor(pauseStage);
Gdx.input.setInputProcessor(gameStage);
==> remove this code from the render method! Also you should not have the other code that looks like it should only be executed when creating the screen inside the render() method. It seems like your code results in overlapping stages, buttons & tables and it is unclear which stage currently is set as InputProcessor.
Like #donfuxx said, you should not set your input processor in the render() method, but rather in show().
And you can only set one input processor at a time. Your second call to setInputProcessor replaces the first call. If you want two different stages as input processors, you must combine them with an InputMultiplexer:
public void show(){
Gdx.input.setInputProcessor(new InputMultiplexer(pauseStage, gameStage)); //list them in order of precedence
//...your other code
}