transparent background of GridLayout - java

i wrote a code using GridLayou, however i cant manage to delete the grey background and use the img i plugged as a background, and the picture demonstrate the problem:
Can someone please help?
this is the code
public class mainClass {
private static JButton start;
static BackgroundPanel bp = null;
static JFrame mainf = null;
static int R;
final static boolean shouldFill = true;
// group turns boolean
boolean redTurn = false;
boolean blueTurn = false;
boolean greenTurn = false;
boolean yellowTurn = false;
// boards
static ImageIcon gameBoard;
static ImageIcon blueBoard;
static ImageIcon qBoard;
// dice
static JButton dice_1 = null;
public static void main(String[] args) throws IOException {
mainf = new JFrame ("سين جيم");
// background
BufferedImage mFrame = ImageIO.read(new File("B1.png"));
bp = new BackgroundPanel(mFrame);
mainf.add(bp);
bp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// c.fill = GridBagConstraints.HORIZONTAL;
// Hi string
JLabel hi = new JLabel ("أهلا وسهلا بكم في لعبة الليدو");
Font fs = hi.getFont();
hi.setFont(fs.deriveFont(50f));
bp.add(hi);
// empty
// button
start = new JButton ( "لنبدأاللعب");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10,0,0,0); //top padding
bp.add(start, c);
// Action Listener
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// starting the game area
// emptying all
bp.removeAll();
bp.revalidate();
bp.repaint();
BufferedImage mFrame2= null;
try {
// changing background
mFrame2 = ImageIO.read(new File("B2.png"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// setting new background
bp = new BackgroundPanel(mFrame2);
bp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// adding gameBoard
gameBoard = new ImageIcon("gameBoard.png");
JLabel gameBoard_1 = new JLabel(gameBoard);
bp.add(gameBoard_1);
// adding blueBoard
blueBoard = new ImageIcon("blueBoard.png");
JLabel blueBoard_1 = new JLabel(blueBoard);
bp.add(blueBoard_1);
GridLayout experimentLayout = new GridLayout(4,4); // rows | , cols-
blueBoard_1.setLayout(experimentLayout);
// gameName panel
JPanel gameName = new JPanel();
gameName.setLayout(new GridLayout(1,0));
JLabel Ledu= new JLabel ("لعبة اللدو");
Font font3 = new Font("Verdana", Font.BOLD, 30);
Ledu.setFont(font3);
Ledu.setForeground(Color.WHITE);
gameName.add(Ledu);
// teamPanel
JPanel teamName = new JPanel();
teamName.setLayout(new GridLayout(2,0));
JLabel blue= new JLabel ("الفريق الأرزق");
Font font2 = new Font("Verdana", Font.BOLD, 20);
blue.setFont(font2);
blue.setForeground(Color.BLUE);
JLabel red= new JLabel ("الفريق الأحمر");
red.setFont(font2);
red.setForeground(Color.RED);
JLabel yellow= new JLabel ("الفريق الأصفر");
yellow.setFont(font2);
yellow.setForeground(Color.YELLOW);
JLabel green= new JLabel ("الفريق الأخضر");
green.setFont(font2);
green.setForeground(Color.GREEN);
// team panel
teamName.add(blue);
teamName.add(red);
teamName.add(yellow);
teamName.add(green);
// adding question
JPanel question = new JPanel();
question.setLayout(new GridLayout(3,2));
ImageIcon q = new ImageIcon("Q.png");
JLabel q_1 = new JLabel(q);
// adding Question panel
question.add(q_1);
// dicePanel
final JPanel dicePanel = new JPanel();
dicePanel.setLayout(new GridLayout(4,0));
ImageIcon dice = new ImageIcon("dice.png");
dice_1 = new JButton(dice);
// adding dice panel
dicePanel.add(dice_1);
dice_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dicePanel.remove(dice_1);
dicePanel.revalidate();
dicePanel.repaint();
ImageIcon dice = new ImageIcon("dice.gif");
dice_1 = new JButton(dice);
dicePanel.add(dice_1);
// random number
Random r = new Random();
R = r.nextInt(10) + 2;
System.out.println(R);
}
});
// Centeralizing Ledu
Ledu.setHorizontalAlignment(SwingConstants.CENTER);
gameName.setAlignmentX(Component.CENTER_ALIGNMENT);
blue.setHorizontalAlignment(SwingConstants.CENTER);
red.setHorizontalAlignment(SwingConstants.CENTER);
yellow.setHorizontalAlignment(SwingConstants.CENTER);
green.setHorizontalAlignment(SwingConstants.CENTER);
teamName.setAlignmentX(Component.CENTER_ALIGNMENT);
// no backgrounf color
Ledu.setOpaque( false );
gameName.setOpaque( false );
blue.setOpaque( false );
red.setOpaque( false );
yellow.setOpaque( false );
green.setOpaque( false );
teamName.setOpaque( false );
question.setOpaque( false );
dicePanel.setOpaque( false );
// final add
blueBoard_1.add(gameName, BorderLayout.PAGE_START);
blueBoard_1.add(teamName, BorderLayout.CENTER);
blueBoard_1.add(question, BorderLayout.LINE_END);
blueBoard_1.add(dicePanel, BorderLayout.PAGE_END);
/*
// add dice
ImageIcon dice = new ImageIcon("dice.png");
dice_1 = new JButton(dice);
dice_1.setSize(100, 70);
bp.add(dice_1);
// changin to moving dice
dice_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bp.remove(dice_1);
bp.revalidate();
bp.repaint();
ImageIcon dice = new ImageIcon("dice.gif");
dice_1 = new JButton(dice);
dice_1.setSize(100, 70);
bp.add(dice_1);
// random number
Random r = new Random();
int R = r.nextInt(10) + 2;
System.out.println(R);
}
});
*/
mainf.setContentPane(bp);
};}); // end of start actionListener
mainf.pack();
mainf.setVisible(true);
};
// dice class
}

