Align textView and Image on same line JAVA [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 5 years ago.
Improve this question
I created the Food tab using code below
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
addIt(tabbedPane, "Foods");
addIt1(tabbedPane, "Drinks");
addIt1(tabbedPane, "Desserts");
tabbedPane.setBounds(10, 11, 400, 450);
frame.getContentPane().add(tabbedPane);
Here the addIt methods
static void addIt(JTabbedPane tabbedPane, String text) throws IOException {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JTextField textField = new JTextField(2);
BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\MedSalad.png"));
Image scaled = myPicture.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel = new JLabel("Salad",new ImageIcon(scaled),JLabel.CENTER);
picLabel.setHorizontalTextPosition(JLabel.CENTER);
picLabel.setVerticalTextPosition(JLabel.BOTTOM);
JTextField textField1 = new JTextField(2);
BufferedImage myPicture1 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\JapanesePanNoodles.png"));
Image scaled1 = myPicture1.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel1 = new JLabel("Japanese Noodles",new ImageIcon(scaled1),JLabel.CENTER);
picLabel1.setHorizontalTextPosition(JLabel.CENTER);
picLabel1.setVerticalTextPosition(JLabel.BOTTOM);
JTextField textField2 = new JTextField(2);
BufferedImage myPicture2 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\Spaghetti.png"));
Image scaled2 = myPicture2.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel2 = new JLabel("Spaghetti",new ImageIcon(scaled2),JLabel.CENTER);
picLabel2.setHorizontalTextPosition(JLabel.CENTER);
picLabel2.setVerticalTextPosition(JLabel.BOTTOM);
JTextField textField3 = new JTextField(2);
BufferedImage myPicture3 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\PadThai.png"));
Image scaled3 = myPicture3.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel3 = new JLabel("Spaghetti Meat Balls",new ImageIcon(scaled3),JLabel.CENTER);
picLabel3.setHorizontalTextPosition(JLabel.CENTER);
picLabel3.setVerticalTextPosition(JLabel.BOTTOM);
JTextField textField4 = new JTextField(2);
BufferedImage myPicture4 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\RamenNoodles.png"));
Image scaled4 = myPicture4.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel4 = new JLabel("Noodles",new ImageIcon(scaled4),JLabel.CENTER);
picLabel4.setHorizontalTextPosition(JLabel.CENTER);
picLabel4.setVerticalTextPosition(JLabel.BOTTOM);
JTextField textField5 = new JTextField(2);
BufferedImage myPicture5 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\SpaghettiAndMeatBalls.png"));
Image scaled5 = myPicture5.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel5 = new JLabel("Kids Spaghetti",new ImageIcon(scaled5),JLabel.CENTER);
picLabel5.setHorizontalTextPosition(JLabel.CENTER);
picLabel5.setVerticalTextPosition(JLabel.BOTTOM);
JTextField textField6 = new JTextField(2);
BufferedImage myPicture6 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\chickenRice.jpg"));
Image scaled6 = myPicture6.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel6 = new JLabel("Chicken Rice",new ImageIcon(scaled6),JLabel.CENTER);
picLabel6.setHorizontalTextPosition(JLabel.CENTER);
picLabel6.setVerticalTextPosition(JLabel.BOTTOM);
JTextField textField7 = new JTextField(2);
BufferedImage myPicture7 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\thaiFood.jpeg"));
Image scaled7 = myPicture7.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel7 = new JLabel("Thai Food",new ImageIcon(scaled7),JLabel.CENTER);
picLabel7.setHorizontalTextPosition(JLabel.CENTER);
picLabel7.setVerticalTextPosition(JLabel.BOTTOM);
JTextField textField8 = new JTextField(2);
BufferedImage myPicture8 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\vietnamFood.jpg"));
Image scaled8 = myPicture8.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel8 = new JLabel("Vietnam Food",new ImageIcon(scaled8),JLabel.CENTER);
picLabel8.setHorizontalTextPosition(JLabel.CENTER);
picLabel8.setVerticalTextPosition(JLabel.BOTTOM);
panel.add(picLabel);
panel.add(textField);
panel.add(picLabel1);
panel.add(textField1);
panel.add(picLabel2);
panel.add(textField2);
panel.add(picLabel3);
panel.add(textField3);
panel.add(picLabel4);
panel.add(textField4);
panel.add(picLabel5);
panel.add(textField5);
panel.add(picLabel6);
panel.add(textField6);
panel.add(picLabel7);
panel.add(textField7);
panel.add(picLabel8);
panel.add(textField8);
tabbedPane.addTab(text, panel);
}
And here the screen shot of Food Tab
MainClass
public class FoodOrdering {
private JFrame frame;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FoodOrdering window = new FoodOrdering();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public FoodOrdering() throws IOException {
initialize();
}
private void initialize() throws IOException {
frame = new JFrame();
frame.setBounds(100, 100, 700, 550);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setLocationRelativeTo(null);
JLabel lblFoodOrdered = new JLabel("Food Ordered");
lblFoodOrdered.setBounds(529, 11, 81, 14);
frame.getContentPane().add(lblFoodOrdered);
TextArea textArea = new TextArea();
textArea.setBounds(462, 31, 199, 275);
frame.getContentPane().add(textArea);
JLabel lblTotal = new JLabel("Total : ");
lblTotal.setBounds(519, 315, 46, 14);
frame.getContentPane().add(lblTotal);
textField = new JTextField();
textField.setBounds(575, 312, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnOrder = new JButton("Order");
btnOrder.setBounds(521, 352, 89, 23);
frame.getContentPane().add(btnOrder);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
addIt(tabbedPane, "Foods");
addIt1(tabbedPane, "Drinks");
addIt1(tabbedPane, "Desserts");
tabbedPane.setBounds(23, 11, 400, 450);
frame.getContentPane().add(tabbedPane);
}
How can I align the picture, JTextField in the same line ?

I don't have images to test, there's no valid MCVE in the question, however from what I see in it you could try (in order of preference)
Using GridBagLayout instead of FlowLayout that you're currently using, this will help placing your images in a grid and align them in it.
Using GridLayout which will make your images and JTextFields the same size and placing them in a grid of the same size, each component.
Resizing your images to be all the same size, before getting their getScaledInstance(...)
BTW, this tabbedPane.setBounds(10, 11, 400, 450); suggests that in some point of your code, you're using null layout, you should know that null layout is evil and thus it's use is frowned upon. If you're not using null layout anywhere (we can't know because we don't have that code in the question), then, that line is needed.
Also, you could improve your code by wrapping all the same functionality like this:
JTextField textField1 = new JTextField(2);
BufferedImage myPicture1 = ImageIO.read(new File("C:\\Users\\tony\\Desktop\\JapanesePanNoodles.png"));
Image scaled1 = myPicture1.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel1 = new JLabel("Japanese Noodles",new ImageIcon(scaled1),JLabel.CENTER);
picLabel1.setHorizontalTextPosition(JLabel.CENTER);
picLabel1.setVerticalTextPosition(JLabel.BOTTOM);
inside a method where it receives the image name and label text, as the rest of the code is identical to the other ones, and then you could call that method inside a loop, that could really improve the code written by you, legibility and simplicity.
From my above recommendations, you can use GridBagLayout using the GridBagConstraints to place your elements where you want, avoiding the use of null layout:
frame.getContentPane().setLayout(null); //COMPLETELY WRONG!!!!!!
In this example, I used two images of different sizes, so, you can see, that even like that, your fields will stay the same size.
The following code is a MCVE, the one you posted isn't (and I'm surprised of you having almost 3K rep not knowing how to make a proper MCVE)
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class FoodMenu {
private JFrame frame;
private JPanel pane;
private GridBagConstraints gbc;
private JLabel[] foodLabel;
private JTextField[] qtyField;
private static final int ELEMENTS = 9;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new FoodMenu().createAndShowGui());
}
private void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
pane = new JPanel();
pane.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
foodLabel = new JLabel[ELEMENTS];
qtyField = new JTextField[ELEMENTS];
ImageIcon icon = null, icon2 = null;
try {
URL url = new URL("https://image.flaticon.com/icons/png/128/148/148836.png");
URL url2 = new URL("https://i.stack.imgur.com/IucNt.png");
BufferedImage img = ImageIO.read(url);
icon = new ImageIcon(img);
BufferedImage img2 = ImageIO.read(url2);
icon2 = new ImageIcon(img2);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < ELEMENTS; i++) {
foodLabel[i] = new JLabel(i % 2 == 0 ? icon : icon2);
qtyField[i] = new JTextField(3);
}
gbc.gridx = 0;
for (int i = 0; i < ELEMENTS; i++) {
if (i % 3 == 0) {
gbc.gridy++;
gbc.gridx = 0;
}
pane.add(foodLabel[i], gbc);
gbc.gridx++;
pane.add(qtyField[i], gbc);
gbc.gridx++;
}
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
But how can I display the food label below the food image ?
Change the for loop as below
gbc.gridx = 0;
for (int i = 0; i < ELEMENTS; i++) {
if (i % 3 == 0) {
gbc.gridy += 2;
gbc.gridx = 0;
}
pane.add(foodLabel[i], gbc);
gbc.gridy++;
pane.add(qtyField[i], gbc);
gbc.gridx++;
gbc.gridy--;
}

Related

I want my button not in the same row as my choose buttons in my gui? How will I do that?

How do I add a break to put my "Make pokemon" buttons and textarea not in the same row as my "Pokemon choice." I'm trying to put an empty JLabel, but I don't think it works.
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton(" Make Pokemon ");
private JButton bClear = new JButton(" Clear ");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel();
private JPanel bottomSubPanel = new JPanel();
private GUIListener listener = new GUIListener();
private Choice chSpe = new Choice();
private JLabel lEmp = new JLabel(" ");
private PokemonGUILizylf st;
private final int capacity = 10;
private PokemonGUILizylf[ ] stArr = new PokemonGUILizylf[capacity];
private int count = 0;
private String sOut = new String("");
private JTextArea textArea = new JTextArea(400, 500);
private JTextArea textArea2 = new JTextArea(400, 500);
private JScrollPane scroll = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lEmp = new JLabel(" ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
chSpe.add("Choose");
chSpe.add("Bulbasaur");
chSpe.add("Venusaur");
chSpe.add("Ivysaur");
chSpe.add("Squirtle");
chSpe.add("Wartortle");
chSpe.add("Blastoise");
chSpe.add("Charmander");
chSpe.add("Charmeleon");
chSpe.add("Charizard");
centerSubPanel.add(lSpe);
centerSubPanel.add(chSpe);
centerSubPanel.add(lEmp);
centerSubPanel.add(bDone);
centerSubPanel.add(lNew);
textArea.setPreferredSize(new Dimension(500, 200));
textArea.setEditable(false);
textArea2.setPreferredSize(new Dimension(500, 200));
textArea2.setEditable(false);
textArea.setBackground(Color.white);
textArea.setEditable(false);
scroll.setBorder(null);
centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
bottomSubPanel.add(lMsg);
bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
This is what my GUI looks like:
enter image description here
But it should show like this:
enter image description here
Can someone explain to me how I can do that?
Use a different layout manager (other then default FlowLayout which JPanel uses)
See Laying Out Components Within a Container for more details.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new PokemonPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
// private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton("Make Pokemon ");
private JButton bClear = new JButton("Clear");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel(new GridBagLayout());
private JPanel bottomSubPanel = new JPanel();
// private GUIListener listener = new GUIListener();
private JComboBox<String> chSpe = new JComboBox<>();
private JLabel lEmp = new JLabel(" ");
// private PokemonGUILizylf st;
private final int capacity = 10;
// private PokemonGUILizylf[] stArr = new PokemonGUILizylf[capacity];
// private int count = 0;
// private String sOut = new String("");
// private JTextArea textArea = new JTextArea(400, 500);
// private JTextArea textArea2 = new JTextArea(400, 500);
//
// private JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
// JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
// this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
DefaultComboBoxModel<String> chSpeModel= new DefaultComboBoxModel<>();
chSpeModel.addElement("Choose");
chSpeModel.addElement("Bulbasaur");
chSpeModel.addElement("Venusaur");
chSpeModel.addElement("Ivysaur");
chSpeModel.addElement("Squirtle");
chSpeModel.addElement("Wartortle");
chSpeModel.addElement("Blastoise");
chSpeModel.addElement("Charmander");
chSpeModel.addElement("Charmeleon");
chSpeModel.addElement("Charizard");
chSpe.setModel(chSpeModel);
centerSubPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.LINE_END;
centerSubPanel.add(lSpe, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
centerSubPanel.add(chSpe);
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy++;
centerSubPanel.add(bDone, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
centerSubPanel.add(lNew, gbc);
gbc.gridx++;
gbc.gridheight = gbc.REMAINDER;
centerSubPanel.add(new JScrollPane(new JTextArea(10, 10)), gbc);
// textArea.setEditable(false);
// textArea2.setEditable(false);
//
// textArea.setBackground(Color.white);
// textArea.setEditable(false);
// scroll.setBorder(null);
// centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
// scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
// bottomSubPanel.add(lMsg);
// bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
// bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
}
}
Also, avoid using setPreferredSize, let the layout managers do their job. In the example I'm used insets (from GridBagConstraints) and an EmptyBorder to add some additional space around the components
Also, be careful of using AWT components (ie Choice), they don't always play nicely with Swing. In this case, you should be using JComboBox

How to increase the width of JTextField in Tab?

In Food Tab, I want to achieve this
But I only able to get this
How can I increase the width of the JTextField which are in Food Tab ? Below is my code
public class FoodOrdering {
static private JFrame frame;
static private JTextField textField;
static private GridBagConstraints gbc;
static private JLabel[] foodLabel;
static private JLabel[] labels;
static private JTextField[] qtyField;
static private JLabel[] foodImage;
static private File[] file;
private static final int ELEMENTS = 9;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FoodOrdering window = new FoodOrdering();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* #throws IOException
*/
public FoodOrdering() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
*
* #throws IOException
*/
static void initialize() throws IOException {
frame = new JFrame();
frame.setBounds(100, 100, 700, 550);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setLocationRelativeTo(null);
JLabel lblFoodOrdered = new JLabel("Food Ordered");
lblFoodOrdered.setBounds(529, 11, 81, 14);
frame.getContentPane().add(lblFoodOrdered);
TextArea textArea = new TextArea();
textArea.setBounds(462, 31, 199, 275);
frame.getContentPane().add(textArea);
JLabel lblTotal = new JLabel("Total : ");
lblTotal.setBounds(519, 315, 46, 14);
frame.getContentPane().add(lblTotal);
textField = new JTextField();
textField.setBounds(575, 312, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnOrder = new JButton("Order");
btnOrder.setBounds(521, 352, 89, 23);
frame.getContentPane().add(btnOrder);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
addIt(tabbedPane, "Foods");
addIt1(tabbedPane, "Drinks");
addIt1(tabbedPane, "Desserts");
tabbedPane.setBounds(23, 11, 400, 450);
frame.getContentPane().add(tabbedPane);
frame.setVisible(true);
}
static void addIt1(JTabbedPane tabbedPane, String text) {
JLabel label = new JLabel(text);
JButton button = new JButton(text);
JPanel panel = new JPanel();
panel.add(label);
panel.add(button);
tabbedPane.addTab(text, panel);
}
static void addIt(JTabbedPane tabbedPane, String text) throws IOException {
JPanel panel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(1, 1, 1, 1);
foodImage = new JLabel[ELEMENTS];
foodLabel = new JLabel[ELEMENTS];
labels = new JLabel[ELEMENTS];
qtyField = new JTextField[ELEMENTS];
file = new File[ELEMENTS];
try {
file[0] = new File("C:\\Users\\tony\\Desktop\\MedSalad.png");
file[1] = new File("C:\\Users\\tony\\Desktop\\JapanesePanNoodles.png");
file[2] = new File("C:\\Users\\tony\\Desktop\\Spaghetti.png");
file[3] = new File("C:\\Users\\tony\\Desktop\\PadThai.png");
file[4] = new File("C:\\Users\\tony\\Desktop\\RamenNoodles.png");
file[5] = new File("C:\\Users\\tony\\Desktop\\SpaghettiAndMeatBalls.png");
file[6] = new File("C:\\Users\\tony\\Desktop\\chickenRice.jpg");
file[7] = new File("C:\\Users\\tony\\Desktop\\thaiFood.jpeg");
file[8] = new File("C:\\Users\\tony\\Desktop\\vietnamFood.jpg");
foodLabel[0] = new JLabel("Salad");
foodLabel[1] = new JLabel("Japanese Noodles");
foodLabel[2] = new JLabel("Spaghetti");
foodLabel[3] = new JLabel("Spaghetti Meat Balls");
foodLabel[4] = new JLabel("Noodles");
foodLabel[5] = new JLabel("Kids Spaghetti");
foodLabel[6] = new JLabel("Chicken Rice");
foodLabel[7] = new JLabel("Thai Food");
foodLabel[8] = new JLabel("Vietnam Food");
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < ELEMENTS; i++) {
Image image = ImageIO.read(file[i]);
Image imageScaled = image.getScaledInstance(80, 95, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(imageScaled);
qtyField[i] = new JTextField(3);
foodImage[i] = new JLabel(imageIcon);
}
gbc.gridx = 0;
for (int i = 0; i < ELEMENTS; i++) {
if (i % 3 == 0) {
gbc.gridy += 2;
gbc.gridx = 0;
}
panel.add(foodImage[i], gbc);
gbc.gridy++;
panel.add(foodLabel[i], gbc);
gbc.gridy--;
gbc.gridx++;
panel.add(qtyField[i], gbc);
gbc.gridx++;
tabbedPane.addTab(text, panel);
}
}
public void setVisible(boolean b) throws IOException {
}
}
The JTextfield objects are so narrow because of a very old "bug" in GridBagLayout which causes it to ignore the preferred size of its contents.
There are several possible ways to work-around this bug:
Create a class called PreferredGridBagLayout as explained in the link and use that instead of GridBagLayout.
Set the minimum size of each of your qtyField instances with qtyField[i].setMinimumSize(qtyField[i].getPreferredSize()).
Create subclasses of JTextField which override the method getMinimumSize() to return the same value as getPreferredSize(), or some other reasonable minimum size.
Because this problem is so common when using GridBagLayout, solution #1 is the easiest in the long term.
Afterwards, you'll need to make your tabbedPane object a little wider, or switch to a layout manager in the main panel that automatically determines the size of the tabbed pane.
There are multiple things that could be improved in your code. Creating good layouts in Swing is not easy, and you will need much more work to make a pretty layout. But this will solve your problem with collapsing text fields.
This problem simply can be solved by setting the
qtyField[i].setMinimumSize(new Dimension(33,20));
function. The reason for setting minimum size is that the GridBagLayout dont have enough space to arrange all those components properly so it only takes the minimum size of the empty textField.
Just add the code after the line
qtyField[i] = new JTextField(3);
and you will be also needed to increase the width of tabbedPane a little bit more to make the components(qtyField) visible
Instead of using null layout. use some other layout like border layout. Then use just one line:
frame.pack();
This will display all the components at their preferred sizes.
Just a coding practice: instead of setting bounds use panels to add components and then add these panels to a main panel.
Like use one different panel to add your Jlabel of food ordered, textarea, Jlabel for order and order button. And then add that panel to your main panel.
Hope you understand. :)

JTable not showing up on JFrame (Java)

I'm having a problem with a JFrame not showing a JTable that is added to it. I've tried getContentPane().add(..), I've switched to just add to keep the code a little shorter. Any help is more than appreciated!
package com.embah.Accgui;
import java.awt.*;
import javax.swing.*;
public class accCreator extends JFrame {
private String[] columnNames = {"Username", "Password", "Members", "World"};
private Object[][] data = {{"b", "b", "b", "b"},
{ "e", "e", "e", "e"}};
private JTable tbl_Accounts;
private JScrollPane scrollPane;
private JLabel lbl_Account = new JLabel();
private JLabel lbl_Username = new JLabel();
private JLabel lbl_Password = new JLabel();
private JLabel lbl_Homeworld = new JLabel();
private JButton btn_Select = new JButton();
private JButton btn_Addacc = new JButton();
private JButton btn_Delacc = new JButton();
private JTextArea txt_Username = new JTextArea();
private JTextArea txt_Password = new JTextArea();
private JTextArea txt_Homeworld = new JTextArea();
private JCheckBox cbox_Members = new JCheckBox();
private JCheckBox cbox_RanWrld = new JCheckBox();
public accCreator() {
setLayout(null);
setupGUI();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setupGUI() {
tbl_Accounts = new JTable(data, columnNames);
tbl_Accounts.setLocation(5, 30);
tbl_Accounts.setPreferredScrollableViewportSize(new Dimension(420, 250));
tbl_Accounts.setFillsViewportHeight(true);
tbl_Accounts.setVisible(true);
add(tbl_Accounts);
scrollPane = new JScrollPane(tbl_Accounts);
add(scrollPane);
lbl_Account.setLocation(4, 5);
lbl_Account.setSize(100, 20);
lbl_Account.setText("Select Account:");
add(lbl_Account);
lbl_Username.setLocation(5, 285);
lbl_Username.setSize(70, 20);
lbl_Username.setText("Username:");
add(lbl_Username);
lbl_Password.setLocation(5, 310);
lbl_Password.setSize(70, 20);
lbl_Password.setText("Password:");
add(lbl_Password);
lbl_Homeworld.setLocation(310, 310);
lbl_Homeworld.setSize(80, 20);
lbl_Homeworld.setText("Home World:");
add(lbl_Homeworld);
btn_Select.setLocation(305, 5);
btn_Select.setSize(120, 20);
btn_Select.setText("Select Account");
add(btn_Select);
btn_Addacc.setLocation(300, 285);
btn_Addacc.setSize(60, 20);
btn_Addacc.setText("Add");
btn_Addacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String worldSel = "";
if(cbox_RanWrld.isSelected()){
worldSel = "Random";
} else {
worldSel = txt_Homeworld.getText();
}
Object[] row = {txt_Username.getText(), txt_Password.getText(), cbox_Members.isSelected(), worldSel};
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
model.addRow(row);
}
});
add(btn_Addacc);
btn_Delacc.setLocation(365, 285);
btn_Delacc.setSize(60, 20);
btn_Delacc.setText("Del");
btn_Delacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
}
});
add(btn_Delacc);
txt_Username.setLocation(80, 285);
txt_Username.setSize(100, 20);
txt_Username.setText("");
txt_Username.setRows(5);
txt_Username.setColumns(5);
add(txt_Username);
txt_Password.setLocation(80, 310);
txt_Password.setSize(100, 20);
txt_Password.setText("");
txt_Password.setRows(5);
txt_Password.setColumns(5);
txt_Password.setTabSize(0);
add(txt_Password);
txt_Homeworld.setLocation(395, 310);
txt_Homeworld.setSize(30, 20);
txt_Homeworld.setText("82");
txt_Homeworld.setRows(5);
txt_Homeworld.setColumns(5);
txt_Homeworld.setTabSize(0);
add(txt_Homeworld);
cbox_Members.setLocation(185, 285);
cbox_Members.setSize(80, 20);
cbox_Members.setText("Members");
cbox_Members.setSelected(false);
add(cbox_Members);
cbox_RanWrld.setLocation(185, 310);
cbox_RanWrld.setSize(115, 20);
cbox_RanWrld.setText("Random World");
cbox_RanWrld.setSelected(false);
add(cbox_RanWrld);
setTitle("Account Manager");
setSize(440, 370);
setVisible(true);
setResizable(false);
}
public static void main(String args[]) {
new accCreator();
}
}
I know thats not the problem tho because everything else shows up just fine
Oh... really? Not in my computer...
Let's have a picture of your actual GUI shown in my PC:
Does the GUI looks the same in your computer? I bet no.
But... why does it looks like that in my PC?
Well, as stated above in the comments by #MadProgrammer this is because of the setLayout(null); line. You might want to read Why is it frowned upon to use a null layout in Java Swing? for more information.
Now, that being said, you should also want to read and learn how to use the various layout managers that will let you create complex GUIs.
In your code you never set the location / bounds for scrollPane, and the size of it, so the component has a default size of 0, 0.
But... I think it's better to show you how you can get a really similar GUI (I'm in a hurry so I didn't make an even more similar GUI). You can copy-paste my code and see the same output (with slight differences because of the OS maybe) but text won't be cropped.
The code that produces the above image is this one:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AccountCreator {
private JFrame frame;
private JPanel mainPane;
private JPanel topPane;
private JPanel tablePane;
private JPanel bottomPane;
private JLabel selectAccountLabel;
private JLabel userNameLabel;
private JLabel passwordLabel;
private JLabel homeWorldLabel;
private JTextField userNameField;
private JTextField homeWorldField;
private JPasswordField passwordField;
private JCheckBox membersBox;
private JCheckBox randomBox;
private JButton selectAccountButton;
private JButton addButton;
private JButton deleteButton;
private JTable table;
private JScrollPane scroll;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new AccountCreator().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
int rows = 30;
int cols = 3;
String[][] data = new String[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = i + "-" + j;
}
}
String[] columnNames = { "Column1", "Column2", "Column3" };
table = new JTable(data, columnNames);
scroll = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
table.setPreferredScrollableViewportSize(new Dimension(420, 250));
table.setFillsViewportHeight(true);
selectAccountLabel = new JLabel("Select Account");
userNameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
homeWorldLabel = new JLabel("Home world");
selectAccountButton = new JButton("Select Account");
addButton = new JButton("Add");
deleteButton = new JButton("Del");
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
homeWorldField = new JTextField(3);
membersBox = new JCheckBox("Members");
randomBox = new JCheckBox("Random world");
topPane = new JPanel();
topPane.setLayout(new BorderLayout());
topPane.add(selectAccountLabel, BorderLayout.WEST);
topPane.add(selectAccountButton, BorderLayout.EAST);
tablePane = new JPanel();
tablePane.add(scroll);
bottomPane = new JPanel();
bottomPane.setLayout(new GridLayout(0, 5, 3, 3));
bottomPane.add(userNameLabel);
bottomPane.add(userNameField);
bottomPane.add(membersBox);
bottomPane.add(addButton);
bottomPane.add(deleteButton);
bottomPane.add(passwordLabel);
bottomPane.add(passwordField);
bottomPane.add(randomBox);
bottomPane.add(homeWorldLabel);
bottomPane.add(homeWorldField);
mainPane = new JPanel();
mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.PAGE_AXIS));
frame.add(topPane, BorderLayout.NORTH);
frame.add(tablePane, BorderLayout.CENTER);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also, you might have noticed that the main() method is different, well, the code inside it is placing the program on the Event Dispatch Thread (EDT).
So, be sure to include it in your future programs

