Doesn't display all labels of the arraylist - java

I have a problem that I can't display all the labels in the window
I created 20 labels in the arraylist, but sometimes I get 10, another I got 14 later it became 19 (from 0 to 19). So it cant't display all the labels from the first time.
package Windows;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Protofenetre extends JFrame {
public JPanel panneau;
public ArrayList<JLabel> labels = new ArrayList<JLabel>();
public Protofenetre ()
{
this.setTitle ("The Scopy Zoo :D");
this.setSize(500, 500);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panneau = new JPanel();
panneau.setLayout(null);
this.setContentPane(panneau);
}
}
Here is my Main CLass
package Concession;
import javax.swing.JLabel;
import Windows.Protofenetre;
public class Main_Class {
public static void main(String[] args) {
Protofenetre fenetre = new Protofenetre ();
for(int i=0; i<20; i++)
{
JLabel temp = new JLabel();
temp.setBounds(20, i*20, 200, 100);
temp.setText("pixels" + String.valueOf(i));
temp.setVisible(true);
fenetre.panneau.add(temp);
fenetre.labels.add(temp);
}
}
}
Thanks in advance

Related

How do I update a JLabel during run time

the JLabel's name is set to an int which changes as the user modifies the number, i tried label.revalidate and Label.repaint after the user changes the int value. i have seen in similar questions people suggest creating a new jlabel everytime, but im wondering if there is a simpler way? the code is very long so i will summerize when needed.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class officia {
static JFrame Frame;
static JPanel Panel;
static JTextField healthPlace;
static String health="0";
static JButton begin;
static JLabel heart;
static int loop;
public static void main(String[] args) {
Panel = new JPanel();
Frame = new JFrame();
Frame.setSize(500,1000);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(Panel);
Panel.setLayout(null);
//adds panel and frame
healthPlace = new JTextField();
healthPlace.setBounds(170, 130, 165, 25);
Panel.add(healthPlace);
begin = new JButton("Begin");
begin.setBounds(217, 185, 70, 25);
Panel.add(begin);
while(loop==1)
loop=0;
heart = new JLabel(health);
heart.setBounds(150, -85, 500, 500);
Panel.add(heart);
Frame.setVisible(true);
//inputs gui's
ActionListener beginPressed = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
health = healthPlace.getText();
loop=1;
}
};
begin.addActionListener(beginPressed);
}
}
You're working in a event driven environment, that is, something happens and you respond to it.
This means, you're while-loop is ill-conceived and is probably the source of your issue. How can the ActionListener for the button be added when the loop is running, but you seem to using the ActionListener to exit the loop...
I modified you code slightly, so when you press the button, it will update the label.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class officia {
static JFrame Frame;
static JPanel Panel;
static JTextField healthPlace;
static String health = "0";
static JButton begin;
static JLabel heart;
static int loop;
public static void main(String[] args) {
Panel = new JPanel();
Frame = new JFrame();
Frame.setSize(500, 1000);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(Panel);
Panel.setLayout(null);
//adds panel and frame
healthPlace = new JTextField();
healthPlace.setBounds(170, 130, 165, 25);
Panel.add(healthPlace);
begin = new JButton("Begin");
begin.setBounds(217, 185, 70, 25);
Panel.add(begin);
// This is ... interesting, but a bad idea
// while (loop == 1) {
// loop = 0;
// }
heart = new JLabel(health);
heart.setBounds(150, -85, 500, 500);
Panel.add(heart);
Frame.setVisible(true);
//inputs gui's
ActionListener beginPressed = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
health = healthPlace.getText();
loop ++;
heart.setText(Integer.toString(loop));
}
};
begin.addActionListener(beginPressed);
}
}
JLabel#setText is what's known as a stateful property, that is, it will trigger an update that will cause it to be painted, so, if it's not updating, you're doing something wrong.
Possible runnable example (of what I think you want to do)
You're working a very rich UI framework. One if it's, many, features, is the layout management framework, something you should seriously take the time to learn to understand and use.
See Laying Out Components Within a Container for more details.
Below is a relatively simple example which shows one way you might "swicth" between views based on a response to a user input
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
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 BasePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BasePane extends JPanel {
private CardLayout cardLayout;
public BasePane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
StartPane startPane = new StartPane(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(BasePane.this, "HeartPane");
}
});
HeartPane heartPane = new HeartPane();
add(startPane, "StartPane");
add(heartPane, "HeartPane");
}
}
public class StartPane extends JPanel {
public StartPane(ActionListener actionListener) {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
JButton start = new JButton("Begin");
add(start);
start.addActionListener(actionListener);
}
}
public class HeartPane extends JPanel {
private JTextField heartTextField;
private JLabel heartLabel;
public HeartPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
heartLabel = new JLabel("Heart");
heartTextField = new JTextField(10);
add(heartLabel);
add(heartTextField);
}
}
}

