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);
Related
I'm trying to create a program that lists movies in a Netflix style to learn Front-End coding.
How I want it to look in the end:
My guess is that every movie is a button component with an image a name label and a release year label.
I'm struggling to recreate this look. This is how it looks when I try it:
The navigationbar in my image is at the page start of a border layout. Below the navigationbar the movie container is in the center of the border layout.
My idea was creating a GridLayout and then create a button for each movie and adding it to the GridLayout.
You can recreate this with this code:
public class Main {
private static JFrame frame;
public static void main(String[] args) throws HeadlessException {
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBackground(new Color(32, 32, 32));
JPanel navigationPanel = createNavigationBar();
frame.add(navigationPanel, BorderLayout.PAGE_START);
JPanel moviePanel = createMoviePanel();
frame.add(moviePanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(1920, 1080));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Example App");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel moviePanel = new JPanel();
GridLayout layout = new GridLayout(0, 10);
layout.setHgap(3);
layout.setVgap(3);
moviePanel.setLayout(layout);
moviePanel.setBackground(new Color(32, 32, 32));
ArrayList<String> exampleList = new ArrayList<>();
// Add stuff to the example list
for(int i = 0; i < 120; i++) {
exampleList.add(Integer.toString(i));
}
final File root = new File("");
for(final String movie : exampleList) {
JLabel picLabel = new JLabel();
try {
File imageFile = new File(root.getAbsolutePath() + "\\src\\images\\" + "imageName.jpg"); // Try to find the cover image
if(imageFile.exists()) {
BufferedImage movieCover = ImageIO.read(imageFile);
picLabel = new JLabel(new ImageIcon(movieCover));
} else {
BufferedImage movieCover = ImageIO.read(new File(root.getAbsolutePath() + "\\src\\images\\temp.jpg")); // Get a temp image
picLabel = new JLabel(new ImageIcon(movieCover));
}
} catch (IOException e) {
e.printStackTrace();
}
JLabel movieName = new JLabel("New Movie");
movieName.setForeground(Color.WHITE);;
JButton movieButton = new JButton();
movieButton.setLayout(new GridLayout(0, 1));
//movieButton.setContentAreaFilled(false);
//movieButton.setBorderPainted(false);
//movieButton.setFocusPainted(false);
movieButton.add(picLabel);
movieButton.add(movieName);
moviePanel.add(movieButton);
}
return moviePanel;
}
public static JPanel createNavigationBar() {
JPanel navBar = new JPanel();
navBar.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
navBar.setBackground(new Color(25, 25, 25));
JButton homeButton = new JButton("Home");
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
JButton movieButton = new JButton("Movies");
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
// Add all the buttons to the navbar
navBar.add(homeButton);
navBar.add(movieButton);
return navBar;
}
}
I noticed that the GridLayout always tries to fit everything onto the window.
All that's needed is a properly configured JButton in a GridLayout.
E.G.
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 1; ii < 21; ii++) {
JButton picButton = new JButton("Mov " + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
Here is a complete source for the above with a tweak to put the year on a new line. It uses HTML in the JButton to break the button text into two lines.
The input focus is on the first button, whereas the mouse hovers over the '2009' movie:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class MovieGrid {
MovieGrid() {
JFrame f = new JFrame("Movie Grid");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(createMoviePanel());
f.pack();
f.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(
9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 2001; ii < 2021; ii++) {
JButton picButton = new JButton(
"<html>Movie<br>" + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new MovieGrid();
}
};
SwingUtilities.invokeLater(r);
}
}
Same idea's from Andrew Thompson answer but with some minor text alignment changes and hover effect
final class Testing
{
public static void main(String[] args)
{
JFrame frame=new JFrame("NEFLIX");
frame.setContentPane(new GridDisplay());
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static final class GridDisplay extends JPanel implements ActionListener
{
private GridDisplay()
{
super(new GridLayout(0,5,20,20));
setBackground(new Color(0,0,0,255));
BufferedImage image=new BufferedImage(150,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=(Graphics2D)image.getGraphics();
g2d.setColor(Color.BLUE);
g2d.fillRect(0,0,image.getWidth(),image.getHeight());
HoverPainter painter=new HoverPainter();
for(int i=0;i<10;i++)
{
TVShowCard card=new TVShowCard(image,"Show "+i,"199"+i);
card.addMouseListener(painter);
add(card);
}
}
//highlight only on hover
private final class HoverPainter extends MouseAdapter
{
#Override
public void mouseExited(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(false);
}
#Override
public void mouseEntered(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(true);
}
}
private final class TVShowCard extends JButton
{
private TVShowCard(BufferedImage preview,String name,String year)
{
super();
setContentAreaFilled(false);
setBackground(new Color(0,0,0,0));
setFocusPainted(false);
setBorderPainted(false);
//I didn't use image icon & text horizontal alignment because the text always horizontally centered aligned but from the expected output it was left so created 2 labels for the job
setLayout(new GridBagLayout());
addIcon(preview);
addLabel(name,year);
addActionListener(GridDisplay.this);
}
private void addIcon(BufferedImage preview)
{
JLabel icon=new JLabel();
icon.setIcon(new ImageIcon(preview));
add(icon,new GridBagConstraints(0,0,1,1,1.0f,0.0f,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0));
}
private void addLabel(String name,String year)
{
JLabel label=new JLabel("<html><body>"+name+"<br>"+year+"</body></html>");
label.setForeground(Color.white);
label.setBackground(new Color(0,0,0,0));
add(label,new GridBagConstraints(0,1,1,1,1.0f,1.0f,GridBagConstraints.SOUTHWEST,GridBagConstraints.NONE,new Insets(5,0,0,0),0,0));
}
}
#Override
public void actionPerformed(ActionEvent e)
{
TVShowCard card=(TVShowCard)e.getSource();
//do stuff with it
}
}
}
I am 'relatively' new to java creating a Hangman game in Java (Eclipse) using Swing. I have got all the components relating to the word done.
However I want that in the middle of the screen a Hangman image to be shown and when you get a guess wrong it updated with a different image (Of a more complete hangman).
However I am unsure of how to do this, whether I would need ImageIcon or just images and using paintComponent etc. Any Help appreciated, my code is below. I am unsure of how to do it in a efficient method that allows me to change it every time variable guess goes down. Please Suggest a method for doing this and the basics of how it might work.
public class Test extends JTextField {
private JFrame frame;
JTextField userInput;
private JTextField textField;
private String inputString;
private String total="";
private static char[] pass = Hangmangame.word.getPassword();
private static String passString = new String(pass);
private String []wordch = new String[passString.length()];
private String []astri = new String[passString.length()];
private int guess;
private boolean letter = false;
private JTextField txtGuesses;
private JPanel PicturePanel;
public static void start() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
initialize();
}
public void initialize() {
for (int i = 0; i < passString.length(); i++) {
astri[i]="*";
wordch[i]=passString.substring(i, i+1);
total =total+ astri[i];
guess =10;
}
//------------------------------------------------
frame = new JFrame();
frame.setBounds(300, 100, 1000, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
//------------------------------------
JLabel Hangman = new JLabel("Hangman");
Hangman.setFont(new Font("Tahoma", Font.BOLD, 46));
Hangman.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(Hangman, BorderLayout.NORTH);
//----------------------------------
textField = new JTextField(total);
textField.setBorder(null);
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setFont(new Font("Tahoma", Font.BOLD, 46));
frame.getContentPane().add(textField, BorderLayout.SOUTH);
textField.setColumns(10);
//------------------------------------------
userInput = new JTextField();
userInput.setBorder(new LineBorder(new Color(0, 0, 0)));
userInput.setFont(new Font("Tahoma", Font.PLAIN, 22));
userInput.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(userInput, BorderLayout.EAST);
userInput.setColumns(10);
TextFieldListener tfListener = new TextFieldListener();
userInput.addActionListener(tfListener);
//----------------------------------------------
txtGuesses = new JTextField();
txtGuesses.setBorder(null);
txtGuesses.setHorizontalAlignment(SwingConstants.LEFT);
txtGuesses.setFont(new Font("Tahoma", Font.BOLD, 20));
txtGuesses.setText("Guesses:"+guess);
frame.getContentPane().add(txtGuesses, BorderLayout.WEST);
txtGuesses.setColumns(10);
//-------------------------------
PicturePanel = new JPanel();
PicturePanel.setBackground(new Color(255, 255, 255));
frame.getContentPane().add(PicturePanel, BorderLayout.CENTER);
//----------------------------------------------
}
public class TextFieldListener implements ActionListener
{ public void actionPerformed(ActionEvent evt)
{ inputString = userInput.getText();
userInput.setText("");
checkcorrect();
}
}
private void checkcorrect() {
//runs it as many times as there are letters
for (int i = 0; i < passString.length(); i++) {
if(wordch[i].equals(inputString)) {
astri[i]=wordch[i];
total="";
// rewrites the *** with the letter added in same as code for setting up the astrixs.
for (int x = 0; x < passString.length(); x++) {
total =total+ astri[x];
}
textField.setText(total);
letter = true;
}
}
if(letter==true) {
letter=false;
}else {
guess=guess-1;
txtGuesses.setText("Guesses:"+guess);
if(guess==0) {
if(JOptionPane.showConfirmDialog(frame,"You Lose","Hangman",
JOptionPane.PLAIN_MESSAGE ) == JOptionPane.YES_OPTION ) {
System.exit(0);
}
}
}
if(total.equals(passString)) {
if(JOptionPane.showConfirmDialog(frame,"You Win","Hangman",
JOptionPane.PLAIN_MESSAGE ) == JOptionPane.YES_NO_OPTION ) {
System.exit(0);
}
}
}
private void Image() {
// My images
ImageIcon icon1 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\0");
ImageIcon icon2 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\1");
ImageIcon icon3 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\2");
ImageIcon icon4 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\3");
ImageIcon icon5 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\4");
ImageIcon icon6 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\5");
ImageIcon icon7 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\6");
ImageIcon icon8 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\7");
ImageIcon icon9 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\8");
ImageIcon icon10 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\9");
ImageIcon icon11 = new ImageIcon("P:\\Profiles\\workspace\\Games\\Images\\files\\10");
}
}
Can anyone help me solve this?
imagePanel = new JPanel();
label = new JLabel();
for (int i = 0; i < 9; i++)
{
label.setIcon(image[i]);
imagePanel.add(label);
}
When using this it gives me the errors:
Exception in thread "main" java.lang.NullPointerException...
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at assignment.Furniture_System.<init>(Furniture_System.java:55)
at assignment.Furniture_System.main(Furniture_System.java:113)
I suppose I should explain that I call this for loop in a void function that implements in a class constructor. That constructor is called in the main program.
And the variable array image is shown here:
private ImageIcon image[] =
{
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\1.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\2.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\3.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\4.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\5.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\6.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\7.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\8.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\9.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\10.jpg"),
};
All I am trying to do is cycle through the array, set and display the images as the cycle goes through.
Below is the whole program to make it easier to fix:
private ImageIcon image[] =
{
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\1.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\2.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\3.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\4.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\5.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\6.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\7.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\8.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\9.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\10.jpg")
};
private JLabel label;
private JLabel sofaImageLabel;
private JLabel armchairImageLabel;
private JLabel cDeskImageLabel;
private JLabel cTableImageLabel;
private JLabel tvStandImageLabel;
private JLabel cushionImageLabel;
private JLabel bedImageLabel;
private JLabel mattressImageLabel;
private JLabel duvetImageLabel;
private JLabel pillowImageLabel;
private JPanel buttonPanel;
private JPanel imagePanel;
private JButton button;
public Furniture_System()
{
setTitle("Furniture Management System");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildImagePanel();
// buildButtonPanel();
add(imagePanel, BorderLayout.WEST);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
private void buildImagePanel()
{
imagePanel = new JPanel();
for (int i = 0; i < 9; i++)
{
label = new JLabel();
label.setIcon(image[i]);
imagePanel.add(label);
}
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
button = new JButton("Get Image");
button.addActionListener(new chooseFileButton());
buttonPanel.add(button);
}
private class chooseFileButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
/* String filename = null;
JFileChooser fileChosen = new JFileChooser();
int status = fileChosen.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChosen.getSelectedFile();
filename = selectedFile.getPath();
JOptionPane.showMessageDialog(null, "You selected " + filename);
}
ImageIcon image = new ImageIcon(filename);
sofaImageLabel.setIcon(image);
sofaImageLabel.setText(null);
pack(); */
}
}
public static void main(String[] args)
{
new Furniture_System();
}
}
Any component can have only one parent container, and not be reused.
So the code must be:
for (ImageIcon img : image)
{
JLabel label = new JLabel();
label.setIcon(img);
imagePanel.add(label);
}
Though I would look in Furniture_System.java at line 55 (in the constructor) what could be an access to null. Like above maybe imagePanel being null.
Hey I could use help debugging this program. The code is not mine, it is from an answer to a question and I wanted to try it but I get a NullPointerException and can't figure out where the problem is. I think the problem may be image paths but I am not sure so I could use help.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class CircleImages {
private int score = 0;
private JTextField scoreField = new JTextField(10);
public CircleImages() {
scoreField.setEditable(false);
final ImageIcon[] icons = createImageIcons();
final JPanel iconPanel = createPanel(icons, 8);
JPanel bottomLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomLeftPanel.add(new JLabel("Score: "));
bottomLeftPanel.add(scoreField);
JPanel bottomRightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton newGame = new JButton("New Game");
bottomRightPanel.add(newGame);
JButton quit = new JButton("Quit");
bottomRightPanel.add(quit);
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
reset(iconPanel, icons);
score = 0;
scoreField.setText(String.valueOf(score));
}
});
JFrame frame = new JFrame();
frame.add(iconPanel);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void reset(JPanel panel, ImageIcon[] icons) {
Component[] comps = panel.getComponents();
Random random = new Random();
for(Component c : comps) {
if (c instanceof JLabel) {
JLabel button = (JLabel)c;
int index = random.nextInt(icons.length);
button.setIcon(icons[index]);
}
}
}
private JPanel createPanel(ImageIcon[] icons, int gridSize) {
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
for (int i = 0; i < gridSize * gridSize; i++) {
int index = random.nextInt(icons.length);
JLabel label = new JLabel(icons[index]);
label.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
score += 1;
scoreField.setText(String.valueOf(score));
}
});
label.setBorder(new LineBorder(Color.GRAY, 2));
panel.add(label);
}
return panel;
}
private ImageIcon[] createImageIcons() {
String[] files = {"DarkGrayButton.png",
"BlueButton.png",
"GreenButton.png",
"LightGrayButton.png",
"OrangeButton.png",
"RedButton.png",
"YellowButton.png"
};
ImageIcon[] icons = new ImageIcon[files.length];
for (int i = 0; i < files.length; i++) {
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
}
return icons;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleImages();
}
});
}
}
Your problem is here:
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
You don't have the required images in your project, so getClass().getResource() will return null and you will have a NullPointerException in the constructor of ImageIcon.
What you have to do is put the following files in your project:
/circleimages/DarkGrayButton.png
/circleimages/BlueButton.png
/circleimages/GreenButton.png
/circleimages/LightGrayButton.png
/circleimages/OrangeButton.png
/circleimages/RedButton.png
/circleimages/YellowButton.png
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);
...