A JPanel is opaque by default so you see a grey background.
You need to use:
panel.setOpaque( false );
if you add a panel to your component containing the background image.
By the way you should NOT be using static variables. Look at the examples from the Swing tutorial for a better way to create your frames. That is create a class to represent your game. This would be a JPanel. Then you define all the variables you need for you game in this class. Then you simple add the panel to the frame. You should NOT be createing components in the main() method.

Related

JLabel won't show up on JPanel

Help is needed :)
My friends and I are coding hangman in school for a project, and we're really stumped on one part. We made a JFrame and an outer JPanel (Background), then divided it into two columns (the left column is functional as we like). Our problem lies in the right column, rightPanel. We need to set up a JLabel so we can have the lines correlating to the word length a player chooses, but our JLabel doesn't work. I've tried to just do a simple System.out.println("test"); and nothing shows up within the panel (blankSpaces). The layout has been changed as well just to try and make something show up. We also tried to set the JLabel within a method which would be called in the panel blankSpaces, but nothing seems to work. These are just two of the classes we have for the game, so if any other code is needed for explanation please let me know :)
//the rightPanel
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class RightPanel extends JPanel {
//unnecessary code rn
Guess dalia = new Guess();
WordSelection clementine = new WordSelection();
private String letterGuess = "";
public JTextField jt;
//where we tried to make a test or just declare the label
private JLabel label3;
JLabel test;
private JPanel parent;
JPanel panel3;
//constructor
public RightPanel() {
this.setLayout(new GridLayout(0, 1));
this.add(letters(parent));
this.add(lettersGuessed(parent));
this.add(blankSpaces(parent));
this.add(notLetterButtons(parent));
}
//where the alphabet is supposed to be but we just made it using coordinates
public JPanel letters(JPanel Parent) {
GridLayout layout1 = new GridLayout(1, 1);
JPanel panel1 = new JPanel(layout1);
return panel1;
}
// where the player will guess letters
public JPanel lettersGuessed(JPanel parent) {
GridLayout layout2 = new GridLayout(1, 1);
JPanel panel2 = new JPanel(layout2);
panel2.add(generateTextField());
return panel2;
}
//textfield that is currently useless
public JTextField generateTextField() {
// TODO Auto-generated method stub
// JLabel jl = new JLabel();
jt = new JTextField(1);
jt.setFont(new Font("Verdana", 1, 30));
jt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
letterGuess = jt.getText().substring(0, 1);
// jl.setText(input);
}
});
return jt;
}
//where we coded the alphabet
#Override
public void paint(Graphics g) {
int y = this.getHeight();
int x = this.getWidth();
// super.paint(g);
String firstLine = "A B C D E F G";
String secondLine = "H I J K L M N";
String thirdLine = "O P Q R S T U";
String fourthLine = "V W X Y Z";
g.setFont(new Font("Verdana", 1, 30));
// alphabet
g.drawString(firstLine, x / 3, y / 25);
g.drawString(secondLine, x / 3, y / 12);
g.drawString(thirdLine, x / 3, y / 8);
g.drawString(fourthLine, (int) (x / 2.65), y / 6);
}
// where the blank spaces in the amount of letters to be guessed will appear
public JPanel blankSpaces(JPanel parent) {
GridLayout layout3 = new GridLayout(1, 1);
panel3 = new JPanel(layout3);
// panel3.add(label3);
/*test = new JLabel("dalia is my bffl");
test.setLayout(new BorderLayout());
test.setVerticalTextPosition(JLabel.CENTER);
test.setHorizontalTextPosition(JLabel.CENTER);
test.setVisible(true);
panel3.add(test);*/
return panel3;
}
// where player will be able to choose if they want a new word
public JPanel notLetterButtons(JPanel parent) {
// int rows = 2; int cols = 4;
GridLayout layout4 = new GridLayout(2, 4);
JPanel panel4 = new JPanel(layout4);
/*
JPanel[][] parent = new JPanel[2][4];
Container f1 = new Container();
f1.setLayout(new GridLayout(2, 4));
for(int m = 0; m < 2; m++) {
for(int n = 0; n < 4; n++) {
parent[m][n] = new JPanel();
f1.add(parent[m][n]);
}
}*/
int y = this.getHeight();
int x = this.getWidth();
//new button
JButton button1 = new JButton();
button1.setText("QUIT");
button1.addActionListener(e -> quitAction() );
panel4.add(button1);
//new button
JButton button2 = new JButton();
button2.setText("SUBMIT");
button2.addActionListener(e -> submitAction() );
panel4.add(button2);
//new button
JButton button3 = new JButton();
button3.setText("QUOTE");
panel4.add(button3);
//new button
JButton button4 = new JButton();
button4.setText("FRENCH");
panel4.add(button4);
//new button
JButton button5 = new JButton();
button5.setText("5");
button5.addActionListener(e -> fiveAction() );
panel4.add(button5);
//new button
JButton button6 = new JButton();
button6.setText("6");
button6.addActionListener(e -> sixAction() );
panel4.add(button6);
//new button
JButton button7 = new JButton();
button7.setText("7");
button7.addActionListener(e -> sevenAction() );
panel4.add(button7);
//new button
JButton button8 = new JButton();
button8.setText("RESTART");
panel4.add(button8);
return panel4;
// panel4.add(gt);
// gt.pack();
// gt.setVisible(true);
// return f1;
}
private Object fiveAction() {
clementine.wordPick(5);
//String underline = "";
//for (int x = 0; x < 5; x++) {
// underline += "_ ";
//}
JLabel lbl = new JLabel ( "i hate this");
label3.setText("_ _ _ _ _");
panel3.add(label3);
return label3;
}
private Object sixAction() {
clementine.wordPick(6);
JLabel label6 = new JLabel("_ _ _ _ _ _");
return label6;
}
private Object sevenAction() {
clementine.wordPick(7);
return null;
}
private JButton submitAction() {
String letterGuess = jt.getText();
dalia.runThrough();
return null;
}
private Object quitAction() {
System.exit(0);
return null;
}
}
//Background class
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
public class Background extends JPanel {
private static final int FRAME = 400;
//private Dimension rightPanelSize;
HangmanPicture hangmanPicture = new HangmanPicture();
RightPanel rightPanel = new RightPanel();
public Background(JFrame frame) {
this.setLayout(new GridLayout(0, 2));
this.setPreferredSize(frame.getSize());
this.add(hangmanPicture);
this.setPreferredSize(frame.getSize());
Dimension frameSize = frame.getSize();
this.add(rightPanel);
this.setPreferredSize(frame.getSize());
//double up = height / 4;
//double down = height * (3 / 4);
// int width = (int) (frameSize.getWidth()/2);
//int height = (int) (frameSize.getHeight());
//this.rightPanelSize = new Dimension(width, height);
}// heyy
enter code here
}
Thank you!!

