Remove buttons in JLabel [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a java swing project that looks like this:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.Box;
import javax.swing.BoxLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class DiceGameReplaceDice extends JFrame
{
private JFrame gameFrame;
private JPanel mainPanel;
private JPanel centerPanel = new JPanel();
private JButton diceArray[];
private DiceListener diceListener = new DiceListener();
private ButtonListener buttonListener = new ButtonListener();
private Random rand = new Random();
private int NUM_DICE = 2;
private String diceImages[] = {"./src/1.png", "./src/2.png", "./src/3.png",
"./src/4.png", "./src/5.png", "./src/6.png"};
public static void main(String[] args)
{
new DiceGameReplaceDice();
}
public DiceGameReplaceDice()
{
// Initialize the frame that holds the game
gameFrame = new JFrame();
gameFrame.setSize(800, 600);
gameFrame.setLocation(300, 100);
gameFrame.setTitle("Dice Game");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add Panel
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
// Instantiate a ButtonListener
buttonListener = new ButtonListener();
// Add 1 Button and 1 Label to a newly created panel
// Add new panel to West
JButton buttonW1 = new JButton("Add Die");
buttonW1.setName("W1");
buttonW1.addActionListener(buttonListener);
JPanel panelWest = new JPanel();
panelWest.setLayout(new BoxLayout(panelWest,BoxLayout.Y_AXIS ));
panelWest.setBackground(new Color(0, 0, 122)); // set to blue
panelWest.add(Box.createVerticalGlue());
panelWest.add(buttonW1);
panelWest.add(Box.createVerticalGlue());
mainPanel.add(panelWest, BorderLayout.WEST);
// Create and display center panel with dice
displayCenterPanel();
// Add mainPanel to frame and display the frame
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
private void displayCenterPanel()
{
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel,BoxLayout.X_AXIS ));
centerPanel.setBackground(new Color(0, 122, 0)); // set to green
centerPanel.add(Box.createHorizontalGlue());
diceArray = new JButton[NUM_DICE];
// Add 2 Buttons to center panel with images of 2 random dice
for (int i=0; i<NUM_DICE; i++)
{
// Create dice button
int dieNum = rand.nextInt(6)+1;
diceArray[i] = new JButton(new ImageIcon(diceImages[dieNum-1]));
diceArray[i].setName("Dice" + i);
diceArray[i].addActionListener(diceListener);
// Add to center panel
centerPanel.add(diceArray[i]);
centerPanel.add(Box.createHorizontalGlue());
}
mainPanel.add(centerPanel, BorderLayout.CENTER);
// Add mainPanel to frame and display the frame
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
// Implement an (inner) class that implements ActionListener
class DiceListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
NUM_DICE -= 1;
displayCenterPanel();
}
}
// Implement an (inner) class that implements ActionListener
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String button = ((JButton)e.getSource()).getName();
System.out.println("Button Pressed: " + button);
if (button.equals("W1"))
NUM_DICE ++;
System.out.println(NUM_DICE);
displayCenterPanel();
}
}
}
When Clicking the "Add Die" button, a die is added to the screen and is correctly formatted. However, when a die is pressed, and the NUM_DICE is decreased, clicking on the die button results in weird overlaps and "ghost buttons". How do you fix this?

The quick fix would be to remove the centerPanel prior to adding the new one. Add the line
mainPanel.remove(centerPanel);
as the first thing you do inside displayCenterPanel.
However, your way of manipulating the layout dynamically leaves a lot to be desired. Instead of creating a new panel each time, just modify the existing one:
public class DiceGame {
private JPanel centerPanel = new JPanel();
private Random rand = new Random();
private int numDice = 2;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DiceGame());
}
public DiceGame() {
JFrame gameFrame = new JFrame();
gameFrame.setSize(800, 600);
gameFrame.setTitle("Dice Game");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JButton buttonW1 = new JButton("Add Die");
buttonW1.addActionListener(e -> {
numDice++;
updateCenterPanel();
});
JPanel panelWest = new JPanel();
panelWest.setLayout(new BoxLayout(panelWest, BoxLayout.Y_AXIS));
panelWest.setBackground(new Color(0, 0, 122));
panelWest.add(Box.createVerticalGlue());
panelWest.add(buttonW1);
panelWest.add(Box.createVerticalGlue());
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
centerPanel.setBackground(new Color(0, 122, 0));
mainPanel.add(panelWest, BorderLayout.WEST);
mainPanel.add(centerPanel);
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
private void updateCenterPanel() {
centerPanel.removeAll();
centerPanel.add(Box.createHorizontalGlue());
JButton[] diceArray = new JButton[numDice];
for (int i = 0; i < numDice; i++) {
diceArray[i] = new JButton(Integer.toString(rand.nextInt(6) + 1));
diceArray[i].setName("Dice" + i);
diceArray[i].addActionListener(e -> {
numDice--;
updateCenterPanel();
});
centerPanel.add(diceArray[i]);
centerPanel.add(Box.createHorizontalGlue());
}
centerPanel.revalidate();
centerPanel.repaint();
}
}
Revalidating and repainting is necessary after invalidating the component hierarchy.
Notes:
Don't create fields when local variables will do.
NUM_DICE is not final, so it should be named numDice.
Calling gameFrame.setVisible(true); when it is already visible does nothing.
When you have a working version of whatever it is you are doing, replace setSize(...) on the JFrame with pack and be sure to calculate the size of its children properly.