Set Image to Button and process ActionListener in Puzzle Game using Java

I only learn Java Swing 1 week so I tried complete some exercises. This is my code. I set 9 icon to 9 button but it doesn't show on button.
package mypack;
import java.awt.Color;
import javax.swing.*;
public class PuzzleGame extends JFrame{
static JButton bt1,bt2,bt3,bt4,bt5,bt6,bt7,bt8,bt9,btNew,btExit;
static JLabel move, moveNum, time, timeNum;
public PuzzleGame(){
createMyGUI();
}
public static void createMyGUI(){
JFrame jf = new JFrame("Game Puzzle Java");
JPanel jpl = new JPanel();
Icon icSpace = new ImageIcon("images/0.png");
Icon ic1 = new ImageIcon("images/1.png");
Icon ic2 = new ImageIcon("images/2.png");
Icon ic3 = new ImageIcon("images/3.png");
Icon ic4 = new ImageIcon("images/4.png");
Icon ic5 = new ImageIcon("images/5.png");
Icon ic6 = new ImageIcon("images/6.png");
Icon ic7 = new ImageIcon("images/7.png");
Icon ic8 = new ImageIcon("images/8.png");
jpl.setSize(100,100);
jpl.setBounds(480, 50, 200, 200);
jpl.setBackground(Color.BLUE);
move = new JLabel("Move:");
move.setBounds(480,10,50,20);
moveNum = new JLabel("0");
moveNum.setBounds(530, 10, 50, 20);
time = new JLabel("Time:");
time.setBounds(580, 10, 50, 20);
timeNum = new JLabel("0");
timeNum.setBounds(630,10,50,20);
btNew = new JButton("New Game");
btNew.setBounds(480, 270, 200, 80);
btExit = new JButton("Exit");
btExit.setBounds(480, 370, 200, 80);
jf.add(move);
jf.add(moveNum);
jf.add(time);
jf.add(timeNum);
jf.add(btNew);
jf.add(btExit);
jf.add(jpl);
jf.setSize(700, 500);
jf.setLocation(300,20);
jf.setLayout(null);
jf.setResizable(false);
jf.setVisible(true);
bt1 = new JButton();
bt1.setBounds(10, 10, 150, 150);
bt1.setIcon(ic1);
bt2 = new JButton();
bt2.setBounds(160, 10, 150, 150);
bt2.setIcon(ic2);
bt3 = new JButton();
bt3.setBounds(310, 10, 150, 150);
bt3.setIcon(ic3);
bt4 = new JButton();
bt4.setBounds(10, 160, 150, 150);
bt4.setIcon(ic4);
bt5 = new JButton();
bt5.setBounds(160, 160, 150, 150);
bt5.setIcon(ic5);
bt6 = new JButton();
bt6.setBounds(310, 160, 150, 150);
bt6.setIcon(ic6);
bt7 = new JButton();
bt7.setBounds(10, 310, 150, 150);
bt7.setIcon(ic7);
bt8 = new JButton();
bt8.setBounds(160, 310, 150, 150);
bt8.setIcon(ic8);
bt9 = new JButton();
bt9.setBounds(310, 310, 150, 150);
bt9.setIcon(icSpace);
jf.add(bt1);
jf.add(bt2);
jf.add(bt3);
jf.add(bt4);
jf.add(bt5);
jf.add(bt6);
jf.add(bt7);
jf.add(bt8);
jf.add(bt9);
}
public static void main(String[] args){
PuzzleGame.createMyGUI();
}
}
I think method setIcon is not apply for Button. Besides, someone show me how to set a action to arrange mess picture into a complete picture in Puzzle Game with my code.
I see some issues in your code:
You're extending JFrame and creating a new JFrame object inside your class. You're never using the JFrame of your class (the extended one). So it's wise to just remove it.
You should avoid extending JFrame because that means that your class is a JFrame, JFrame is a rigid container, instead make your programs based on JPanels and add them to other Containers. For reference see: Using extends JFrame vs calling it inside of class.
You're over using the static keyword. static is not a cross method passing word, it will harm you a lot, stop using it. Instead create instances of your class and call your methods that way.
You have multiple objects that do the same:
Icon ic1 = new ImageIcon("images/1.png");
Icon ic2 = new ImageIcon("images/2.png");
...
Why not have an Icon[] icons and iterate over it?
You're using the evil null layout and setBounds(...), stop using it and instead make use of the layout managers along with EmptyBorders for extra spacing between components.
While pixel perfect positioning might be like the easiest way to Swing newbies to create complex GUIs, the more you use it, the more problems you'll find regarding this. Swing has to deal with different platforms, screen sizes, resolutions, PLAFs, etc. That's why pixel perfect GUIs are just an illusion. For reference see Null layout is evil and the answers in this question for a further explanation on why you should avoid null layout.
You're making your JFrame visible before you have added all your components, this could cause your GUI to not be painted fully before it's shown and could cause a "bug" that the components don't display until you hover where they should be. JFrame#setVisible(...) should be one of the last lines to be called.
You're calling JFrame#setSize(...), you should instead override the getPreferredSize of your inner JPanels and then call JFrame#pack(), so your JFrame reduces its size to the minimum size where all your components are visible on their preferred sizes. See Should I avoid the use of setPreferred|Maximum|MinimumSize in Java Swing? (The general consensus says "yes").
You're not placing your program on the Event Dispatch Thread (EDT), Swing is not Thread safe and this could make your program to freeze sometimes, you can solve this by changing your main(...) method like this one:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Your constructor here
}
});
}
Your images probably aren't located, but they'll become embedded resources once you package your program as a JAR file, and thus, it's wise to start treating the files (or images) as if they already were.
You can change for example:
Icon ic1 = new ImageIcon("images/1.png");
To this:
Icon ic1 = null;
try {
ic1 = new ImageIcon(ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("images/1.png")));
} catch (IOException e) {
e.printStackTrace();
}
That will make your image to be loaded. See this question and the accepted answer for reference.
That should solve your question, and your GUI (I did it with 2 icons) shoudl look like this one:
But if you want to follow my above recommendations you could try this code, which uses layout managers, empty borders, overrides getPreferredSize() methods and uses pack(), etc and generates a really similar GUI like the one you already have:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ImagesInResourcesExample {
private JFrame frame;
private JPanel buttonsPane;
private JPanel rightPane;
private JPanel scorePanel;
private JPanel colorPanel;
private BufferedImage img;
private JButton[][] buttons;
private JLabel moveLabel;
private JLabel timeLabel;
private JButton newGameButton;
private JButton exitButton;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ImagesInResourcesExample().createAndShowGui();
}
});
}
#SuppressWarnings("serial")
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
buttons = new JButton[3][3];
moveLabel = new JLabel("Move: 0");
timeLabel = new JLabel("Time: 0");
colorPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
colorPanel.setBackground(Color.BLUE);
colorPanel.setOpaque(true);
newGameButton = new JButton("New Game");
exitButton = new JButton("Exit");
try {
img = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("images/arrow.png"));
} catch (IOException e) {
e.printStackTrace();
}
buttonsPane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
};
buttonsPane.setLayout(new GridLayout(3, 3));
buttonsPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons.length; j++) {
buttons[i][j] = new JButton(new ImageIcon(img));
buttonsPane.add(buttons[i][j]);
}
}
rightPane = new JPanel();
rightPane.setLayout(new GridBagLayout());
scorePanel = new JPanel();
scorePanel.setLayout(new GridLayout(1, 2, 10, 10));
scorePanel.add(moveLabel);
scorePanel.add(timeLabel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(10, 10, 10, 10);
rightPane.add(scorePanel, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
rightPane.add(colorPanel, gbc);
gbc.gridy = 2;
gbc.ipadx = 30;
gbc.ipady = 80;
rightPane.add(newGameButton, gbc);
gbc.gridy = 3;
rightPane.add(exitButton, gbc);
rightPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.add(buttonsPane, BorderLayout.CENTER);
frame.add(rightPane, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
As you can see, the code is at most 20 lines longer than the one you already have, but if you keep adding elements to both programs, the one I did will, in a future, be shorter than the one you'll end up by using null layout.
I hope you follow the above recommendations and take this example and try to understand it and improve it.

Change Button to JButton can't fixe it(((

I'm stuck using Button and JButton
expected result.. ( all information working )
http://i.stack.imgur.com/3qX7v.png
and what I have
http://i.stack.imgur.com/a4gao.png
I want to replace this:
Button butRock = new Button("Rock");
butRock.addActionListener(this);
ButtPan.add(butRock);
To This:
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
I'm stuck because when I replace Button to JButton the program doesn't work properly...when I use this JButton
Question: How to replace the button with picture and that program still work properly...
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class gui extends JFrame implements ActionListener
{
public JLabel JWoL,JWoLPlayer,JWoLPC,JNumWin,JNumLose,JNumTie, logo;
public JLabel JWinT,JLoseT,JTieT, rpsP, rpsC, result;
JPanel LabelsPan;
static final int WINS = 0, LOSSES = 1, DRAWS = 2;
int[] counts = new int[3];
String[] strings = {"| You Win", "| You Lose", "| Draw"};
JLabel[] labels = {JNumWin, JNumLose, JNumTie};
#SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
gui theWindow = new gui();
theWindow.show();
}
private void record(int type)
{
JWoL.setText(strings[type]);
counts[type]++;
labels[type].setText(""+counts[type]);
}
public gui() throws IOException
{
JPanel logo = new JPanel();
logo.setLayout(new GridLayout(1,1));
BufferedImage myPicture = ImageIO.read(new File("logo.jpg"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
add(picLabel);
JPanel ButtPan=new JPanel();
ButtPan.setLayout(new GridLayout(1,3));
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
Button butPaper = new Button("Paper");
butPaper.addActionListener(this);
ButtPan.add(butPaper);
Button butScissors = new Button("Scissors");
butScissors.addActionListener(this);
ButtPan.add(butScissors);
JWoLPlayer = new JLabel();
JWoLPC = new JLabel();
JWoL= new JLabel();
JLabel rpsPlayer= new JLabel("| Your Choice: ");
JLabel rpsComputer= new JLabel("| Computers Choice: ");
setTitle("| RoPaS GAME |");
LabelsPan=new JPanel();
LabelsPan.setLayout(new GridLayout(3,2));
rpsP = new JLabel();
LabelsPan.add(rpsPlayer);
LabelsPan.add(JWoLPlayer);
rpsC = new JLabel();
LabelsPan.add(rpsComputer);
LabelsPan.add(JWoLPC);
result =new JLabel();
LabelsPan.add(JWoL,"Center");
JPanel WLPan = new JPanel();
WLPan.setLayout(new GridLayout(3, 2));
JWinT = new JLabel("Wins: ");
JLoseT = new JLabel("Losses: ");
JTieT = new JLabel("Ties: ");
WLPan.add(JWinT);
JNumWin = new JLabel();
WLPan.add(JNumWin);
WLPan.add(JLoseT);
JNumLose = new JLabel();
WLPan.add(JNumLose);
WLPan.add(JTieT);
JNumTie = new JLabel();
WLPan.add(JNumTie);
JLabel[] labels1 = {JNumWin, JNumLose, JNumTie};
labels = labels1;
JPanel TwoPanesN1=new JPanel();
TwoPanesN1.setLayout(new BorderLayout());
TwoPanesN1.add(logo,"North");
TwoPanesN1.add(LabelsPan,"West");
TwoPanesN1.add(WLPan,"East");
getContentPane().setLayout(new GridLayout(3,2));
getContentPane().add(ButtPan);
getContentPane().add(TwoPanesN1);
Font fontDisplay = new Font("Arial", Font.BOLD, 16);
JWoL.setFont(fontDisplay);
LabelsPan.setFont(fontDisplay);
setSize(400,250);
setVisible(true);
setResizable(false);
addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent ev){System.exit(0);}});
}
public void Play(String PlayerChoice)
{
String PCchoice=PCansw();
JWoLPC.setText(PCchoice);
if(PlayerChoice.equals(PCchoice))
record(DRAWS);
else if(PlayerChoice.equals("Rock"))
if(PCchoice.equals("Paper"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Paper"))
if(PCchoice.equals("Scissors"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Scissors"))
if(PCchoice.equals("Rock"))
record(LOSSES);
else
record(WINS);
}
public String PCansw()
{
String rpsPC2="";
int rpsPC=(int)(Math.random( )*3)+1;
if(rpsPC==1)
rpsPC2= "Rock";
else if(rpsPC==2)
rpsPC2= "Paper";
else if(rpsPC==3)
rpsPC2= "Scissors";
return rpsPC2;
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Exit"))
System.exit(0);
else
{
JWoLPlayer.setText(e.getActionCommand());
Play(e.getActionCommand());
}
}
}
The problem is that you are using getActionCommand to determine which JButton was clicked but this property is not set by default in Swing. You would have to call
butRock.setActionCommand("Rock");
java.awt.Button automatically uses the label property as the ActionCommand if it not explicitly set. From the docs
If the command name is null (default) then this method returns the label of the button.
Some asides:
Better to avoid mixing heavy & lightweight components and use lightweight components throughout the application.
As your Rock, Paper, Scissors buttons have identical functionality, consider using an Action.
A direct instance JFrame is typically used rather than extending the class
Use Initial Threads
Window#show is deprecated. Use Window#setVisible.
Don't use System.exit - See more here

Categories