getSelectedIndex() for JList always return -1 eventhough an item is selected

http://prntscr.com/9jhrwa "How the GUI looks"
public class Okno1 extends javax.swing.JFrame {
static Konto[]konto;
static DefaultListModel listModel;
static int indexKonta;
public Okno1() {
initComponents();
napolniKonto();
jScrollPane1.setVisible(false);
button_potrdiKonto.setVisible(false);
}
here I fill my array with Objects and add them to DefaultListModel, also I create a new list with the mentioned DefaultListModel
listModel=new DefaultListModel();
list_konto.setModel(listModel);
konto=new Konto[4];
konto[0]=new Konto("10000/20000", "Test konto primer1");
konto[1]=new Konto("20000/30000", "Test konto primer2");
konto[2]=new Konto("50000/60000", "Test konto primer3");
konto[3]=new Konto("30000/50000", "Test konto primer4");
for (int i = 0; i < konto.length; i++) {
listModel.addElement(konto[i].getID()+" | "+konto[i].getOpis());
}
list_konto=new JList(listModel);
jScrollPane1.repaint();
}
Here I show the jScrollPanel when this button is pressed, I also show the button which must be pressed if I want to get the index of the selected element in the JList displayed
private void button_prikaziKontoActionPerformed(java.awt.event.ActionEvent evt) {
jScrollPane1.setVisible(true);
button_potrdiKonto.setVisible(true);
//revalidate();
//repaint();
}
Here I press a button and it should get me the index of the selected item, but it keeps giving me -1 and it doesn't matter if an item on the JList is selected or is not
private void button_potrdiKontoActionPerformed(java.awt.event.ActionEvent evt) {
//indexKonta=list_konto.getSelectedIndex();
text_opisKonta.setText(Integer.toString(list_konto.getSelectedIndex()));
}
It's not clear where your code is going awry. This compete example may allow you to study the problem in isolation. Also consider adding a ListSelectionListener to see the effect.
myList.addListSelectionListener((ListSelectionEvent e) -> {
myLabel.setText(getSelectionIndex());
});
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
/** #see http://stackoverflow.com/a/34497773/230513 */
public class Test extends JPanel {
private final String[] values = {"Value1", "Value2", "Value3", "Value4"};
private final JList myList = new JList(values);
private final JLabel myLabel = new JLabel();
public Test() {
myList.setSelectedIndex(values.length - 1);
myLabel.setText(getSelectionIndex());
this.add(myList);
this.add(myLabel);
this.add(new JButton(new AbstractAction("Show Selected Index") {
#Override
public void actionPerformed(ActionEvent e) {
myLabel.setText(getSelectionIndex());
}
}));
}
private String getSelectionIndex() {
return String.valueOf(myList.getSelectedIndex());
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Test());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
});
}
}
don't use static variables
always to test if (list.getSelectedIndex() > -1) {
use ListSelectionListener for JList, by always testing if (list.getSelectedIndex() > -1) {
for example (without using ListSelectionListener)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class JListAndSelection {
private JFrame frame = new JFrame();
private DefaultListModel listModel = new DefaultListModel();
private JList list = new JList(listModel);
private JScrollPane scrollPane = new JScrollPane(list);
private JLabel label = new JLabel("nothing is selected");
private JButton button1 = new JButton("print me selected value");
public JListAndSelection() {
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (list.getSelectedIndex() > -1) {
label.setText((String) list.getSelectedValue());
} else {
label.setText("nothing is selected");
}
}
});
listModel.addElement("10000/20000 - Test konto primer1");
listModel.addElement("20000/30000 - Test konto primer2");
listModel.addElement("50000/60000 - Test konto primer3");
listModel.addElement("30000/50000 - Test konto primer4");
list.setVisibleRowCount(5);
frame.setTitle("JFrame");
frame.add(label, BorderLayout.NORTH);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(button1, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new JListAndSelection();
});
}
}

