How to also change int if Jlabel is changed - java

I am trying to figure out how I can also change my int if my Jlabel is changed. I tried to use AtomicInteger and it works if I only want to change n1, but how do I make it that it looks at the label and then changes the correct int? At the moment I have n1 - n3, but in the future that will be 30.
This is my code at the moment:
public class GUI {
JLabel currentEditLabel = null;
JFrame frame;
int n1 = 6;
int n2 = 5;
int n3 = 8;
GUI() {
frame = new JFrame();//creating instance of JFrame
JLabel l1 = new JLabel(Integer.toString(n1));
JLabel l2 = new JLabel(Integer.toString(n2));
JLabel l3 = new JLabel(Integer.toString(n3));
JTextField t = new JTextField();
l1.setBounds(40, 50, 100, 40);
l2.setBounds(40, 100, 100, 40);
l3.setBounds(40, 150, 100, 40);
t.setBounds(20, 200, 100, 40);
frame.add(l1);
frame.add(l2);
frame.add(l3);
frame.add(t);
t.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (currentEditLabel != null) {
currentEditLabel.setText(t.getText());
AtomicInteger level = new AtomicInteger(Integer.parseInt(currentEditLabel.getText()));
n1 = level.intValue();
currentEditLabel = null;
}
}
});
addMouseListener(l1, t);
addMouseListener(l2, t);
addMouseListener(l3, t);
frame.setSize(400, 500);//400 width and 500 height
frame.setLayout(null);//using no layout managers
frame.setVisible(true);//making the frame visible
}
private void addMouseListener(JLabel label, JTextField t) {
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
currentEditLabel = (JLabel) e.getComponent();
t.setText(currentEditLabel.getText());
}
});
}
public static void main(String[] args) {
new GUI();
}
}