Related

How to pass JTextfield info from a JDialog into a JFrame (separate classes)

I have been trying to pass the info of my JTextField that is in a JDialog into my JFrame. Both the JDialog and JFrame are in separate classes. I have tried to store the JTextField into a JLable using the .setText and .getText and then passing the JLable into the JFrame but with no luck.
I know there are many similar questions but I have tried many different approaches but still no luck. I am relatively new to Java and do not know all the in's and out's. Any help is very appreciated!
My code for the JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JPanel;
public class StockApp extends JFrame implements PropertyChangeListener {
private JPanel main = new JPanel();
private JPanel north = new JPanel();
private JPanel center = new JPanel();
private JPanel south = new JPanel();
private JButton buyStock = new JButton("Buy Stock");
private JButton sellStock = new JButton("Sell Stock");
public TestTest variables = new TestTest();
private JLabel stockNameNorth = new JLabel("Stock Name");
private JLabel stockPriceNorth = new JLabel("Stock Price");
String stockName = variables.getStockName();
String stockPrice = variables.getStockPrice();
public StockApp() {
setTitle("StockApp");
getContentPane().setBackground(Color.white);
setSize(400,400);
setLocation(500,200);
setVisible(true);
main.setLayout(new BorderLayout());
north.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
south.setLayout(new FlowLayout());
stockNameNorth.setText(stockName);
stockPriceNorth.setText(stockPrice);
add(main);
north.add(stockNameNorth);
north.add(stockPriceNorth);
south.add(buyStock);
south.add(sellStock);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
main.add(south, BorderLayout.SOUTH);
}
}
And Dialog:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestTest extends JDialog implements ActionListener {
private JPanel main = new JPanel();
private JPanel north = new JPanel();
private JPanel center = new JPanel();
private JPanel south = new JPanel();
private JLabel stockNameLabel = new JLabel("Stock name: ");
private JLabel stockPriceLabel = new JLabel("Stock price(£): ");
private JTextField stockNameIn = new JTextField(5);
private JTextField stockPriceIn = new JTextField(5);
private JButton buttonOK = new JButton("OK");
public JLabel stockPrice = new JLabel();
public JLabel stockName = new JLabel();
public TestTest() {
getContentPane().setBackground(Color.white);
setSize(400,400);
setLocation(500,200);
setModal(false);
setVisible(true);
getRootPane().setDefaultButton(buttonOK);
main.setLayout(new BorderLayout());
north.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
south.setLayout(new FlowLayout());
add(main);
north.add(stockNameLabel);
north.add(stockNameIn);
center.add(stockPriceLabel);
center.add(stockPriceIn);
south.add(buttonOK);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
main.add(south, BorderLayout.SOUTH);
buttonOK.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonOK){
stockName.setText(stockNameIn.getText());
stockPrice.setText(stockPriceIn.getText());
dispose();
new StockApp();
}
}
public String getStockName() {
return stockNameIn.getText();
}
public String getStockPrice() {
return stockPriceIn.getText();
}
}
I am trying to pass the stockName and stockPrice variables from the JDialog into the JFrame. I then want the name and price to display at the top of the JFrame.
For demonstration, what the problem is, we need less Fields and Buttons.
So far, no component of StockApp needs to be accessed from different methods, so there is no need to make them visible outside of the ctor.
More explanations in the code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
public class StockApp extends JFrame {
public StockApp() {
// move those unreferenced panels here, so we don't have to reason about them:
JPanel main = new JPanel();
JPanel north = new JPanel();
JPanel center = new JPanel();
JPanel south = new JPanel();
// add price later, when name works
JButton buyStock = new JButton("Buy Stock");
JLabel stockNameNorth = new JLabel("Stock Name");
// critical change: Make the label, which you like to update,
// accessible by whom it should be updated:
TestTest variables = new TestTest (stockNameNorth);
setTitle ("StockApp");
getContentPane().setBackground(Color.white);
setSize (600,400);
setLocation (500,200);
setVisible (true);
// make the close-frame action terminate the program:
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
main.setLayout (new BorderLayout());
north.setLayout (new FlowLayout());
center.setLayout (new FlowLayout());
south.setLayout (new FlowLayout());
add (main);
north.add (stockNameNorth);
south.add (buyStock);
main.add (north, BorderLayout.NORTH);
main.add (center, BorderLayout.CENTER);
main.add (south, BorderLayout.SOUTH);
}
// Main method to start the damn thing
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new StockApp ();
}
});
}
}
// no need to make this class public in a short test:
class TestTest extends JDialog implements ActionListener {
// this are elements, visible outside the construction phase,
// we need to have access to from more than one method.
// Make this important distinction visible to the reader:
JLabel name;
JTextField stockNameIn = new JTextField (5);
JButton buttonOK = new JButton ("OK");
// add the JLabel to update to the ctor, so that it can't be forgotten
// to be set
public TestTest (JLabel pname) {
// we copy the reference to the label, to have access to it in
// the actionPerformed method.
name = pname;
JPanel main = new JPanel();
JPanel north = new JPanel();
JPanel center = new JPanel();
JPanel south = new JPanel();
JLabel stockNameLabel = new JLabel ("Stock name: ");
getContentPane().setBackground(Color.white);
// different size/location than frame, so that they don't hide
// each other completly
setSize (400,600);
setLocation (700,300);
setModal (false);
setVisible (true);
getRootPane().setDefaultButton(buttonOK);
main.setLayout (new BorderLayout());
north.setLayout (new FlowLayout());
center.setLayout (new FlowLayout());
south.setLayout (new FlowLayout());
add (main);
north.add (stockNameLabel);
north.add (stockNameIn);
south.add (buttonOK);
main.add (north, BorderLayout.NORTH);
main.add (center, BorderLayout.CENTER);
main.add (south, BorderLayout.SOUTH);
buttonOK.addActionListener(this);
}
// here we need access to the button - was it the OK-Button, clicked?
// and the textfield stockNameIn, to read the text
// and the name field from the frame, to set the text
public void actionPerformed(ActionEvent e) {
if (e.getSource () == buttonOK) {
name.setText (stockNameIn.getText());
dispose();
}
}
}