netbeans does not run javaswing application

The JavaSwing application shows no errors in netbeans. When I try to run it, it takes forever and nothing is happening(JDK 8 + Netbeans 8.1). The same problem in eclipse. A simple hello world program works. The program is divided in 4 classes. Sorry for the long code.
package test2;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class MainWindow extends JFrame {
private Navigator navigator = new Navigator(this);
private Field spielfeld = new Field();
public MainWindow() {
super("GameTest");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.add(spielfeld);
this.setResizable(false);
this.pack();
}
public static void main(String[] args) {
new MainWindow();
}
}
package test2;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
public class Field extends JPanel {
private static int x = 10;
private static int y = 10;
private JLabel[][] fields = new JLabel[10][10];
public Field() {
Dimension dim = new Dimension();
dim.setSize(50, 50);
this.setLayout(new GridLayout(x, y));
for(int i = 0; i < y; i++){
for(int j = 0; j < x; j++){
fields[i][j] = new JLabel();
fields[i][j].setPreferredSize(dim);
fields[i][j].setOpaque(true);
if((i+j)%2 == 0){
fields[i][j].setBackground(Color.BLACK);
}
else {
fields[i][j].setBackground(Color.WHITE);
}
this.add(fields[i][j]);
}
}
}
}
package test2;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JWindow;
public class Navigator extends JWindow {
public Navigator(JFrame parent) {
super(parent);
JPanel frame = new JPanel();
frame.setLayout(new BorderLayout());
frame.setBorder(BorderFactory.createLineBorder(Color.RED));
frame.add(new Keypad(), BorderLayout.NORTH);
this.getContentPane().add(frame);
this.updateLocation();
this.pack();
}
public void updateLocation()
{
this.setLocation((int)this.getParent().getLocation().getX() + this.getParent().getWidth() + 550,
(int)this.getParent().getLocation().getY());
}
public MainWindow getMainWindow()
{
return (MainWindow)this.getParent();
}
}
package test2;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Keypad extends JPanel {
public Keypad() {
Dimension dim = new Dimension(60, 30);
this.setLayout(new GridLayout(3, 3));
this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
for(int i = 9; 0 < i; i--) {
JButton button = new JButton(String.valueOf(i));
button.setPreferredSize(dim);
button.setVisible(true);
if(i != 5) {
this.add(button);
this.add(button);
}
}
this.setVisible(true);
}
}
You are missing setVisible(true) inside your MainWindow constructor.
The code will "run forever" with or without this line. The only difference is that the window will be shown.

Java GUI appears to be blank (swing + awt)

I'm having trouble getting my GUI to contain any of my JButtons or JTextField. I have two classes One "SnowballFight" class that contains my main method and frame constructor. Then I also have "GameBoard" which sets up my GUI. My problem is that my GUI appears, but appears empty.
"SnowballFight" class:
package snowballfight;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SnowballFight extends JFrame implements ActionListener{
public SnowballFight(){
setLayout(new BorderLayout(1,2));
}
public static void main(String[] args) {
SnowballFight frame = new SnowballFight();
GameBoard game = new GameBoard(frame);
}
public void actionPerformed(ActionEvent event) {
}
}
"GameBoard" class:
package snowballfight;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameBoard extends JFrame implements ActionListener{
private JButton[][] game = new JButton[10][10];
private JTextField display = new JTextField("Welcome to the SnowBall fight!");
private Opponent[] opponents = new Opponent[4];
public GameBoard(SnowballFight frame){
JPanel panel = new JPanel();
panel.setLayout(new GridLayout( 10, 10));
for (int row = 0; row < game.length; row++) {
for (int col = 0; col < game[row].length; col++) {
game[row][col] = new JButton();
game[row][col].setBackground(Color.gray);
game[row][col].addActionListener(this);
panel.add(game[row][col]);
}
}
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.SOUTH);
frame.setTitle("Snowball Fight");
frame.setSize(200, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public boolean isGameOver(){
for (int opponent = 0; opponent < opponents.length; opponent++) {
if(opponents[opponent].isSoaked() == false ){
return false;
}
}
return true;
}
public void actionPerformed(ActionEvent event) {
}
}
Not sure why there are two frames, but I think you're adding display and panel to the wrong frame.
Try changing:
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.SOUTH);
to:
frame.add(display, BorderLayout.NORTH);
frame.add(panel, BorderLayout.SOUTH);
You never make the GameBoard JFrame visible
game.setVisible(true);
Some notes:
The frame SnowballFight has no apparent function
It's not necessary to extend JFrame since no functionality is being added
Read The Use of Multiple JFrames, Good/Bad Practice?

