How do I input a string into a JLabel by clicking a JButton? This is just the in
ID: 3859578 • Letter: H
Question
How do I input a string into a JLabel by clicking a JButton?
This is just the interface without the data.
import core.Board;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class BoggleUi
{
private JFrame frame;
private JMenuBar menuBar;
private JMenu game;
private JMenuItem exit;
private JMenuItem newGame;
// Boggle board
private JPanel bogglePanel;
private JButton[][] diceButtons;
// Enter found words
private JPanel wordsPanel;
private JScrollPane scrollPane;
private JTextPane wordsArea;
// time label
private JLabel timeLabel;
private JButton shakeDice;
// Enter current word
private JPanel currentPanel;
private JLabel currentLabel;
private JButton currentSubmit;
// player's score
private JLabel scoreLabel;
// class Board reference object
private Board board;
// ResetGameListener
private ResetGameListener reset;
//Timer
private Timer timer;
private int minutes = 3;
private int seconds = 0;
private int score = 0;
private String chosenLetters = "";
private String newLetters = "";
private int rows;
private int columns;
public BoggleUi(Board inBoard)
{
board = inBoard;
reset = new ResetGameListener();
initComponents();
}
private void initComponents()
{
// Initialize the JFrame
frame = new JFrame("Boggle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(660, 500);
// Initialize the JMenuBar and add to the JFrame
createMenu();
// Initialize the JPane for the current word
setupCurrentPanel();
// Initialize the JPanel for the word entry
setupWordPanel();
// Initialize the JPanel for the Boggle dice
setupBogglePanel();
// initialize the Timer
setupTimer();
// Add everything to the JFrame
frame.setJMenuBar(menuBar);
frame.add(bogglePanel, BorderLayout.WEST);
frame.add(wordsPanel, BorderLayout.CENTER);
frame.add(currentPanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
private void createMenu()
{
menuBar = new JMenuBar();
game = new JMenu("Boggle");
game.setMnemonic('B');
newGame = new JMenuItem("New Game");
newGame.setMnemonic('N');
newGame.addActionListener(reset);
exit = new JMenuItem("Exit");
exit.setMnemonic('E');
exit.addActionListener(new ExitListener());
game.add(newGame);
game.add(exit);
menuBar.add(game);
//////////////////
//currentSubmit.addActionListener(new currentSubmit());
}
private void setupCurrentPanel()
{
currentPanel = new JPanel();
currentPanel.setBorder(BorderFactory.createTitledBorder("Current Word"));
currentLabel = new JLabel();
currentLabel.setBorder(BorderFactory.createTitledBorder("Current Word"));
currentLabel.setMinimumSize(new Dimension(300, 50));
currentLabel.setPreferredSize(new Dimension(300,50));
currentLabel.setHorizontalAlignment(SwingConstants.LEFT);
currentSubmit = new JButton("Submit Word");
currentSubmit.setMinimumSize(new Dimension(200, 100));
currentSubmit.setPreferredSize(new Dimension(200, 50));
scoreLabel = new JLabel();
scoreLabel.setBorder(BorderFactory.createTitledBorder("Score"));
scoreLabel.setMinimumSize(new Dimension(100, 50));
scoreLabel.setPreferredSize(new Dimension(100,50));
currentPanel.add(currentLabel);
currentPanel.add(currentSubmit);
currentPanel.add(scoreLabel);
}
private void setupWordPanel()
{
wordsPanel = new JPanel();
wordsPanel.setLayout(new BoxLayout(wordsPanel, BoxLayout.Y_AXIS));
wordsPanel.setBorder(BorderFactory.createTitledBorder("Enter Words Found"));
wordsArea = new JTextPane();
scrollPane = new JScrollPane(wordsArea);
scrollPane.setPreferredSize(new Dimension(180, 330));
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
timeLabel = new JLabel("3:00");
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
timeLabel.setFont(new Font("Serif", Font.PLAIN, 48));
timeLabel.setPreferredSize(new Dimension(240, 100));
timeLabel.setMinimumSize(new Dimension(240, 100));
timeLabel.setMaximumSize(new Dimension(240, 100));
timeLabel.setBorder(BorderFactory.createTitledBorder("Time Left"));
shakeDice = new JButton("Shake Dice");
shakeDice.setPreferredSize(new Dimension(240, 100));
shakeDice.setMinimumSize(new Dimension(240, 100));
shakeDice.setMaximumSize(new Dimension(240, 100));
shakeDice.addActionListener(reset);
wordsPanel.add(scrollPane);
wordsPanel.add(timeLabel);
wordsPanel.add(shakeDice);
}
private void setupBogglePanel()
{
// counter for the ArrayList of the 16 letters
int counter = 0;
// get new letters for the game
board.shakeDice();
// set up the board for the UI
bogglePanel = new JPanel();
bogglePanel.setLayout(new GridLayout(4, 4));
bogglePanel.setMinimumSize(new Dimension(400, 400));
bogglePanel.setPreferredSize(new Dimension(400, 400));
bogglePanel.setBorder(BorderFactory.createTitledBorder("Boggle Board"));
diceButtons = new JButton[Board.GRID][Board.GRID];
for(int row = 0; row < Board.GRID; row++)
for(int col = 0; col < Board.GRID; col++)
{
diceButtons[row][col] = new JButton();
diceButtons[row][col].setText(board.getGameDice().get(counter));
bogglePanel.add(diceButtons[row][col]);
counter++;
diceButtons[row][col].addActionListener(new dieButton());
}
}
private void setupTimer()
{
timer = new Timer(1000, new TimerListener());
timer.start();
}
private void changeDice()
{
// counter for the ArrayList of the 16 letters
int counter = 0;
// get new letters for the game
board.shakeDice();
for(int row = 0; row < Board.GRID; row++)
for(int col = 0; col < Board.GRID; col++)
{
diceButtons[row][col].setText(board.getGameDice().get(counter));
counter++;
}
}
// inner classes
private class ExitListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent ae)
{
int response = JOptionPane.showConfirmDialog(null, "Confirm to exit Boggle?",
"Exit?", JOptionPane.YES_NO_OPTION);
if (response == JOptionPane.YES_OPTION)
System.exit(0);
}
}
private class TimerListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if(seconds == 0 && minutes == 0)
{
timer.stop();
}
else
{
if(seconds == 0)
{
seconds = 59;
minutes--;
}
else
{
seconds--;
}
}
if(seconds < 10)
{
String strSeconds = "0" + String.valueOf(seconds);
timeLabel.setText(String.valueOf(minutes) + ":" + strSeconds);
}
else
{
timeLabel.setText(String.valueOf(minutes) + ":" + String.valueOf(seconds));
}
}
}
private class ResetGameListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
//this code resets the bogglePanel with new letters
changeDice();
//resets text areas to be ready for a new game
wordsArea.setText(""); //Words found panel is cleared
scoreLabel.setText("0"); //score is reset
currentLabel.setText(""); //currentLabel is reset
timeLabel.setText("3:00"); //timer is 'reset'
// when updating the UI these methods
// performs a layout of the container
bogglePanel.revalidate();
bogglePanel.repaint();
//restarts timer
timer.stop();
minutes = 3;
seconds = 0;
timer.start();
}
}
private class currentSubmit implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
currentLabel.setText(chosenLetters);
}
}
private class dieButton implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton button;
newLetters = e.getActionCommand();
button = (JButton)e.getSource();
chosenLetters += button; // adds selected letter to string
currentLabel.setText(chosenLetters);
for(int i = 0;i < 4;i++ ) { // loops to disable selected button
for(int j = 0; j < 4; j++) {
diceButtons[i][j].setEnabled(true);
if(button == diceButtons[i][j]) {
rows = i;
columns = j;
}
}
}
}
}
}
This is what I get
Explanation / Answer
The most common component button is clickable onscreen region that the user interacts with to perform the user interacts with to perform a single command.
A text label is simply a string of text displayed on screen in a graphical program. Labels often give information or describe others components
Public JButton(String text)//creates a new button
Public JLabel(String text)//creates a new label with the given string as its text
String input = new String();
JButton mbutt = new JButton;
JTextField jtxt = new JTextField();
mbutt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
input = jtxt.getText().toString();
}
});
Now few things before i jump into the code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Tes extends JFrame {
String input;
JTextField jtxt;
JButton mbutt;
public Test(){
//--ALWAYS USE A JPANEL OVER JFRAME, I DID THIS TO KEEP IT SIMPLE FOR U--//
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setComponent();
this.setHandler();
}
public void setComponent(){
jtxt = new JTextField("Hello");
mbutt = new JButton("Button");
this.add(BorderLayout.SOUTH,mbutt);
this.add(BorderLayout.NORTH,jtxt);
}
public void setHandler(){
mbutt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
input = jtxt.getText().toString();
System.out.println("Input Value: "+input);
**//--See your Console Output everytime u press the button--//**
}
});
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
@Override
public void run() {
Tes t = new Tes();
t.setVisible(true);
}
});
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.