setOpaque is true, but JPanel won't change the background color

I'm making a restaurant menu program with GUI.
I created 3 JPanels and set Background(Color.white) to one of them.
But java will not display that background color.
What's wrong?
Here is my code
please do not take any attention to foods' price and cardLayout. Not finished with coding.
public class MainDishPanel extends JPanel {
JCheckBox box1 = new JCheckBox("Hamburger 5 dollars"),
box2 = new JCheckBox("Pizza 5 dollars"),
box3 = new JCheckBox("French Hot dog 5 dollars");
MainDishPanel(){
setOpaque(true);
setBackground(Color.white);
setLayout(new GridLayout(3,1));
// setBorder();
add(box1);add(box2);add(box3);
setVisible(true);
}
}
class with main method:
import java.awt.BorderLayout;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.*;
public class RestaurantMenu extends JFrame implements ActionListener{
/* private JPanel maindishPanel= new JPanel(),
dessertPanel = new JPanel(),
drinkPanel = new JPanel(),*/
private JPanel leftPanel = new JPanel(),
rightPanel = new JPanel();
private MainDishPanel maindish = new MainDishPanel();
private DessertPanel dessert = new DessertPanel();
private DrinkPanel drink = new DrinkPanel();
private LinkedList<Double>price = new LinkedList<>();
private JButton left = new JButton("previous"),
right = new JButton("next");
public int page =1;
private JLabel pageLabel = new JLabel(String.valueOf(page)),
foodTypeLabel = new JLabel();
CardLayout cards;
GridBagLayout grid;
RestaurantMenu(){
setTitle("Main Dish");
GridBagConstraints gbc = new GridBagConstraints();
add(foodTypeLabel, BorderLayout.NORTH);
add(pageLabel, BorderLayout.SOUTH);
add(leftPanel, BorderLayout.WEST);
add(rightPanel, BorderLayout.EAST);
add(maindish, BorderLayout.CENTER);
grid = new GridBagLayout();
leftPanel.setLayout(grid); leftPanel.add(left);
rightPanel.setLayout(grid); rightPanel.add(right);
right.addActionListener(this);
left.addActionListener(this);
//cards = new CardLayout();
/*cards = (CardLayout)maindishPanel.getLayout();
cards.show(maindishPanel,"Main Dish");*/
setVisible(true);
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==right)
cards.next(this);
if(e.getSource()==left)
cards.previous(this);
}
public static void main (String []args){
RestaurantMenu rm = new RestaurantMenu();
}
}
I don't get any error. Background color just won't be changed to white.
RestaurantMenu class can be looked like a spaghetti code or something strange
because I have plenty things to do with that class.
Inside your MainDishPanel you need to set the background color for the JCheckBox to white, or you can just setOpaque to false on your JCheckBox
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
public class MainDishPanel extends JPanel {
JCheckBox box1 = new JCheckBox("Hamburger 5 dollars"), box2 = new JCheckBox("Pizza 5 dollars"),
box3 = new JCheckBox("French Hot dog 5 dollars");
MainDishPanel() {
setOpaque(true);
setBackground(Color.WHITE);
setLayout(new GridLayout(3, 1));
box1.setBackground(Color.WHITE); // or box1.setOpaque(false);
box2.setBackground(Color.WHITE);
box3.setBackground(Color.WHITE);
add(box1);
add(box2);
add(box3);
setVisible(true);
}
}