Drawing & Changing an Image within a JPanel (from another class)

So yeah, I'm trying to write a rock paper scissors program with images, but I'm having trouble at putting in the pictures. There seems to only be a small white square on the JPanel.
Here's the code for my Main Class:
public class Practice extends JPanel implements ActionListener {
// Images
final ImageIcon rockPic = new ImageIcon("D:\\JOVO\\RPS\\src\\rock.png");
final ImageIcon paperPic = new ImageIcon("D:\\JOVO\\RPS\\src\\paper.png");
// variables
String results = null;
Image pic = null;
//Image Panel
ImagePanel youPic = new ImagePanel();
public Practice() {
// FRAME
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("RPS");
frame.setLayout(new BorderLayout());
frame.setVisible(true);
// SUPER JPANEL
setLayout(new GridBagLayout());
setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
frame.add(this);
// JPANELS - RPS title, JButton, PICTURES
JPanel rpsTitle = new JPanel();
c.fill = GridBagConstraints.CENTER;
c.gridy = 0;
c.gridx = 1;
rpsTitle.setBackground(Color.WHITE);
add(rpsTitle, c);
JPanel jbuts = new JPanel();
c.gridy = 3;
jbuts.setLayout(new BorderLayout());
add(jbuts, c);
// ImagePanels
c.gridy = 2;
c.gridx = 0;
add(youPic,c);
c.gridy = 0;
c.gridx = 1;
// JBUTTONS
JButton rock = new JButton(" Rock ");
JButton paper = new JButton(" Paper ");
JButton scissors = new JButton("Scissors");
jbuts.add(rock, BorderLayout.WEST);
jbuts.add(paper, BorderLayout.CENTER);
jbuts.add(scissors, BorderLayout.EAST);
paper.addActionListener(this);
JButton resultB = new JButton("RES");
c.gridy = 2;
c.weighty = 10;
add(resultB, c);
c.weighty = 0;
// FONTS
Font rps = new Font(null, Font.BOLD, 28);
Font labels = new Font(null, Font.ITALIC, 18);
// JLABELS
JLabel rpsTit = new JLabel("Rock, Paper, Scissors");
rpsTit.setFont(rps);
rpsTitle.add(rpsTit);
JLabel you = new JLabel("You: ");
you.setFont(labels);
JLabel com = new JLabel("Com: ");
com.setFont(labels);
c.gridy = 1;
c.gridx = 0;
add(you, c);
c.gridx = 2;
add(com, c);
// PICTURES
// comPic.setPic(rockPic);
// youPic.setPic(pic);
}
public String test(String name) {
// test the game
return results;
}
public static void main(String[] args) {
// main stuffs
Practice prac = new Practice();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Works");
ImageIcon pic = null;
pic = paperPic;
youPic.setPic(pic);
}
}
And my other class:
public class ImagePanel extends JPanel {
Image pic = null;
public ImagePanel() {
repaint();
}
public void setPic(ImageIcon pic) {
// set picture for painting
this.pic = pic.getImage();
System.out.println("Set Pic");
repaint();
}
public void paintComponent(Graphics g) {
// paint
super.paintComponent(g);
System.out.println("Painting");
g.drawImage(pic, 0, 0, this);
}
}
Thanks in advance! :)

