Generate a random number of JButtons in a GUI builder? - java

I'm using a GUI builder to make a simple JFrame that contains a JPanel. I want to add a random number of JButtons to the panel, is it possible for me to do this without having to write my own code for the JPanel? I ask because I am not strong with Swing layouts.
Main class:
public static void main( String[] args )
{
int buttonCount = new Random().nextInt(5)+1;
JFoo foo = new JFoo(buttonCount);
foo.setVisible(true);
}
JFoo class:
public class JFoo extends javax.swing.JFrame {
int buttonCount;
public JFoo() {
initComponents();
}
public JFoo(int buttonCount) {
this.buttonCount = buttonCount;
initComponents();
buttonCountLabel.setText("Button Count: "+buttonCount);
}
private void initComponents() {
//generated code
...
}

Related

How to use multiple instances of a JFrame and access variables from another JFrame form

I am making a sudoku game, in which I have two separate JFrame forms i.e., Home.java and Avg_Game.java
I have made two instances of Avg_Game class in Avg_Game JFrame form.
One instance is used to get variable "Player" from Home.java Jframe and another is to generate sudoku within Avg_Game file.
Now the problem is if I just run the Avg_Game.java file then i it just generate sudoku and don't access the variable "Player" from another Jframe ....... and if I run Home.java file and open Avg_Game Jframe using a button on Home.java file then it is just access variable "Player" but not generates sudoku.But I want both should work...PLease help
/* in Avg_Game.java */
public class Avg_Game extends javax.swing.JFrame {
public Avg_Game() {
}
public Avg_Game(String Om) {
pop = Om;
initComponents();
}
String pop;
JFrame frame = new JFrame();
int[] mat[];
int[] mat_sol[];
int n,sqn,k;
public Avg_Game(int n,int k) {
this.n = n;
this.k = k;
Double sqnd = Math.sqrt(n);
sqn = sqnd.intValue();
mat = new int[n][n];
initComponents();
}
..........
..........
// in main
public static void main(){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Avg_Game(n,k).setVisible(true);
}
});
}
/*in Home.java */
Avg_Game average = new Avg_Game(Player);
average.setVisible(true);

Java: Button Encapsulation

So what I am trying to accomplish is to add ActionListener to a button which is defined in another class, without breaking encapsulation of this button.
My GUI class:
public class GUI extends JFrame {
private JButton button;
public GUI () {
this.button = new JButton ();
}
public void setText (Text text) {
this.button.setText (text);
}
public JButton getButton () {
return this.button;
}
}
My Game class:
public class Game {
private GUI gui;
public Game () {
this.gui = new GUI ();
this.gui.getButton ().addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent evt) {
play ();
}
});
}
public void play () {
this.gui.setText ("Play");
}
}
Then I call a new Game instance in the Main class.
I would like to get rid of the getter in GUI class, otherwise there is no point in using text setter or setters similar to that.
When I add ActionListener to GUI constructor, I have no access to Game methods than. Is there a solution that I don't see?
Normally when I do this, I add an interface that describes the View (GUI), and then have the view implement that interface.
public interface MyView {
void addActionListener( ActionListener l );
}
And the view:
public class GameGui implements MyView {
// lots o' stuff
public void addActionListener( ActionListener l ) {
button.addActionListener( l );
}
}
Then your main code is free from dependencies on what kind of view you actually implement.
public class Main {
public static void main( String... args ) {
SwingUtils.invokeLater( Main::startGui );
}
public static void startGui() {
MyView gui = new GameGui();
gui.addActionListener( ... );
}
}
Don't forget that Swing is not thread safe and must be invoked on the EDT.
Let the GUI add the action listener to the button, let the Game create the action listener:
public class GUI extends JFrame {
public void addActionListenerToButton(ActionListener listener) {
button.addActionListener(listener);
}
....
}
public class Game {
private GUI gui;
public Game () {
this.gui = new GUI ();
this.gui.addActionListenerToButton (new ActionListener () {
public void actionPerformed (ActionEvent evt) {
play ();
}
});
}
...
}
Alternatively just pass in a functional interface instead of a fully built ActionListener.

Java Class Diagram