What Layout Should I Use for This Project (Java)

I am making a platformer game for a project for class and need to have a chicken character jump on some platforms. I have a start screen and a button, and when the button is clicked, it will change the frame to the first level. When I add the chicken character to the frame as well as the background image, all I can see is the background image. Should I be using a different layout or is there something else I can do. This is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Main extends JFrame {
public Main(){
//Creates Chicken Character
final JLabel chicken = new JLabel(" ");
ImageIcon chick1 = new ImageIcon("chicken.gif");
ImageIcon chick2 = new ImageIcon("chicken2.gif");
chicken.setIcon(chick1);
//Sets Chicken Location
chicken.setLocation(1, 1);
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Creates label for level 0 background image
JLabel background = new JLabel(" ");
ImageIcon back = new ImageIcon("level0.gif");
background.setIcon(back);
//Creates a panel for level 0
final JPanel p5 = new JPanel();
chicken.setLocation(1, 1);
p5.add(background);
//Create first frame for "Start" button
final JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
final JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
final JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//When button is clicked, it changes the level
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(start.isEnabled()) {
remove(p4);
add(new ContentPanel());
add(chicken);
chicken.setLocation(100, 100);
setSize(1440, 500);
setLocale(null);
chicken.isOpaque();
validate();
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String arg[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
}
class ContentPanel extends JPanel{
Image bgimage = null;
ContentPanel() {
MediaTracker mt = new MediaTracker(this);
bgimage = Toolkit.getDefaultToolkit().getImage("level0.gif");
mt.addImage(bgimage, 0);
try {
mt.waitForAll();
} catch (InterruptedException e){
e.printStackTrace();
}
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
g.drawImage(bgimage, 1, 1, null);
}
}
Note: It's been a while since I used the Graphics API
Quick Answer:
You need to draw everything in your paintComponent method. Your drawing routine should check the state of all game objects and draw them accordingly. Right now the panel is drawing the background image - that's it. Add your chicken image the same way you added your bgImage.
Some more things to consider:
If you experience screen flicker look into Double Buffering.
Not to overwhelm you but you might want to do some light reading on game coding. Get a general idea on how to code your game loop and what happens each time the loop is executed.
Since you are using an OO language you should also probably make a Chicken class.
public class Chicken {
private int x;
private int y;
private Image chickenSprtie;
//add get / set for access
}
Or even a general Super Class - Sprite with int x, int y. Or even a "Drawable" interface to forces all your drawable game objects to have common methods....

Set Location of Button on a Window

As practice, I've been trying to make a simple tic tac toe game to see how layouts work in java. Now that I have the base code, with all of the rules and variable checks, I cannot find out how to get the buttons to line up the way I want. I wanted to make a 3x3 grid of buttons, but whenever I try a tutorial online or find someone with a similar problem, it always leads to the buttons not showing up at all. The following code gets the buttons on the screen, but doesn't arrange them.
package game;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
//JPanel
JPanel pnlMainBoard = new JPanel();
//Buttons
JButton btnTest = new JButton("Test");
JButton btnAI = new JButton("A1");
JButton btnBI = new JButton("B1");
JButton btnCI = new JButton("C1");
JButton btnAII = new JButton("A2");
JButton btnBII = new JButton("B2");
JButton btnCII = new JButton("C2");
JButton btnAIII = new JButton("A3");
JButton btnBIII = new JButton("B3");
JButton btnCIII = new JButton("C3");
public Main(){
//Layout
//pnlMainBoard.setLayout(null);
//Game set bounds
btnTest.setBounds(60,400,220,30);
//JPanel bounds
pnlMainBoard.setBounds(800,800,200,100);
//Add buttons to frame
pnlMainBoard.add(btnTest);
pnlMainBoard.add(btnAI);
pnlMainBoard.add(btnBI);
pnlMainBoard.add(btnCI);
pnlMainBoard.add(btnAII);
pnlMainBoard.add(btnBII);
pnlMainBoard.add(btnCII);
pnlMainBoard.add(btnAIII);
pnlMainBoard.add(btnBIII);
pnlMainBoard.add(btnCIII);
add(pnlMainBoard);
//JFrame Properties
setSize(400,400);
setTitle("Ultimate Tic Tac Toe");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
So far this is the only code I've created that successfully puts the buttons on the screen, and when I change it the buttons disappear. How do I make it so I can set the location of the buttons where I want them on the window?
For a 3x3 grid check out the swing grid layout that you can set the JPanel to use like this:
GridLayout grid = new GridLayout(3,3);
JPanel.setLayout(grid);
Where jpanel is the name of your jpanel in your program...
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ThreeByThreeWithButtonLayout {
private JComponent ui = null;
ThreeByThreeWithButtonLayout() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
int gap = 10;
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JButton testButton = new JButton("Test");
JPanel buttonConstrain = new JPanel(
new FlowLayout(FlowLayout.CENTER, gap, gap));
buttonConstrain.add(testButton);
ui.add(buttonConstrain, BorderLayout.PAGE_START);
JPanel gridPanel = new JPanel(new GridLayout(0, 3, 5, 5));
gridPanel.setBorder(new EmptyBorder(gap, gap, gap, gap));
ui.add(gridPanel, BorderLayout.CENTER);
String[] buttonRows = {"A", "B", "C"};
for (int ii = 1; ii < 4; ii++) {
for (String buttonRow : buttonRows) {
JButton b = new JButton(buttonRow + ii);
b.setFont(b.getFont().deriveFont(32f));
gridPanel.add(b);
}
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ThreeByThreeWithButtonLayout o = new ThreeByThreeWithButtonLayout();
JFrame f = new JFrame("3x3 + Button");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
GridLayout makes some rows and columns to your frame/panel like this :
GridLayout grid = new GridLayout(3,3);
Jpanel.setLayout(grid);

how can I make this class an applet

I have the following class which is a simple gui, and I would like to make it an applet so it can be displayed in the browser. I know how to embed the code into an html page(got that done)... but how can make my class an applet? Also, I assuming I don't need a web server just to display the applet in my browser...
package tester1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PanelTest implements ActionListener {
JFrame frame;
JLabel inputLabel;
JLabel outputLabel;
JLabel outputHidden;
JTextField inputText;
JButton button;
JButton clear;
JButton about;
public PanelTest() {
frame = new JFrame("User Name");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2, 10, 10));
//creating first row
JPanel row1 = new JPanel();
inputLabel = new JLabel("Your Name");
inputText = new JTextField(15);
// FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row1.setLayout(flow1);
row1.add(inputLabel);
row1.add(inputText);
frame.add(row1);
//creating second row
JPanel row2 = new JPanel();
button = new JButton("Display");
clear = new JButton("Clear");
about = new JButton("About");
button.addActionListener(this);
clear.addActionListener(this);
about.addActionListener(new displayAbout());
row2.add(button);
row2.add(clear);
row2.add(about);
frame.add(row2);
//creating third row
JPanel row3 = new JPanel();
outputLabel = new JLabel("Output:", JLabel.LEFT);
outputHidden = new JLabel("", JLabel.RIGHT);
// FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row3.setLayout(flow2);
row3.add(outputLabel);
row3.add(outputHidden);
frame.add(row3);
frame.pack();
frame.setVisible(true);
}
//same method listen for two different events
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Display")) {
outputHidden.setText(inputText.getText());
}
if(command.equals("Clear")) {
outputHidden.setText("");
inputText.setText("");
}
}
//another way to listen for events
class displayAbout implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Username 1.1 \n by Jorge L. Vazquez");
}
}
public static void main(String[] args) {
PanelTest frameTest = new PanelTest();
}
}
Use a JApplet rather than a JFrame. Make sure you read the relevant Java Tutorial, which covers the applet lifecycle methods like init, start, stop, and destroy.
As a side note, you should not be building your UI outside of the event dispatch thread.
Use a JApplet instead of a JFrame like veer said, but you must also remove frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, frame.pack();, and frame.setVisible(true);
Also, replace main(String[] args) with init().

Categories