Layout settings for JTabbedPane

I have a JTabbedPane in a java program. I added a JPanel to each "tab" but when I style the elements inside each panel (GridBagLayout and BorderLayout), there seems to be no effect. Am I doing something wrong? Is there a certain way I need to control the layout? Here's one portion of the code:
public static void main(String args[]) {
// set L&F
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
JFrame main = new JFrame();
JTabbedPane tabs = new JTabbedPane();
JPanel checkOutPanel = new JPanel();
Font f = new Font("Header", Font.BOLD, 24);
Font f2 = new Font("Menu", Font.BOLD, 36);
Font font = new Font("Menu", Font.BOLD, 24);
// check out
JLabel checkOutLabel = new JLabel("Checkout");
JLabel bookNumLabel = new JLabel("Book Number");
JLabel personNameLabel = new JLabel("Person Name");
final JTextField bookNumEntry = new JTextField(20);
final JTextField personNameEntry = new JTextField(20);
JButton checkOutButton = new JButton("Check Out");
checkOutLabel.setFont(font);
// checkout gui
GridBagConstraints co = new GridBagConstraints();
co.gridx = 1;
checkOutPanel.add(checkOutLabel, co);
co.gridx = 0;
co.gridy = 1;
checkOutPanel.add(bookNumLabel, co);
co.gridx = 1;
checkOutPanel.add(bookNumEntry, co);
co.gridx = 0;
co.gridy = 2;
checkOutPanel.add(personNameLabel, co);
co.gridx = 1;
checkOutPanel.add(personNameEntry, co);
co.gridx = 2;
checkOutPanel.add(checkOutButton, co);
tabs.addTab("Checkout",checkOutPanel );
tabs.setTabPlacement(JTabbedPane.LEFT);
main.add(tabs);
main.setSize(1300,1100);
main.setVisible(true);
}
You've not set the layout manager for checkOutPanel so it's using it's default layout manager of FlowLayout
Change...
JPanel checkOutPanel = new JPanel();
To something more like...
JPanel checkOutPanel = new JPanel(new GridBagLayout());