addActionListener on panel. How to map to main frame?

I have 2 panel (2 class, extends from JPanel), 1 frame (1 class, extends from JFrame)
My first panel - WelcomePanel:
package caro;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class WelcomePanel extends JPanel {
public WelcomePanel() {
ImageIcon logoImage = new ImageIcon("/home/khanhpq/logo.png");
JButton playButton = new JButton("Play");
JButton exitButton = new JButton("Exit");
JLabel imageLabel = new JLabel(logoImage);
add(imageLabel);
add(playButton);
add(exitButton);
playButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(null, "Are you sure ?", "Warning", JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
}
}
My second panel - BoardPanel:
package caro;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class BoardPanel extends JPanel {
public BoardPanel() {
JPanel boardPanel = new JPanel();
Board board = new Board();
CellButton cellButton[] = new CellButton[144];
GridLayout gridLayout = new GridLayout(12, 12);
boardPanel.setLayout(gridLayout);
for (int i = 0; i < 144; i++) {
cellButton[i] = new CellButton();
boardPanel.add(cellButton[i]);
}
}
}
My main frame - MainFrame
package caro;
import javax.swing.JFrame;
public class MainFrame extends JFrame {
public MainFrame() {
add(new WelcomePanel());
setSize(360, 380);
setVisible(true);
}
public static void main(String[] args) {
MainFrame startFrame = new MainFrame();
}
}
My question: Help me write code, addActionListener on buttons of panels (material example). When i press play button (of WelcomePanel), WelcomePanel is hidden and BoardPanel is show. And, when i exit BoardPanel (close button is pressed, or click x button), WelcomePanel is showed.
My friend recommend use Message and Handle, but I don't know. Please help me. Thanks.
Its better to declare dependencies (Component like buttons, panels, etc...) as fields. In this way they are visible for a third class that is the Controller of them. In next examaple I make MainFrame controlling itself, just an example. Read about Presentation patterns for better pratices.
WelcomePanel.java
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class WelcomePanel extends JPanel {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
ImageIcon logoImage;
JButton playButton;
JButton exitButton;
JLabel imageLabel;
public WelcomePanel() {
logoImage = new ImageIcon("/home/khanhpq/logo.png");
playButton = new JButton("Play");
exitButton = new JButton("Exit");
imageLabel = new JLabel(logoImage);
add(imageLabel);
add(playButton);
add(exitButton);
}
}
BoardPanel.java
import javax.swing.JButton;
import javax.swing.JPanel;
public class BoardPanel extends JPanel {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
JButton closeButton;
public BoardPanel() {
closeButton = new JButton();
add(closeButton);
}
}
MainFrame.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame implements ActionListener {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
WelcomePanel welcomePanel;
BoardPanel boardPanel;
public MainFrame() {
welcomePanel = new WelcomePanel();
boardPanel = new BoardPanel();
add(welcomePanel);
add(boardPanel);
boardPanel.setVisible(false);
boardPanel.closeButton.addActionListener(this);
welcomePanel.playButton.addActionListener(this);
setSize(360, 380);
}
/**
* This class is the controller.
*/
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(boardPanel.closeButton)) {
welcomePanel.setVisible(false);
boardPanel.setVisible(true);
} else if (e.getSource().equals(welcomePanel.playButton)) {
welcomePanel.setVisible(true);
boardPanel.setVisible(false);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame startFrame = new MainFrame();
startFrame.setVisible(true);
}
});
}
}

Categories

Resources