I'm learning to design a class diagram for java and this is my first attempt. Could you please tell me if it's okay.
Here's the source code
public class DiceRoll1 extends JFrame implements ActionListener {
private JTextField txtNotation;
private JButton btRoll, btShuffle;
private List<Integer> dealtCard;
private History history;
public DiceRoll1() {
initComponents();
dealtCard = new ArrayList<>();
history = new History();
}
public void initComponents() {
//designing the userform
setSize(400, 500);
setLayout(new FlowLayout());
setTitle("Dice Roll");
txtNotation = new JTextField("2d6");
btRoll = new JButton("Roll");
btShuffle = new JButton("Shuffle");
txtNotation.setColumns(20);
getContentPane().add(txtNotation);
getContentPane().add(btRoll);
getContentPane().add(btShuffle);
btRoll.addActionListener(this);
btShuffle.addActionListener(this);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new DiceRoll().setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if (source.equals(btRoll)) {
} else if (source.equals(btShuffle)) {
}
}
public void displayOutput(String message) {
System.out.println(message);
}
}
Here's the diagram that i have drawn using Visio professional:
I think that your diagram isn't too bad but I noticed some things.
the names of your attributes in the code and the diagram are not consistent
You don't need to add Java built-in classes except you extend or implement them or you're told to do so because they unnecessarily inflate your diagram
You should draw an inheritance connection between JFrame and your class
You should draw a realization connection between ActionListeners and your class
Connection types of an UML-Class-Diagram

I have two classes and want to get a variable from one to the other

I have two classes. Draw and DrawGUI. In DrawGUI I have a JPanel. For my JUnit test I need to ask the class Draw for getWidth() and getHeight(). So my code is like the following:
public class Draw {
public static void main(String[] args) throws ColorException {new Draw();}
/** Application constructor: create an instance of our GUI class */
public Draw() throws ColorException { window = new DrawGUI(this); }
protected JFrame window;
public void getWidth(){
}
}
class DrawGUI extends JFrame {
JPanel drawPanel;
public DrawGUI(Draw application) throws ColorException {
super("Draw"); // Create the window
app = application;
drawPanel = new JPanel();
}
}
So how do I implement getWidth? getWidth should return the width from the JPanel drawPanel
One option is to change the weak type you're saving your window under:
public class Draw {
public static void main(String[] args) throws ColorException {new Draw();}
/** Application constructor: create an instance of our GUI class */
public Draw() throws ColorException { window = new DrawGUI(this); }
protected DrawGUI window; // <- is now a DrawGUI
public int getWidth(){
return window.getPanelWidth();
}
}
class DrawGUI extends JFrame {
JPanel drawPanel;
...
public DrawGUI(Draw application) throws ColorException {
super("Draw"); // Create the window
app = application;
drawPanel = new JPanel();
}
public int getPanelWidth() { // <- added method to get panel width
return drawPanel.getWidth();
}
}
There are other options. You could also just make a getter for the whole panel, but then you have less encapsulation.

adding a double to a JTextArea?

im trying to add a double value that represents the stamina of my player into a jTextArea after i click my north button cant seem to do it heres my code:
private void northButtonActionPerformed(java.awt.event.ActionEvent evt)
{
game.playerMove(MoveDirection.NORTH);
update();
double playerStamina = player.getStaminaLevel();
//tried this
String staminaLevel = Double.toString(playerStamina);
jTextArea1.setText("Stamina: " + staminaLevel);
}
im new here sorry if this is not right
heres the main method
public class Main
{
/**
* Main method of Lemur Island.
*
* #param args the command line arguments
*/
public static void main(String[] args)
{
// create the game object
final Game game = new Game();
// create the GUI for the game
final LemurIslandUI gui = new LemurIslandUI(game);
// make the GUI visible
java.awt.EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
gui.setVisible(true);
}
});
}
and heres the class
public class LemurIslandUI extends javax.swing.JFrame
{
private Game game;
private Player player;
/**
* Creates a new JFrame for Lemur Island.
*
* #param game the game object to display in this frame
*/
public LemurIslandUI(final Game game)
{
this.game = game;
initComponents();
createGridSquarePanels();
update();
}
private void createGridSquarePanels() {
int rows = game.getIsland().getNumRows();
int columns = game.getIsland().getNumColumns();
LemurIsland.removeAll();
LemurIsland.setLayout(new GridLayout(rows, columns));
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
GridSquarePanel panel = new GridSquarePanel(game, row, col);
LemurIsland.add(panel);
}
}
}
/**
* Updates the state of the UI based on the state of the game.
*/
private void update()
{
for(Component component : LemurIsland.getComponents())
{
GridSquarePanel gsp = (GridSquarePanel) component;
gsp.update();
}
game.drawIsland();
}
Your class doesn't seem to be implmeneting ActionListener, therefore the action on your button will not be triggered.
Your class declaration should be:
public class LemurIslandUI extends javax.swing.JFrame implements ActionListener
And put the code for your button action inside:
public void actionPerformed(ActionEvent e) {}
Alternatively, you can use an anonymous class to implement the code for your button, instead of making your class implement the ActionListener. Something like:
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionevent)
{
//code
}
});
Try this.
jTextArea1.setText("Stamina: " + player.getStaminaLevel());
Using anything + string does auto casting to string.

Categories