How to set JLabel in a specific area in JFrame?

I am trying to make a desktop application in Java Swing. I am trying to create image slider in frame and I got it. Now problem in that I want to set the specific area for imagelabel in that frame. How can I do this? I want to set imagelabel in left side. I am posting my snapshot which I am getting after running my program.
Here is my code
public class ImageSlider extends JPanel implements ActionListener {
private static final int MAX = 20;
private static final Font sans = new Font("SansSerif", Font.PLAIN, 16);
private static final Border border =
BorderFactory.createMatteBorder(4, 16, 4, 16, Color.BLUE);
private List<String> list = new ArrayList<String>(MAX);
private List<ImageIcon> cache = new ArrayList<ImageIcon>(MAX);
private JLabel imageLabel = new JLabel();
//label = new JLabel( image, SwingConstants.CENTER);
private JButton prevButton = new JButton();
private JButton nextButton = new JButton();
private JComboBox favorites;
public ImageSlider() {
this.setLayout(new BorderLayout());
list.add("c.jpg");
list.add("a0.png");
list.add("yellow.png");
list.add("a0.png");
list.add("c.jpg");
for (int i = 0; i < list.size(); i++) cache.add(i, null);
ImageIcon image = new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\a0.png");
JLabel titleLabel = new JLabel(image, SwingConstants.CENTER);
// titleLabel.setText("ImageSlider");
titleLabel.setHorizontalAlignment(JLabel.CENTER);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 24));
titleLabel.setBorder(border);
this.add(titleLabel, BorderLayout.NORTH);
imageLabel.setIcon(getImage(0));
imageLabel.setAlignmentX(LEFT_ALIGNMENT);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setBorder(border);
this.add(imageLabel, BorderLayout.CENTER);
favorites = new JComboBox(
list.toArray(new String[list.size()]));
favorites.setActionCommand("favs");
favorites.addActionListener(this);
prevButton.setText("\u22b2Prev");
prevButton.setFont(sans);
prevButton.setActionCommand("prev");
prevButton.addActionListener(this);
nextButton.setText("Next\u22b3");
nextButton.setFont(sans);
nextButton.setActionCommand("next");
nextButton.addActionListener(this);
JPanel controlPanel = new JPanel();
controlPanel.add(prevButton);
controlPanel.add(favorites);
controlPanel.add(nextButton);
controlPanel.setBorder(border);
this.add(controlPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if ("favs".equals(cmd)) {
int index = favorites.getSelectedIndex();
ImageIcon image = getImage(index);
imageLabel.setIcon(image);
if (image != null) imageLabel.setText("");
else imageLabel.setText("Image not available.");
}
if ("prev".equals(cmd)) {
int index = favorites.getSelectedIndex() - 1;
if (index < 0) index = list.size() - 1;
favorites.setSelectedIndex(index);
}
if ("next".equals(cmd)) {
int index = favorites.getSelectedIndex() + 1;
if (index > list.size() - 1) index = 0;
favorites.setSelectedIndex(index);
}
}
public JButton getDefault() { return nextButton; }
// Return the (possibly cached) image having the given index.
private ImageIcon getImage(int index) {
ImageIcon image = cache.get(index);
if (image != null) return image;
String name = "/images/" + list.get(index);
URL url = ImageSlider.class.getResource(name);
if (url != null) {
image = new ImageIcon(url);
}
cache.set(index, image);
return image;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageSlider go = new ImageSlider();
frame.add(go);
frame.setTitle("ImageSlider");
// frame.setSize(400, 300);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
go.getDefault().requestFocusInWindow();
}
});
}
}
How can I achieve my goal?
The easiest way to achieve this is to put the imageLabel into a JPanel with a FlowLayout. Then add that panel to the bigger BorderLayout.
So change:
this.add(imageLabel, BorderLayout.CENTER);
To something like:
JPanel imageConstrain = new JPanel(new FlowLayout(SwingConstants.LEFT));
imageConstrain.add(imageLabel);
this.add(imageConstrain, BorderLayout.CENTER);