AtomicInteger? You're barking up the wrong tree since this won't help you in the least.
Your n1 value does in fact change within the listener, but you're not changing the JLabel text at all, and that is what you need to do:
In the MouseListener, also call setText(...) on whatever JLabel (the one clicked perhaps) that you wish to have the text display change on.
While the l1 JLabel's displayed text is created using n1's value, note that if n1 ever changes, l1
s text will not change on its own. Again, if you wish to change l1's text, you must do so with code, calling .setText(...) on it.
Some suggestions based on your new requirements:
Create an array of int to hold the int values
Create a List<JLabels> to hold all the JLabels that will display the values held in the above collection of numbers
Create your JLabels in a for loop that loops through all the ints, and fill each JLabel with the appropriate number text
In that same for loop, add your JLabels to the JLabel-list mentioned above
Add a MouseListener (I usually use a MouseAdapter for this) to each JLabel in the for loop
Pass the for loop's index into your MouseListener's constructor to set a field of the class, so that the index of the selected JLabel is readily available
Use a JSpinner and SpinnerNumberModel to display the changable text
In the MouseLister, set the value that the spinner holds
Add a ChangeListener to the spinner so that when the numeric value changes, you update the appropriate JLabel with the new value
You will need to also remove the above ChangeListener before setting the spinner's value in the mouse listener and then re-add the same listener immediately after making this change.
Do not use AtomicInteger as it is completely unnecessary and is somewhat misleading to you
Avoid using null layouts but instead use layout managers
Proof of concept:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
#SuppressWarnings("serial")
public class GUI2 extends JPanel {
private static final Border UNSELECTED_BORDER = BorderFactory.createLineBorder(Color.LIGHT_GRAY, 3);
private static final Border SELECTED_BORDER = BorderFactory.createLineBorder(Color.PINK, 3);
private int[] intArray = { 6, 5, 8, 13, 17, 22, 55, 33, 2, 0, 23, 51, 0, 111, 200, 6, 5, 8, 13, 17, 22, 55, 33, 2,
0, 23, 51, 0, 111, 200, 6, 5, 8, 13, 17, 22, 55, 33, 2, 0, 23, 51, 0, 111, 200 };
private SpinnerNumberModel spinnerModel = new SpinnerNumberModel(0, 0, 10000, 1);
private JSpinner intSpinner = new JSpinner(spinnerModel);
private ChangeListener spinnerListener = new SpinnerListener();
private List<JLabel> labelList = new ArrayList<>();
private int selectedIndex = -1;
public GUI2() {
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Current Selected Value:"));
topPanel.add(Box.createHorizontalStrut(5));
topPanel.add(intSpinner);
intSpinner.addChangeListener(spinnerListener);
int gap = 3;
JPanel labelGridPanel = new JPanel(new GridLayout(0, 5, gap, gap));
for (int i = 0; i < intArray.length; i++) {
String text = String.valueOf(intArray[i]);
JLabel label = new JLabel(text);
label.setBorder(UNSELECTED_BORDER);
label.addMouseListener(new MyMouse(i));
labelGridPanel.add(label);
labelList.add(label);
}
setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
setLayout(new BorderLayout(gap, gap));
add(topPanel, BorderLayout.PAGE_START);
add(labelGridPanel, BorderLayout.CENTER);
}
private class MyMouse extends MouseAdapter {
private int index;
public MyMouse(int index) {
this.index = index;
}
#Override
public void mousePressed(MouseEvent e) {
selectedIndex = index;
JLabel label = labelList.get(index);
int currentValue = Integer.parseInt(label.getText());
// remove change listener before making this change
intSpinner.removeChangeListener(spinnerListener);
intSpinner.setValue(currentValue);
// then re-add the change listener after
intSpinner.addChangeListener(spinnerListener);
// show by border which JLabel has been selected
for (JLabel jLabel : labelList) {
// first make all borders the default border
jLabel.setBorder(UNSELECTED_BORDER);
}
// then set the selected border
labelList.get(index).setBorder(SELECTED_BORDER);
}
}
private class SpinnerListener implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
// if we have not yet selected a JLabel, get out of here
if (selectedIndex < 0) {
return;
}
int value = (int) spinnerModel.getValue();
labelList.get(selectedIndex).setText(Integer.toString(value));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GUI2 mainPanel = new GUI2();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

In your code, you only update n1 regardless of which label is the currentEditLabel.
Your code:
currentEditLabel.setText(t.getText());
AtomicInteger level = new AtomicInteger(Integer.parseInt(currentEditLabel.getText()));
n1 = level.intValue();
currentEditLabel = null;
Solution: You need to know which label is the currentEditLabel so that you can update the correct variable. Your action listener will need access to l1, l2 and l3. So, instead of defining them in the constructor, define them as instance variables same way you defined n1, n2, and n3.
currentEditLabel.setText(t.getText());
AtomicInteger level = new AtomicInteger(Integer.parseInt(currentEditLabel.getText()));
if (currentEditLabel == l1)
n1 = level.intValue();
else if (currentEditLabel == l2)
n2 = level.intValue();
else
n3 = level.intValue();
currentEditLabel = null;

Related

How to calculate summation values from multiple JTextFields using loop in java

I am trying to making a calculator.
Here the user can add multiple JTextFields to take his/her desired input with just one button click.
Now I want that the user will take the input in multiple JTextFields added by him and on clicking the Result button will show the sum of all. But I am always getting 0 as output.
Code:
public class Button extends JFrame {
private JPanel contentPane;
private JButton btnAdd;
private JButton btnResult;
private JTextField resultField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Button frame = new Button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Button() {
initComponents();
}
static JTextField field = null;
//static JTextField fields[] = new JTextField[10];
private static int y = 0;
ArrayList<String> arr = new ArrayList<String>();
int ans, sum = 0;
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 527, 414);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field = new JTextField();
field.setBounds(45, y += 60, 284, 32);
field.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(field);
contentPane.revalidate();
contentPane.repaint();
}
});
btnAdd.setBounds(170, 341, 89, 23);
contentPane.add(btnAdd);
btnResult = new JButton("Result");
btnResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < arr.size(); i++) {
arr.add(field.getText());
sum += Integer.parseInt(arr.get(i));
}
resultField.setText(String.valueOf(sum));
}
});
btnResult.setBounds(383, 306, 89, 23);
contentPane.add(btnResult);
resultField = new JTextField();
resultField.setBounds(361, 275, 129, 20);
contentPane.add(resultField);
resultField.setColumns(10);
}
}
Please help how can I find the correct output?
Suggestions:
Again, when you create a data-entry text field, add it to the GUI and add it to an ArrayList of the data entry field type.
Then in the result button's ActionListener, iterate through this list using a for loop.
Inside of the for loop, get the entry field, get its text (via .getText() if using a JTextField), parse it to number via Integer.parseInt(...), and add it to a sum variable that is initialized to 0 prior to the for loop. Then display the result after the loop.
Also,
Best to use JSpinners that use a SpinnerNumberModel such as JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1)); instead of JTextField for number entry. This will limit the user to entering numbers only, and won't allow non-numeric text entry, a danger inherent in your current design.
Having to add your entry fields by button may be an over-complication
But if it is necessary, then best to add the spinners (or text fields if you must) to a JPanel that uses a proper layout manager, such a new GridLayout(0, 1) (variable number of rows, 1 column) and then add that to a JScrollPane so that you can see as many fields as has been entered.
If using a JSpinner, then you don't even need a "calculate result" button, since if you add a ChangeListener to each JSpinner, you can calculate the result on the fly whenever a spinner has had its data changed.
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Button2 extends JPanel {
private List<JSpinner> spinnerList = new ArrayList<>();
private JButton resultButton = new JButton("Result");
private JButton addEntryFieldBtn = new JButton("Add Entry Field");
private JTextField resultField = new JTextField(6);
private JPanel fieldPanel = new JPanel(new GridLayout(0, 1, 4, 4));
public Button2() {
resultField.setFocusable(false);
resultButton.addActionListener(e -> calcResult());
resultButton.setMnemonic(KeyEvent.VK_R);
addEntryFieldBtn.addActionListener(e -> addEntryField());
JPanel topPanel = new JPanel();
topPanel.add(addEntryFieldBtn);
topPanel.add(resultButton);
topPanel.add(new JLabel("Result:"));
topPanel.add(resultField);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(fieldPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(centerPanel);
scrollPane.setPreferredSize(new Dimension(300, 300));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane);
}
private void calcResult() {
int sum = 0;
for (JSpinner spinner : spinnerList) {
sum += (int) spinner.getValue();
}
resultField.setText(String.valueOf(sum));
}
private void addEntryField() {
JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinner.addChangeListener(evt -> {
calcResult();
});
fieldPanel.add(spinner);
spinnerList.add(spinner);
revalidate();
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Button2 mainPanel = new Button2();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

JScrollPane "stretching" out the panel that I add to it

I have to make a scrollable list where I can add a panel with 3 labels many times.
I kind of made it work but the first panels are stretched and occupy all the area of the JScrollPane and I can't figure out how to fix this, I tried changing layouts many times but still didn't manage to fix it.
I want the added panel to occupy a fixed size but I can't figure this out. Example in this picture:
https://i.stack.imgur.com/LNznP.png
The one on the left is the one that I get and the one on the right (edited) is how I want it to work.
This is my first day of Swing so the code is very likely a mess, sorry in advance.
Here is the code:
public class MainWindow extends JFrame implements ActionListener{
private JPanel viewportPanel;
private JButton addButton,remButton;
private JScrollPane scrollPane;
private int counter = 0;
private JLabel dateLabel,dateLabel_1,dateLabel_2;
public MainWindow(boolean run) {
//BUTTONS
addButton = new JButton("Add");
addButton.setLocation(521, 11);
addButton.setSize(101, 100);
addButton.addActionListener(this);
remButton = new JButton("Remove");
remButton.setLocation(521, 122);
remButton.setSize(101, 100);
remButton.addActionListener(this);
//SCROLLPANE
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 11, 501, 211);
add(scrollPane);
//PANELS
viewportPanel = new JPanel(new GridLayout(0,1));
scrollPane.setViewportView(viewportPanel);
//FRAME
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 273);
setResizable(false);
//setIconImage(new ImageIcon("epic.png").getImage());
setLayout(null);
if(run) setVisible(true);
add(addButton);
add(remButton);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addButton) {
//LABELS
dateLabel = new JLabel("DATE");
dateLabel.setFont(new Font("Tahoma", Font.BOLD, 28));
dateLabel.setSize(500,500);
dateLabel_1 = new JLabel("LABEL1");
dateLabel_1.setFont(new Font("Tahoma", Font.BOLD, 22));
dateLabel_1.setBounds(10, 45, 481, 30);
dateLabel_2 = new JLabel("LABEL2");
dateLabel_2.setFont(new Font("Tahoma", Font.ITALIC, 22));
dateLabel_2.setBounds(10, 45, 481, 30);
//PANEL WITH ALL THE STUFF
JPanel componentPanel = new JPanel();
componentPanel.setLayout(new GridLayout(3, 1));
componentPanel.setMaximumSize(new Dimension(50,50));
componentPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));
componentPanel.setBackground(Color.gray);
componentPanel.add(dateLabel);
componentPanel.add(dateLabel_1);
componentPanel.add(dateLabel_2);
viewportPanel.add(componentPanel); //add panel with labels to viewportpanel
counter++;
}
if(e.getSource() == remButton) {
Component[] componentList = viewportPanel.getComponents();
int lastElement = (componentList.length);
viewportPanel.remove(--lastElement);
--counter;
}
viewportPanel.revalidate();
viewportPanel.repaint();
}
}
Some help would be amazing!
First off, never do this:
setLayout(null);
Next, if you want things compressed at the top of a container, then use a layout that does this. such as a BorderLayout with the compressed items placed into a JPanel (perhaps one that uses a GridLayout) that is placed BorderLayout.PAGE_START
Actually, it looks as if your best solution is to us a JList, one that uses a custom renderer that places your time JLabel and two text JLabels into a JPanel and displays this in the list. So let's explore that.
First create a class to hold the data that is displayed by the JList, which looks to be a date and two lines of text:
public class ListItem {
private LocalDate date;
private String text1;
private String text2;
public ListItem(LocalDate date, String text1, String text2) {
super();
this.date = date;
this.text1 = text1;
this.text2 = text2;
}
public LocalDate getDate() {
return date;
}
public String getText1() {
return text1;
}
public String getText2() {
return text2;
}
}
Then let's create a renderer that a JList can use to display the above information in a JPanel. This is more complicated and requires that the class create a JPanel that places the labels where we want them, perhaps using a GridLayout with 1 column and 3 rows, plus some gaps between the rows: setLayout(new GridLayout(3, 1, 2 * gap, 2 * gap));. The class must implement the ListCellRenderer<T> interface which has one method: public Component getListCellRendererComponent(...). Java will pass in the paramters into this method, including a ListItem value, and we will use that value to fill in the JLabels that we add into this JPanel. Edited to highlight selected items.
import java.awt.*;
import java.time.format.DateTimeFormatter;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class ListItemRenderer extends JPanel implements ListCellRenderer<ListItem> {
private static final Color LIGHT_BLUE = new Color(204, 255, 255);
private static final Color REDDISH_GREY = new Color(205, 126, 121);
private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
private static final int GAP = 2;
private Border emptyBorder = BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP);
private Border blackBorder = BorderFactory.createLineBorder(Color.BLACK);
private Border redBorder = BorderFactory.createLineBorder(REDDISH_GREY, 2);
private JLabel dateLabel = new JLabel();
private JLabel text1Label = new JLabel();
private JLabel text2Label = new JLabel();
public ListItemRenderer() {
dateLabel.setFont(dateLabel.getFont().deriveFont(Font.BOLD, 14f));
text1Label.setFont(text1Label.getFont().deriveFont(Font.BOLD));
text2Label.setFont(text1Label.getFont().deriveFont(Font.ITALIC));
int gap = 2;
setLayout(new GridLayout(0, 1, 2 * gap, 2 * gap));
setBorder(BorderFactory.createCompoundBorder(emptyBorder, blackBorder));
add(dateLabel);
add(text1Label);
add(text2Label);
}
#Override
public Component getListCellRendererComponent(JList<? extends ListItem> list, ListItem value, int index,
boolean isSelected, boolean cellHasFocus) {
if (value != null) {
String dateText = dateFormatter.format(value.getDate());
dateLabel.setText(dateText);
text1Label.setText(value.getText1());
text2Label.setText(value.getText2());
} else {
dateLabel.setText("");
text1Label.setText("");
text2Label.setText("");
}
if (isSelected ) {
setBackground(LIGHT_BLUE);
setBorder(BorderFactory.createCompoundBorder(emptyBorder, redBorder));
} else {
setBackground(null);
setBorder(BorderFactory.createCompoundBorder(emptyBorder, blackBorder));
}
return this;
}
}
And now the main program that puts this all together, edited to show removing items:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class MainPanel extends JPanel {
DefaultListModel<ListItem> listModel = new DefaultListModel<>();
private JList<ListItem> jList = new JList<>(listModel);
private JScrollPane scrollPane = new JScrollPane(jList);
private JButton addButton = new JButton("Add");
private JButton removeButton = new JButton("Remove");
public MainPanel() {
jList.setPrototypeCellValue(new ListItem(LocalDate.now(),
"This is text 1 for testing. This is text 1 for testing. This is text 1 for testing",
"This is text 2 for testing. This is text 2 for testing. This is text 2 for testing"));
jList.setVisibleRowCount(4);
jList.setCellRenderer(new ListItemRenderer());
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 3, 3));
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
addButton.setMnemonic(KeyEvent.VK_A);
removeButton.setMnemonic(KeyEvent.VK_R);
addButton.addActionListener(e -> addEvent());
removeButton.addActionListener(e -> removeEvent());
JPanel rightPanel = new JPanel();
rightPanel.add(buttonPanel);
int gap = 5;
setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
setLayout(new BorderLayout());
add(scrollPane);
add(rightPanel, BorderLayout.LINE_END);
}
private void removeEvent() {
int[] selectedIndices = jList.getSelectedIndices();
for (int i = selectedIndices.length - 1; i >= 0; i--) {
listModel.remove(selectedIndices[i]);
}
}
private void addEvent() {
// this adds random stuff to the JList
String text1 = "Some random text: " + randomText();
String text2 = "Some random text: " + randomText();
listModel.addElement(new ListItem(LocalDate.now(), text1, text2));
// TODO: change this so that it adds *real* data to the JList
}
private String randomText() {
Random random = new Random();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 2 + random.nextInt(3); i++) {
for (int j = 0; j < 3 + random.nextInt(5); j++) {
char c = (char) ('a' + random.nextInt('z' - 'a'));
builder.append(c);
}
builder.append(" ");
}
return builder.toString();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Output would look like:

Writing a small app for a DnD puzzle and have trouble with a JButton array

After adding an object of class Puzzle to Main everything displays mostly as it should. when I click any of the buttons some indexes of state should swap to the opposite so from true to false or from false to true.
unfortunately button clicking doesn't want to register for any of the buttons from the array yet it does register for a single button that was initialized by itself. How can I fix the problem?
my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
public class Puzzle extends JFrame implements ActionListener
{
int doors = 8;
boolean [] state = new boolean[doors];
JButton [] levers = new JButton[doors];
JButton weird = new JButton("weird lever");
JLabel display = new JLabel();
Puzzle()
{
reset();
this.setSize(new Dimension(1920, 1080));
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setResizable(false);
this.setLayout(null);
this.add(display);
this.add(weird);
int num = levers.length;
int start = 50;
int size = (1920-(num+1)*start)/num;
char label = 'A';
display.setBounds(size*2, 150, 2000, 300);
display.setFont(new Font("Arial Black", Font.PLAIN, 200));
Display();
for(JButton i : levers)
{
i = new JButton(String.valueOf(label));
label++;
i.setBounds(start, 500, size, size);
start+=(size+50);
i.addActionListener(this);
i.setFont(new Font("Arial black", Font.PLAIN, size/2));
i.setFocusable(false);
this.add(i);
}
weird.setFocusable(false);
weird.setBounds(550, 800, 800, 200);
weird.setFont(new Font("Arial Black", Font.PLAIN, size/2));
weird.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e)
{
/*if(e.getSource() == levers[0])
{
state[2] = Swap(state[2]);
Display();
}
if(e.getSource() == levers[1])
{
state[4] = Swap(state[4]);
state[6] = Swap(state[6]);
Display();
}
if(e.getSource() == levers[2])
{
state[2] = Swap(state[2]);
state[3] = Swap(state[3]);
state[6] = Swap(state[6]);
state[7] = Swap(state[7]);
Display();
}
if(e.getSource() == levers[3])
{
state[0] = Swap(state[0]);
state[2] = Swap(state[2]);
state[7] = Swap(state[7]);
Display();
}
if(e.getSource() == levers[4])
{
state[1] = Swap(state[1]);
state[3] = Swap(state[3]);
state[4] = Swap(state[4]);
state[5] = Swap(state[5]);
Display();
}
if(e.getSource() == levers[5])
{
state[0] = Swap(state[0]);
state[2] = Swap(state[2]);
state[6] = Swap(state[6]);
Display();
}
if(e.getSource() == levers[6])
{
state[1] = Swap(state[1]);
state[5] = Swap(state[5]);
Display();
}
if(e.getSource() == levers[7])
{
state[1] = Swap(state[1]);
state[2] = Swap(state[2]);
state[4] = Swap(state[4]);
state[5] = Swap(state[5]);
Display();
}
*/
if(e.getSource() == levers[0])
{
display.setText("A works");
}
if(e.getSource() == weird)
{
display.setText("test");
}
}
boolean Swap(boolean n)
{
return !n;
}
void Display()
{
StringBuilder toDisplay = new StringBuilder();
for (boolean j : state)
{
if (j)
{
toDisplay.append("| ");
} else
toDisplay.append("_ ");
}
display.setText(toDisplay.toString());
}
void reset ()
{
Arrays.fill(state, true);
}
}```
button clicking doesn't want to register for any of the buttons from the array yet it does register for a single button
System.out.println( levers[0] );
if(e.getSource() == levers[0])
{
display.setText("A works");
}
Add some debug code to your ActionListener and you will see that the value of levers[0] is "null".
for(JButton i : levers)
{
i = new JButton(String.valueOf(label));
label++;
i.setBounds(start, 500, size, size);
start+=(size+50);
i.addActionListener(this);
i.setFont(new Font("Arial black", Font.PLAIN, size/2));
i.setFocusable(false);
this.add(i);
}
You create the button, but you never add the instance of each button to the Array.
for(JButton i : levers)
Why would you use "i" as the variable name. Typically "i" is used as an index. Use a proper variable name, like "button". However, in this case you don't want to use a "for each" loop.
Instead you want a normal for loop so you can index your Array to add each button as you create it:
//for(JButton i : levers)
for (int i = 0; i < doors; i++)
{
JButton button = new JButton(String.valueOf(label));
levers[i] = button;
...
Other issues:
method names should NOT start with an upper case character.
components should be added to the frame BEFORE the frame is made visible.
components should be created on the Event Dispatch Thread (EDT).
Don't use a null layout and setBounds(). Swing was designed to be used with layout managers.
Don't hardcode screen sizes. Instead you can use frame.setExtendedState(JFrame.MAXIMIZED_BOTH);, so it will work for all screen sizes.
Introduction
Your code was too complex for me to understand. I like simple code. Short methods and simple classes.
Here's the GUI I came up with.
Here's the GUI after I clicked a couple of letter JButtons
Explanation
Oracle has a nifty tutorial, Creating a GUI With JFC/Swing, which will show you how to create a Swing GUI. Skip the Netbeans section.
Your code was missing a main method, so I added one. I started the Swing application with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The first thing I did was create a PuzzleModel class to hold the boolean array. It's a good idea to separate your model from your view and controller classes. This pattern is the model / view / controller (MVC) pattern.
A Swing JFrame can contain many JPanels. I created a segment JPanel to hold a JLabel and a JButton aligned vertically. I used the GridBagLayout to align the JLabel and JButton. Swing layout managers help you to avoid absolute positioning and the problems that come with absolute positioning.
I created a main JPanel to hold 8 segment JPanels. These JPanels are aligned with a FlowLayout.
As you can see, my JFrame is smaller than yours. You create as small a JFrame as possible. If the user wants to make it bigger, that's what the rectangle in the upper right corner is for.
Swing is meant to be designed from the inside out. You don't specify a JFrame size and try to make the components fit. You create the components and let Swing determine the size of the JFrame. If you want the JFrame I created to be bigger, increase the font sizes. Hint: A fraction or multiple of 72 points looks better on most displays.
I created two ActionListener classes, one for the alphabet JButtons and one for the lever JButton. This makes it easier to focus on the alphabet JButtons. All you have to do in the ActionListener is swap the appropriate isVertical boolean values when each JButton is left-clicked. I just flipped the corresponding boolean as a demonstration.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PuzzleGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PuzzleGUI());
}
private JLabel[] leverLabel;
private final PuzzleModel model;
public PuzzleGUI() {
this.model = new PuzzleModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Weird Lever");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.add(createButtonPanel(), BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
System.out.println(frame.getSize());
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
char c = 'A';
boolean[] isVertical = model.getIsVertical();
leverLabel = new JLabel[isVertical.length];
for (int i = 0; i < isVertical.length; i++) {
String labelText = (isVertical[i]) ? "|" : "-";
panel.add(createLeverButtonPanel(labelText, Character.toString(c), i));
c = (char) (((int) c) + 1);
}
return panel;
}
public void updateMainPanel() {
boolean[] isVertical = model.getIsVertical();
for (int i = 0; i < isVertical.length; i++) {
String labelText = (isVertical[i]) ? "|" : "-";
leverLabel[i].setText(labelText);
}
}
private JPanel createLeverButtonPanel(String labelText, String buttonText, int index) {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font font1 = new Font("Arial Black", Font.PLAIN, 144);
Font font2 = new Font("Arial Black", Font.PLAIN, 72);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
leverLabel[index] = new JLabel(labelText);
leverLabel[index].setFont(font1);
panel.add(leverLabel[index], gbc);
gbc.gridy++;
JButton button = new JButton(buttonText);
button.addActionListener(new AlphabetButtonListener());
button.setFont(font2);
panel.add(button, gbc);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font font2 = new Font("Arial Black", Font.PLAIN, 48);
JButton button = new JButton("Weird Lever");
button.addActionListener(new LeverButtonListener());
button.setFont(font2);
panel.add(button);
return panel;
}
public class AlphabetButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
String text = button.getText();
char c = text.charAt(0);
int index = ((int) c - 'A');
model.swap(index);
updateMainPanel();
}
}
public class LeverButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
}
}
public class PuzzleModel {
private boolean[] isVertical;
public PuzzleModel() {
int doors = 8;
this.isVertical = new boolean[doors];
reset();
}
private void reset() {
Arrays.fill(isVertical, true);
}
public void swap(int index) {
isVertical[index] = !isVertical[index];
}
public boolean[] getIsVertical() {
return isVertical;
}
}
}

JLabel not positioning correctly

I am just throwing together a quick and dirty GUI to display some data when I ran into an odd issue. The last label I add to the JFrame doesn't want to be positioned or display the border I put on it, so it looks like this:
Here is my code:
public DisplayData (Connection tConn)
{
ID = tID;
conn = tConn;
setupObjects();
setupFrame();
}
private void setupObjects()
{
JLabel caseLabel = new JLabel ("Case #:");
JLabel dateLabel = new JLabel ("Date:");
JLabel reportLabel = new JLabel ("Report:");
JLabel offenceLabel = new JLabel ("Offence:");
JLabel descriptionLabel = new JLabel ("Description:");
this.add(caseLabel);
this.add(dateLabel);
this.add(reportLabel);
this.add(offenceLabel);
this.add(descriptionLabel);
caseLabel.setBounds(50, 50, 130, 25); //x, y, width, height
dateLabel.setBounds(50, 100, 130, 25);
reportLabel.setBounds(50, 150, 130, 25);
offenceLabel.setBounds(50, 200, 130, 25);
descriptionLabel.setBounds(100, 50, 130, 25);
caseLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
dateLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
reportLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
offenceLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
descriptionLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
private void setupFrame()
{
this.setTitle("Data Display");
this.setSize (650, 700); //Width, Height
this.setLocation(300, 10);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(null);
}
Yes, I know I should be using a proper layout manager, but like I said i just wanted something quick and dirty. Plus, I will not be beaten by something that should be this simple. Any ideas would be appreciated.
EDIT:
As Compass and Neophyte pointed out, my order of operations was off. Flipped my method calls and all is good again in the world. Thanks for the 2nd pair of eyes.
Contrary to the original poster's strategy, or any of the answers so far, the best approach to this problem is to use layouts.
Here is an example that shows how easy it is to position fields using layouts, and to change the GUI on later updates to the specification.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class CourtDetailsGUI {
private JComponent ui = null;
static final String[] FIELD_NAMES = {
"Case #:",
"Date:",
"Report:",
"Offence:",
"Plaintiff:",
"Defendant:"
};
CourtDetailsGUI(int num) {
initUI(num);
}
public void initUI(int num) {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
ui.add(getFieldsPanel(num), BorderLayout.PAGE_START);
JTextArea ta = new JTextArea(5, 40);
JScrollPane sp = new JScrollPane(ta);
JPanel p = new JPanel(new GridLayout());
p.add(sp);
p.setBorder(new TitledBorder("Details"));
ui.add(p);
}
private JPanel getFieldsPanel(int num) {
JPanel outerPanel = new JPanel(new FlowLayout());
JPanel innerPanel = new JPanel(new GridLayout(0, 1, 15, 15));
outerPanel.add(innerPanel);
for (int ii=1; ii<num; ii++) {
JLabel l = new JLabel(FIELD_NAMES[ii]);
l.setBorder(new LineBorder(Color.BLACK));
innerPanel.add(l);
}
return outerPanel;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
for (int ii=0; ii<FIELD_NAMES.length; ii++) {
CourtDetailsGUI o = new CourtDetailsGUI(ii+1);
JFrame f = new JFrame("Data " + (ii+1));
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
}
};
SwingUtilities.invokeLater(r);
}
}
Your order of operations is incorrect.
You initially call setupObjects();
This plays your objects out onto a JFrame, which has the default LayoutManager of BorderLayout.
By using the default add(Component comp) method, with BorderLayout, you end up putting the component into null for BorderLayout, which is not supposed to be normal. Furthermore, the reason you can't see the border for this object is because the border is actually the size of the frame. If you explicitly set a region for BorderLayout, then you'll see it work, but setting to no region seems to just break BorderLayout.
Additional add calls appear to free the previous item from the BorderLayout null management, allowing the bounds to take over.
Afterwards, you call setupFrame(); which removes the layout manager, but does not refresh what is currently rendered.
This sets the layout to null, which does nothing to how the frame is displayed, but just removes the layout.
To avoid this issue, call setupFrame(); prior to setupObjects();, and then setVisible(true) can be called at the end of setupObjects();

JScrollPane isn't working in GUI

OK, I am trying to create a GUI that has a JScrollPane that, through the JTextArea, will print out an array of ints, one line at a time. I am using some methods I created for an assignment to deal with the data, and have one of them working on the data in the following example, (I can't show the methods because it's homework that isn't due yet). The methods have been tested and work fine, so no need for them in this question. So far, either the text area will show up in the GUI, but not have the scroll pane attached to it, or only the jlabel will show up with the results of the work done via the method. Can someone have a look at my code and tell me what I am doing wrong, because I have gone over this like 50 times, and cannot get the GUI to behave.
public class MyClassName extends JFrame{
private JScrollPane myScroll;
private JTextArea myTextArea;
private JLabel myMean;
private JLabel myMedian;
private JLabel myMax;
private JLabel myMin;
private JLabel mySum;
private Container content;
private Font myFont;
private SpringLayout layout;
private MyClassName() {
this(500,300,"TEST TITLE");
}
private MyClassName(int width, int height, String title)
{
this.setVisible(true);
this.setTitle(title);
this.setSize(width, height);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiComponent();
}
public void guiComponent()
{
layout = new SpringLayout();
content = this.getContentPane();
int [] test = {50,37,43,12,8,16,32,44,78,92,1,3,66,34};
myTextArea = new JTextArea();
myScroll = new JScrollPane(myTextArea);
content.add(myScroll);
myMean = new JLabel("MEAN : " + MyClassName.mean(test));
for(int count : test)
{
String z = Integer.toString(count);
myTextArea.append('\n' + z);
}
myFont = new Font("Serrif", Font.BOLD, 30);
myMean.setFont(myFont);
content.add(myScroll);
layout.putConstraint(SpringLayout.WEST, myScroll, 20, SpringLayout.WEST, content);
layout.putConstraint(SpringLayout.NORTH, myScroll, 25, SpringLayout.NORTH, content);
content.add(myMean);
layout.putConstraint(SpringLayout.WEST, myMean, 20, SpringLayout.EAST, myScroll);
layout.putConstraint(SpringLayout.NORTH, myMean, 25, SpringLayout.NORTH, content);
}
public static double mean(int[] ar) {
double x = 0;
for (int i = 0; i < ar.length; i++) {
x += ar[i];
}
return x / ar.length;
}
public static void main(String[] args) {
MyClassName test2 = new MyClassName();
}
Your problem when you need to display the components in layout, to solve your problem add those three line after initialize 'myTextArea' component:
myTextArea.setColumns(20);
myTextArea.setRows(5);
getContentPane().setLayout(layout);
you maybe need to read this link about Layout.

Categories