Array in Gui to Increment

Hi i have a trouble in my program because i need to set an array for easy way of incrementing it because it is sales so i declare of my array like this iam not yet done of my program this is my program so far .
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class We extends JFrame
{
public static JPanel panel2 = new JPanel();
public static String totallist,addprod;
public static int grandtotal,ve,xxx,z,x,adding,pay,totalp,totalc,payment;
public static JTextField in = new JTextField(z);
public static JTextField ki = new JTextField(15);
public static double disc,totalbayad,sukli;
public static int benta[] = new int [11];
public static String prod[] = new String[11];
public static void main(String[] args)
{
We frameTabel = new We();
prod[1] = "Palmolive";
prod[2] = "Egg";
prod[3] = "Milo";
prod[4] = "Noodles";
prod[5] = "PancitCanton";
prod[6] = "CornBeef";
prod[7] = "LigoSardines";
prod[8] = "CokeSakto";
prod[9] = "RcBig";
prod[10] = "GibsonLespaulGuitar";
benta[1] = 6;
benta[2] = 5;
benta[3] = 6;
benta[4] = 9;
benta[5] = 10;
benta[6] = 25;
benta[7] = 16;
benta[8] = 6;
benta[9] = 16;
benta[10] = 14000;
}
JFrame frame = new JFrame("Customer");
JFrame prodcho = new JFrame("Unofficial receipt");
JFrame want = new JFrame("Buy AGain");
JFrame ftinda = new JFrame("Item && Prices");
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
JLabel lab = new JLabel("Username :");
JLabel pas = new JLabel("Password :");
JLabel cos;
//JPanel panel = new JPanel();
JButton y1;
JButton y2;
We()
{
super("Enter Your Account !");
setSize(300,200);
setLocation(500,280);
panel.setLayout (null);
txuser.setBounds(90,30,150,20);
pass.setBounds(90,65,150,20);
blogin.setBounds(110,100,80,20);
lab.setBounds(15,28,150,20);
pas.setBounds(15,63,150,20);
panel.add(lab);
panel.add(pas);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin()
{
blogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String puname = txuser.getText();
String ppaswd = pass.getText();
if(puname.equals("vincent") && ppaswd.equals("puge"))
{
setVisible(false);
JPanel panel1 = new JPanel();
frame.setVisible(true);
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout());
cos = new JLabel("Do you have a Customer ?");
y1 = new JButton("Yes");
y2 = new JButton("No");
panel1.setLayout(null);
cos.setBounds(70,30,150,20);
y1.setBounds(80,65,150,20);
y2.setBounds(140,65,150,20);
y1.setSize(55,30);
y2.setSize(55,30);
panel1.add(y1);
panel1.add(y2);
panel1.add(cos);
frame.add(panel1);
y1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
if(source == y1)
{
frame.setVisible(false);
//--------------------------------------
int boundsStart=10;
panel.l2.add(new JLabel("-Product-").setBounds(20,boundsStart,150,20));
boundsStart+=20;
for (int i=1; i<11; i++)
{
panel2.add(new JLabel(i+"."+prod[i]).setBounds(20,boundsStart,150,20));
boundsStart+=20;
}
boundsStart = 30; //reset bounds counter
for (int i=1; i<11; i++)
{
panel2.add(new JLabel(""+benta[i]).setBounds(20,boundsStart,150,20));
boundsStart+=20;
}
//You could then change the other JLabels that came after this point in the same way I just did
//price,ent,law, and qx
//--------------------------------------
JLabel vince = new JLabel("-Product-");
JLabel l1 = new JLabel("1."+prod[1]);
JLabel l2 = new JLabel("2."+prod[2]);
JLabel l3 = new JLabel("3."+prod[3]);
JLabel l4 = new JLabel("4."+prod[4]);
JLabel l5 = new JLabel("5."+prod[5]);
JLabel l6 = new JLabel("6."+prod[6]);
JLabel l7 = new JLabel("7."+prod[7]);
JLabel l8 = new JLabel("8."+prod[8]);
JLabel l9 = new JLabel("9."+prod[9]);
JLabel l10 = new JLabel("10."+prod[10]);
JLabel p1 = new JLabel(""+benta[1]);
JLabel p2 = new JLabel(""+benta[2]);
JLabel p3 = new JLabel(""+benta[3]);
JLabel p4 = new JLabel(""+benta[4]);
JLabel p5 = new JLabel(""+benta[5]);
JLabel p6 = new JLabel(""+benta[6]);
JLabel p7 = new JLabel(""+benta[7]);
JLabel p8 = new JLabel(""+benta[8]);
JLabel p9 = new JLabel(""+benta[9]);
JLabel p10 = new JLabel(""+benta[10]);
JLabel price = new JLabel("-Price-");
JButton ent = new JButton("Enter");
JLabel law = new JLabel("Enter No. of Product");
JLabel qx = new JLabel("Enter Quantity");
ftinda.setVisible(true);
ftinda.setSize(350,350);
ftinda.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ftinda.setLayout(new GridLayout());
panel2.setLayout(null);
vince.setBounds(20,10,150,20);
l1.setBounds(20,30,150,20);
l2.setBounds(20,50,150,20);
l3.setBounds(20,70,150,20);
l4.setBounds(20,90,150,20);
l5.setBounds(20,110,150,20);
l6.setBounds(20,130,150,20);
l7.setBounds(20,150,150,20);
l8.setBounds(20,170,150,20);
l9.setBounds(20,190,150,20);
l10.setBounds(20,210,150,20);
p1.setBounds(230,30,150,20);
p2.setBounds(230,50,150,20);
p3.setBounds(230,70,150,20);
p4.setBounds(230,90,150,20);
p5.setBounds(230,110,150,20);
p6.setBounds(230,130,150,20);
p7.setBounds(230,150,150,20);
p8.setBounds(230,170,150,20);
p9.setBounds(230,190,150,20);
p10.setBounds(230,210,150,20);
price.setBounds(225,10,150,20);
in.setBounds(150,250,150,20);
law.setBounds(20,253,150,20);
qx.setBounds(20,280,150,20);
ki.setBounds(150,280,150,20);
ent.setBounds(220,250,150,20);
in.setSize(42,20);
ki.setSize(42,20);
ent.setSize(65,50);
panel2.add(vince);
panel2.add(l1);
panel2.add(l2);
panel2.add(l3);
panel2.add(l4);
panel2.add(l5);
panel2.add(l6);
panel2.add(l7);
panel2.add(l8);
panel2.add(l9);
panel2.add(l10);
panel2.add(p1);
panel2.add(p2);
panel2.add(p3);
panel2.add(p4);
panel2.add(p5);
panel2.add(p6);
panel2.add(p7);
panel2.add(p8);
panel2.add(p9);
panel2.add(p10);
panel2.add(price);
panel2.add(in);
panel2.add(law);
panel2.add(ent);
panel2.add(qx);
panel2.add(ki);
ftinda.add(panel2);
ent.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
ftinda.setVisible(false);
JPanel panel3 = new JPanel();
JLabel cos1 = new JLabel("Do you want to buy more ?");
JButton yy = new JButton("Yes");
JButton nn = new JButton("No");
panel3.setLayout(null);
cos1.setBounds(70,30,150,20);
yy.setBounds(80,65,150,20);
nn.setBounds(140,65,150,20);
yy.setSize(55,30);
nn.setSize(55,30);
panel3.add(cos1);
panel3.add(yy);
panel3.add(nn);
want.add(panel3);
want.setVisible(true);
want.setSize(300,200);
want.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
want.setLayout(new GridLayout());
addprod = prod[];
adding = benta[];
totalp =
totalc = totalp;
totallist = totallist + addprod +"" +x+ "pcs = "+totalc+"pesos";
nn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ea)
{
Object source1 = ea.getSource();
{
if(source1 == nn)
{
JPanel panel4 = new JPanel();
panel4.setLayout(null);
prodcho.setVisible(true);
prodcho.setSize(300,200);
prodcho.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prodcho.setLayout(new GridLayout());
prodcho.add(panel4);
}
}
}
});
}
});
}
}
});
}
else
{
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
}
As PeterMmm stated arrayLists should be able to solve your predicament. ArrayLists allow you to make an array of any type very easily and has a very nice interface such as
mylist.add(element)
Maroun Maroun also made a valid point that you can approach this much more nicely using a loop so that you can avoid the large amount of repitition in your code, but its not necessary to do so if you are happy with it.
Hopefully the following sample of using ArrayList can help you:
http://javarevisited.blogspot.de/2011/05/example-of-arraylist-in-java-tutorial.html
And if you want more information about arraylist here is the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
My last tip, while looking at your code is to add an actionListener to your button, as currently it does nothing ;)
ent.addActionListener(new ActionListener()
{
#Override
public void actionPerformed( ActionEvent e )
{
//..do stuff here or call a function to do stuff :)
}
});
You might want to check out putting this into a bigger loop. You could set up a loop and then use generic statements to add Labels and size them instead of adding a different Label object for each one. It would cut about 20 lines of code.
EDIT: By loops I was talking about how to deal with setting bounds and adding to the panel. An example would be something like
while(condition)
{
panel.add(new JLabel(information).setBounds(bounds));
}
This gets rid of the repetition of having code like:
JLabel p1 = new JLabel(info);
JLabel p2 = new JLabel(info2);
...
panel1.add(p1);
panel1.add(p2);
...
p1.setBounds(bounds1);
p2.setBounds(bounds2);
...

Categories