Swing Components taking up large amount of memory - java

I created a table out of JLabels. I made it so that when the Jpanel the labels are in are resized, the text will scale accordingly. I initially forgot to set the default close operation on the JFrame so I ended up having a ton of instances of them running in the background, until eclipse said the stack/ heap was full. I added that so now it closes correctly, however it got me wondering how much one instance of it takes up. When it launches to its default size, it only takes up about 24000K. If you move it around a lot it peeks at about 200000K and sits at 180000 K if you leave it alone. Why is my program taking up so much memory?
/**
* Class to create the specified table
* #author CGordo01
*
*/
public class WordDocumentTable extends JPanel{
Font f;
// Holds all the label, is used for resizing
ArrayList<JLabel> allLabels= new ArrayList<JLabel>();
/**
* Creates the table
*/
public WordDocumentTable(){
// Sets the layout to a gridBagLayout
this.setLayout(new GridBagLayout());
//Adds a component listener
this.addComponentListener(new ComponentAdapter() {
#Override
/**
* If the component is resized makes the text fit the dimensions
*/
public void componentResized(ComponentEvent e) {
// Boolean used to see if the text width fits the component.
Boolean fits= false;
// value used to divide the components height by.
int divider = 16;
// Makes the font size scale according to the width and height.
while(fits == false){
f = new Font("SansSerif", Font.PLAIN, e.getComponent().getHeight()/divider);
for (int i = 0; i<allLabels.size();i++){
allLabels.get(i).setFont(f);
//System.out.println(divider);
if(allLabels.get(i).getGraphics().getFontMetrics().stringWidth(allLabels.get(i).getText())>allLabels.get(i).getWidth()){
fits = false;
divider++;
break;
}
else{
fits = true;
}
}
}
}
});
makeLeftCells();
makeMidCells();
makeLongCells();
makeTopCells();
}
/**
* Creates the cells that are in between widths of the other cells
*/
private void makeMidCells() {
GridBagConstraints midCells = new GridBagConstraints();
midCells.fill= GridBagConstraints.BOTH;
midCells.weightx=1;
midCells.weighty=1;
midCells.gridwidth=4;
midCells.gridy=9;
midCells.gridx=1;
JLabel b = new JLabel();
b.setText(".Batch Total " + " 985124 " + " Patches ");
b.setName("Previous Batch Total");
b.setBackground(Color.white);
b.setBorder(new LineBorder(Color.black));
b.setOpaque(true);
b.setFont(f);
this.add(b,midCells);
midCells.gridx=5;
JLabel b2 = new JLabel();
b2.setText(".Shift Total " + " 985124 " + " Patches ");
b2.setName("Previous Shift Total");
b2.setBackground(Color.white);
b2.setBorder(new LineBorder(Color.black));
b2.setOpaque(true);
b2.setFont(f);
this.add(b2,midCells);
midCells.gridy=12;
midCells.gridx=1;
JLabel c = new JLabel();
c.setText(".Batch Total " + " 985124 " + " Patches ");
c.setName("Batch Total");
c.setBackground(Color.white);
c.setBorder(new LineBorder(Color.black));
c.setOpaque(true);
c.setFont(f);
this.add(c,midCells);
midCells.gridx=5;
JLabel c2 = new JLabel();
c2.setText(".Shift Total " + " 985124 " + " Patches ");
c2.setName("Shift Total");
c2.setBackground(Color.white);
c2.setBorder(new LineBorder(Color.black));
c2.setOpaque(true);
c2.setFont(f);
this.add(c2,midCells);
allLabels.add(b);
allLabels.add(b2);
allLabels.add(c);
allLabels.add(c2);
}
/**
* Creates the cells which span much of the grid
*/
private void makeLongCells() {
GridBagConstraints longCells = new GridBagConstraints();
longCells.fill= GridBagConstraints.BOTH;
longCells.weightx=1;
longCells.weighty=1;
longCells.gridwidth=8;
longCells.gridx=1;
longCells.gridy=7;
JLabel b = new JLabel();
b.setText("Finish the Batch");
b.setName("Previous Shift Goal");
b.setBackground(Color.white);
b.setBorder(new LineBorder(Color.black));
b.setOpaque(true);
b.setFont(f);
this.add(b,longCells);
longCells.gridy=8;
JLabel c = new JLabel();
c.setText("<html><p> blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah</p></html>");
c.setName("Previous Shift Notes");
c.setBackground(Color.white);
c.setBorder(new LineBorder(Color.black));
c.setOpaque(true);
c.setFont(f);
this.add(c,longCells);
longCells.gridy=10;
JLabel d = new JLabel();
d.setText("Shift Goal");
d.setName("Shift Goal");
d.setBackground(Color.white);
d.setBorder(new LineBorder(Color.black));
d.setOpaque(true);
d.setFont(f);
this.add(d,longCells);
longCells.gridy=11;
JLabel e = new JLabel();
e.setText("Shift Notes");
e.setName("Shift Goal");
e.setBackground(Color.white);
e.setBorder(new LineBorder(Color.black));
e.setOpaque(true);
e.setFont(f);
this.add(e,longCells);
longCells.gridy=13;
JLabel f2 = new JLabel();
f2.setText("");
f2.setName("WO Schedule Note");
f2.setBackground(Color.white);
f2.setBorder(new LineBorder(Color.black));
f2.setOpaque(true);
f2.setFont(f);
this.add(f2,longCells);
longCells.gridy=14;
JLabel g = new JLabel();
g.setText("");
g.setName("Supervisor");
g.setBackground(Color.white);
g.setBorder(new LineBorder(Color.black));
g.setOpaque(true);
g.setFont(f);
this.add(g,longCells);
allLabels.add(b);
allLabels.add(c);
allLabels.add(d);
allLabels.add(e);
allLabels.add(f2);
allLabels.add(g);
}
/**
* Creates a 8x7 grid of small cells
*/
private void makeTopCells() {
GridBagConstraints topCells = new GridBagConstraints();
topCells.fill= GridBagConstraints.BOTH;
topCells.weighty=1;
topCells.weightx=1;
for (int i = 0; i < 8; i++)
{
topCells.gridx=i+1;
for (int j = 0; j < 7; j++)
{
topCells.gridy=j;
JLabel b = new JLabel();
b.setText("" + i + j);
b.setName("" + i + j);
b.setOpaque(true);
b.setFont(f);
if(j==0){
b.setBackground(new Color(242,242,242));
}
else{
b.setBackground(Color.white);
}
b.setBorder(new LineBorder(Color.black));
allLabels.add(b);
this.add(b,topCells);
}
}
}
private void makeLeftCells() {
GridBagConstraints leftCells = new GridBagConstraints();
leftCells.fill = GridBagConstraints.BOTH;
leftCells.gridx = 0;
leftCells.gridy = 0;
leftCells.weightx=2;
leftCells.weighty=1;
JLabel titleBlock = new JLabel();
titleBlock.setOpaque(true);
titleBlock.setText("Delta Hydrogel A");
titleBlock.setForeground(Color.white);
titleBlock.setBackground(new Color(79,129,189));
titleBlock.setBorder(new LineBorder(Color.black));
titleBlock.setFont(f);
this.add(titleBlock, leftCells);
leftCells.gridy = 1;
leftCells.gridheight=3;
JLabel tallBlock1 = new JLabel();
tallBlock1.setOpaque(true);
tallBlock1.setText(".Day Shift");
tallBlock1.setForeground(Color.black);
tallBlock1.setBackground(new Color(242,242,242));
tallBlock1.setBorder(new LineBorder(Color.black));
tallBlock1.setFont(f);
this.add(tallBlock1, leftCells);
JLabel tallBlock2 = new JLabel();
tallBlock2.setOpaque(true);
tallBlock2.setText(".Night Shift");
tallBlock2.setForeground(Color.black);
tallBlock2.setBackground(new Color(242,242,242));
tallBlock2.setBorder(new LineBorder(Color.black));
tallBlock2.setFont(f);
leftCells.gridy = 4;
this.add(tallBlock2, leftCells);
JLabel shortBlock1 = new JLabel();
shortBlock1.setOpaque(true);
shortBlock1.setText(".Previous Shift Goal");
shortBlock1.setForeground(Color.black);
shortBlock1.setBackground(new Color(242,242,242));
shortBlock1.setBorder(new LineBorder(Color.black));
shortBlock1.setFont(f);
leftCells.gridy = 7;
leftCells.gridheight=1;
this.add(shortBlock1, leftCells);
JLabel shortBlockTall = new JLabel();
shortBlockTall.setOpaque(true);
shortBlockTall.setText(".Previous Shift Notes");
shortBlockTall.setForeground(Color.black);
shortBlockTall.setBackground(new Color(242,242,242));
shortBlockTall.setBorder(new LineBorder(Color.black));
shortBlockTall.setFont(f);
leftCells.gridy = 8;
leftCells.ipady=50;
this.add(shortBlockTall, leftCells);
JLabel shortBlock2 = new JLabel();
shortBlock2.setOpaque(true);
shortBlock2.setText(".Previous Shift Output");
shortBlock2.setForeground(Color.black);
shortBlock2.setBackground(new Color(242,242,242));
shortBlock2.setBorder(new LineBorder(Color.black));
shortBlock2.setFont(f);
leftCells.gridy = 9;
leftCells.ipady=0;
this.add(shortBlock2, leftCells);
JLabel shortBlock3 = new JLabel();
shortBlock3.setOpaque(true);
shortBlock3.setText(".Shift Goals");
shortBlock3.setForeground(Color.black);
shortBlock3.setBackground(new Color(184,204,228));
shortBlock3.setBorder(new LineBorder(Color.black));
shortBlock3.setFont(f);
leftCells.gridy = 10;
leftCells.ipady=0;
this.add(shortBlock3, leftCells);
JLabel shortBlock4 = new JLabel();
shortBlock4.setOpaque(true);
shortBlock4.setText(".Shift Notes");
shortBlock4.setForeground(Color.black);
shortBlock4.setBackground(new Color(184,204,228));
shortBlock4.setBorder(new LineBorder(Color.black));
shortBlock4.setFont(f);
leftCells.gridy = 11;
leftCells.ipady=0;
this.add(shortBlock4, leftCells);
JLabel shortBlock5 = new JLabel();
shortBlock5.setOpaque(true);
shortBlock5.setText(".Output");
shortBlock5.setForeground(Color.black);
shortBlock5.setBackground(new Color(184,204,228));
shortBlock5.setBorder(new LineBorder(Color.black));
shortBlock5.setFont(f);
leftCells.gridy = 12;
this.add(shortBlock5, leftCells);
JLabel shortBlock6 = new JLabel();
shortBlock6.setOpaque(true);
shortBlock6.setText(".WO Schedule Note");
shortBlock6.setForeground(Color.black);
shortBlock6.setBackground(new Color(184,204,228));
shortBlock6.setBorder(new LineBorder(Color.black));
shortBlock6 .setFont(f);
leftCells.gridy = 13;
this.add(shortBlock6, leftCells);
JLabel shortBlock7 = new JLabel();
shortBlock7.setOpaque(true);
shortBlock7.setText(".Supervisor");
shortBlock7.setForeground(Color.black);
shortBlock7.setBackground(new Color(184,204,228));
shortBlock7.setBorder(new LineBorder(Color.black));
shortBlock7.setFont(f);
leftCells.gridy = 14;
this.add(shortBlock7, leftCells);
allLabels.add(titleBlock);
allLabels.add(tallBlock1);
allLabels.add(tallBlock2);
allLabels.add(shortBlock1);
allLabels.add(shortBlockTall);
allLabels.add(shortBlock2);
allLabels.add(shortBlock3);
allLabels.add(shortBlock4);
allLabels.add(shortBlock5);
allLabels.add(shortBlock6);
allLabels.add(shortBlock7);
}
public static void main (String[] args)
{
JFrame J = new JFrame();
J.setSize(600,400);
J.setVisible(true);
WordDocumentTable wdc= new WordDocumentTable();
J.setContentPane(wdc);
J.setVisible(true);
J.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

You'll want to profile to be sure, but it may help to focus on your implementation of componentResized(). As the enclosing container is resized, the method will be invoked repeatedly. In the handler, you're continually instantiating a new Font inside a while loop. At a minimum, consider using deriveFont(). Note especially that the size parameter is a float, while your present calculation appears to use a truncating integer division.

Related

can JTextField resizable in a gridlayout?

Below is my code for testing BorderLayout and GridLayout, but I found that the JTextField in the JPanel using GridLayout is not resizable, no matter how many times I change the JTextField.setPreferredSize, it still remains the same.
public class Boderlayout implements ActionListener {
JButton bCalculate;
JLabel lPrinAmount,lInterestRate,lPayPerYear,lResult;
JTextField tPrinAmount,tInterestRate,tPayPerYear,tResult;
public static void main (String[] args) {
new Boderlayout();
}
public Boderlayout() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JPanel p2 = new JPanel();
p2.setBackground(Color.BLUE);
p2.setPreferredSize(new Dimension(600,100));
frame.add(p2,BorderLayout.SOUTH);
bCalculate = new JButton("Calculate");
bCalculate.setPreferredSize(new Dimension(550,85));
p2.add(bCalculate);
bCalculate.addActionListener(this);
JPanel p3 = new JPanel();
p3.setBackground(Color.GREEN);
p3.setLayout(new GridLayout(6,1));
p3.setPreferredSize(new Dimension(300,300));
frame.add(p3,BorderLayout.CENTER);
lPrinAmount = new JLabel("Principle Amount: ");
lPrinAmount.setPreferredSize(new Dimension(200,40));
p3.add(lPrinAmount);
tPrinAmount = new JTextField(20);
tPrinAmount.setPreferredSize(new Dimension(170,40));
p3.add(tPrinAmount);
tPrinAmount.addActionListener(this);
lInterestRate = new JLabel("Interest Rate: ");
lInterestRate.setPreferredSize(new Dimension(200,40));
p3.add(lInterestRate);
tInterestRate = new JTextField(20);
tInterestRate.setPreferredSize(new Dimension(100,40));
p3.add(tInterestRate);
tInterestRate.addActionListener(this);
lPayPerYear = new JLabel("Payment Period (Year): ");
lPayPerYear.setPreferredSize(new Dimension(200,40));
p3.add(lPayPerYear);
tPayPerYear = new JTextField(20);
tPayPerYear.setPreferredSize(new Dimension(170,40));
p3.add(tPayPerYear);
tPayPerYear.addActionListener(this);
JPanel p5 = new JPanel();
p5.setLayout(new GridLayout(2,1));
p5.setBackground(Color.WHITE);
p5.setPreferredSize(new Dimension(300,300));
frame.add(p5,BorderLayout.EAST);
lResult = new JLabel("Result");
lResult.setPreferredSize(new Dimension(170,40));
p5.add(lResult);
tResult = new JTextField(50);
tResult.setPreferredSize(new Dimension(170,200));
tResult.setEditable(false);
p5.add(tResult);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == bCalculate) {
double prinAmount = Double.parseDouble(tPrinAmount.getText());
double interestRate = Integer.parseInt(tInterestRate.getText());
double paymentYear = Integer.parseInt(tPayPerYear.getText());
double interestRatePercentage = interestRate / 100;
double loanInterest = prinAmount * interestRatePercentage;
double year = 12 * paymentYear;
double mortgageResult = (loanInterest * (Math.pow((1 + (interestRatePercentage / 12)), year)) / (Math.pow((1 + (interestRatePercentage) / 12), year) - 1)) / 12;
String stringmortgageResult = Double.toString(mortgageResult);
String newline = System.getProperty("line.separator");
String finalResult = "Principle Amount: " + tPrinAmount.getText() + newline + "Interest Rate: " + tInterestRate.getText() + "%" + newline + "Payment Period: " + tPayPerYear.getText()
+ newline + "Mortgage: " + stringmortgageResult;
tResult.setText(finalResult);
}
}
}
Refer to How to Use GridLayout.
Here is a quote from that Web page:
A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size.
In other words, GridLayout does not consider the preferred size of the components it contains.
A layout manager that does consider its contained components' preferred size is GridBagLayout.
BorderLayout only respects part of its contained components' preferred size. For the EAST component, BorderLayout uses its preferred width but not its preferred height. BorderLayout will initially use its CENTER component's preferred width and height.
This is the window I get when I run your code.
Here is your modified code using GridBagLayout instead of GridLayout.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Boderlayout implements ActionListener {
JButton bCalculate;
JLabel lPrinAmount, lInterestRate, lPayPerYear, lResult;
JTextArea tResult;
JTextField tPrinAmount, tInterestRate, tPayPerYear;
public static void main(String[] args) {
new Boderlayout();
}
public Boderlayout() {
JFrame frame = new JFrame();
JPanel p2 = new JPanel();
p2.setBackground(Color.BLUE);
p2.setPreferredSize(new Dimension(600, 100));
frame.add(p2, BorderLayout.SOUTH);
bCalculate = new JButton("Calculate");
bCalculate.setPreferredSize(new Dimension(550, 85));
p2.add(bCalculate);
bCalculate.addActionListener(this);
JPanel p3 = new JPanel();
p3.setBackground(Color.GREEN);
p3.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
p3.setPreferredSize(new Dimension(300, 300));
frame.add(p3, BorderLayout.CENTER);
lPrinAmount = new JLabel("Principle Amount: ");
lPrinAmount.setPreferredSize(new Dimension(200, 40));
gbc.gridx = 0;
gbc.gridy = 0;
p3.add(lPrinAmount, gbc);
tPrinAmount = new JTextField(20);
tPrinAmount.setPreferredSize(new Dimension(170, 40));
gbc.gridy = 1;
p3.add(tPrinAmount, gbc);
tPrinAmount.addActionListener(this);
lInterestRate = new JLabel("Interest Rate: ");
lInterestRate.setPreferredSize(new Dimension(200, 40));
gbc.gridy = 2;
p3.add(lInterestRate, gbc);
tInterestRate = new JTextField(20);
tInterestRate.setPreferredSize(new Dimension(100, 40));
gbc.gridy = 3;
p3.add(tInterestRate, gbc);
tInterestRate.addActionListener(this);
lPayPerYear = new JLabel("Payment Period (Year): ");
lPayPerYear.setPreferredSize(new Dimension(200, 40));
gbc.gridy = 4;
p3.add(lPayPerYear, gbc);
tPayPerYear = new JTextField(20);
tPayPerYear.setPreferredSize(new Dimension(170, 40));
gbc.gridy = 5;
p3.add(tPayPerYear, gbc);
tPayPerYear.addActionListener(this);
JPanel p5 = new JPanel();
p5.setLayout(new BoxLayout(p5, BoxLayout.PAGE_AXIS));
p5.setBackground(Color.WHITE);
p5.setPreferredSize(new Dimension(300, 300));
frame.add(p5, BorderLayout.EAST);
lResult = new JLabel("Result");
lResult.setPreferredSize(new Dimension(170, 40));
p5.add(lResult);
tResult = new JTextArea();
tResult.setPreferredSize(new Dimension(170, 200));
tResult.setEditable(false);
tResult.setBorder(BorderFactory.createLineBorder(Color.darkGray));
p5.add(tResult);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bCalculate) {
double prinAmount = Double.parseDouble(tPrinAmount.getText());
double interestRate = Integer.parseInt(tInterestRate.getText());
double paymentYear = Integer.parseInt(tPayPerYear.getText());
double interestRatePercentage = interestRate / 100;
double loanInterest = prinAmount * interestRatePercentage;
double year = 12 * paymentYear;
double mortgageResult = (loanInterest
* (Math.pow((1 + (interestRatePercentage / 12)), year))
/ (Math.pow((1 + (interestRatePercentage) / 12), year) - 1)) / 12;
String stringmortgageResult = Double.toString(mortgageResult);
String newline = System.getProperty("line.separator");
String finalResult = "Principle Amount: " + tPrinAmount.getText() + newline
+ "Interest Rate: " + tInterestRate.getText() + "%" + newline
+ "Payment Period: " + tPayPerYear.getText() + newline + "Mortgage: "
+ stringmortgageResult;
tResult.setText(finalResult);
}
}
}
This is the window I get when I run the above code.
Note that I changed tResult to JTextArea rather than JTextField.

Trying to change image when JButton pressed

I am trying to change the Image on the panel when the any of the JButtons are pressed. I have set up an array of images and need it to change to the next image in the array once it has been pressed. Here is my code:
public class SimpleGui implements ActionListener {
JButton button = new JButton("Very Happy");
JButton buttonTwo = new JButton("Happy");
JButton buttonThree = new JButton("Neutral");
JButton buttonFour = new JButton("Sad");
JButton buttonFive = new JButton("Very Sad");
static int[] ButtonArray = new int[5];
private static String[] imageList = { "res/snow.jpg", "res/test-gm.jpg" };
public int i = 0;
public static void main(String[] args) throws FileNotFoundException {
SimpleGui gui = new SimpleGui();
gui.go();
File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
button.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonFour.addActionListener(this);
buttonFive.addActionListener(this);
panel.add(button);
panel.add(buttonTwo);
panel.add(buttonThree);
panel.add(buttonFour);
panel.add(buttonFive);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 600);
frame.setVisible(true);
ImageIcon image = new ImageIcon(imageList[i]);
ImageIcon image1 = new ImageIcon(imageList[i + 1]);
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(label, BorderLayout.CENTER);
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
frame.add(panel2, BorderLayout.CENTER);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button) {
ButtonArray[0] = 1;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Very Happy");
}
// buttonTwo = (JButton) event.getSource();
if (event.getSource() == buttonTwo) {
ButtonArray[0] = 0;
ButtonArray[1] = 1;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Happy");
}
// buttonThree = (JButton) event.getSource();
if (event.getSource() == buttonThree) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 1;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Neutral");
}
// buttonFour = (JButton) event.getSource();
if (event.getSource() == buttonFour) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 1;
ButtonArray[4] = 0;
System.out.println("Sad");
}
// buttonFive = (JButton) event.getSource();
if (event.getSource() == buttonFive) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 1;
System.out.println("Very Sad");
}
// System.out.println(Arrays.toString(ButtonArray));
// ImageIcon image = (imageList[i]);
}
}
I don't really see what most parts of you code are supposed to do. So instead, here's a minimal example that should do what you are asking about: One label, and two buttons setting different images to that label.
ImageIcon[] images = new ImageIcon[] {
new ImageIcon("foo.gif"),
new ImageIcon("bar.gif"),
new ImageIcon("blub.gif")
};
JFrame frame = new JFrame("Test");
frame.getContentPane().setLayout(new FlowLayout());
JLabel label = new JLabel(images[0]);
frame.getContentPane().add(label);
JButton button1 = new JButton("Image 1");
button1.addActionListener(e -> label.setIcon(images[0]));
frame.getContentPane().add(button1);
JButton button2 = new JButton("Image 2");
button2.addActionListener(e -> label.setIcon(images[1]));
frame.getContentPane().add(button2);
frame.pack();
frame.setVisible(true);
Note that this is using Lambda functions (Java 8) but you can do the same with one or more "real" ActionListener classes. The important part is that you call label.setIcon(theImage); this part seems to be missing in your code.
If instead you want to cycle through a list or array of pictures, you can do like this:
AtomicInteger index = new AtomicInteger(0);
JButton buttonCycle = new JButton("Cycle");
buttonCycle.addActionListener(e -> label.setIcon(images[index.getAndIncrement() % images.length]));
frame.getContentPane().add(buttonCycle);
Here, the AtomicInteger is used so I can declare it as a local variable and use it in the lambda. You can just as well use a regular int if you make it a member variable of the surrounding class.
private int c = 0;
...
buttonCycle.addActionListener(e -> label.setIcon(images[c++ % images.length]));
The takeaway is: Create a counter variable, increment it each time the button is called and set the label's icon to the element with that count, module the size of the array.

Random Number won't appear in a JTextField

I have a problem.I created a program that will add two random numbers. I'm trying to put a Math.random() in a JTextField but it won't appear. Here's my code by the way:
public class RandomMathGame extends JFrame {
public RandomMathGame(){
super("Random Math Game");
int random2;
JButton lvl1 = new JButton("LEVEL 1");
JButton lvl2 = new JButton("LEVEL 2");
JButton lvl3 = new JButton("LEVEL 3");
JLabel line1 = new JLabel("Line 1: ");
final JTextField jtf1 = new JTextField(10);
JLabel line2 = new JLabel("Line 2: ");
final JTextField jtf2 = new JTextField(10);
JLabel result = new JLabel("Result: ");
final JTextField jtf3 = new JTextField(10);
JButton ans = new JButton("Answer");
JLabel score = new JLabel("Score: ");
JTextField jtf4 = new JTextField(3);
JLabel itm = new JLabel("Number of Items: ");
JTextField items = new JTextField(3);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(lvl1);
add(lvl2);
add(lvl3);
add(line1);
add(jtf1);
add(line2);
add(jtf2);
add(result);
add(jtf3);
add(ans);
add(score);
add(jtf4);
add(itm);
add(items);
setSize(140,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
lvl1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i, j = 10;
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
int i3 = i1 + i2;
final int random1 = (int)(Math.random() * 10 + 1);
for (i = 0; i <= j + 1; i++){
try{
jtf1.setText(String.valueOf(random1));
jtf2.setText(String.valueOf(random1));
jtf3.setText(String.valueOf(i3));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
Never mind the lvl2 and lvl3 because it's the same in lvl1. And also, I want to loop them 10 times. I'm having difficulties on putting up those codes. Can someone help me? Thanks for your help. :)
Updating text fields in a loop won't produce the animated display that you likely want; only the last update will be seen. Instead, use a javax.swing.Timer to periodically update the fields. Related examples may be found here, here and here.

Unable to getText the value of string

I'm preparing a simple system as my assignment, And I'm facing a problem where I dont know how to getText the value of String. I know how to do it with integer, but not with string.
I use Integer.parseInt(t2.getText()); in my code if i want to get an integer value
I have added my code into this.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tollRate extends JFrame implements ActionListener {
JLabel L1 = new JLabel("Please insert your origin (in capital letter)");
JTextField t1 = new JTextField(20);
JLabel L2 = new JLabel("Please insert your destination (in capital letter)");
JTextField t2 = new JTextField(20);
JLabel L3 = new JLabel("Your vehicle class");
JTextField t3 = new JTextField(1);
JButton b1 = new JButton("Calculate");
JButton b2 = new JButton("Exit");
JLabel L4 = new JLabel("Class 0 : Motorcycles, bicycles, or vehicles with "
+ "2 or less wheels" + "\nClass 1 : Vehicles wit 2 axles and 3 "
+ "or 4 wheels excluding taxis" + "\nClass 2 : Vehicles with 2 "
+ "axles and 5 or 6 wheels excluding busses" + "\n Class 3 : "
+ "Vehicles with 3 or more axles" + "\nClass 4 : Taxis"
+ "\nClass 5 : Buses");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
String i, j, k;
tollRate() {
JFrame a = new JFrame();
setTitle("Highway Toll Rates System");
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
p1.setLayout(new GridLayout(1, 2));
p1.add(L1);
p1.add(t1);
p2.setLayout(new GridLayout(1, 2));
p2.add(L2);
p2.add(t2);
p3.setLayout(new GridLayout(1, 2));
p3.add(L3);
p3.add(t3);
p4.setLayout(new FlowLayout());
p4.add(b1);
p4.add(b2);
p5.setLayout(new FlowLayout());
p5.add(L4);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a) {
Object source = a.getSource();
if (source == b2) {
this.dispose();
} else if (source == b1) {
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
}
}
public static void main(String[] args) {
tollRate a = new tollRate();
}
}
First of all String i, j, k;
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
This is wrong. You are assigning String for int. Correct them first. and if you want int values it is better to use
int i, j, k; and use trim() to avoid additional spaces.
i = Integer.parseInt(t1.getText().trim());
j = Integer.parseInt(t2.getText().trim());
k = Integer.parseInt(t3.getText().trim());
In your case use as follows
i = t1.getText();
j = t2.getText();
k = t3.getText();
to assign a string to a string all you need to do is
i = t1.getText();
j = t2.getText();
k = t3.getText();
as you have created them as strings already

Using Multiple ActionListeners in Java Swing

My problem is that at the moment I am making a GUI for a game and this GUI has many buttons. I had a problem earlier in my code where the actionListener I was using was looking for events in two buttons in rapid succession, not giving enough time for the second button to perform and action and rendering it useless. I thought I overcame that by making the second button a different actionListener in an inner class
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
and now I'm trying to do the same for a third (and eventually fourth and fifth button
P1Roll.addActionListener(new ActionListener(){
public void ActionPerformed(ActionEvent e){
but it is throwing me all kinds of errors. As I am very new to swing, I am unsure how to proceed. Any tips on this, or anything in my code at all would be very much appreciated. :)
import java.awt.Font;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.Border;
public class GUI_Windows extends JFrame implements ActionListener {
public static void main(String[] args) {
new GUI_Windows();
Random rand1, rand2, rand3, rand4;
int dice1, dice2, dice3, dice4;
int numTurns = Turns.getValue();
rand1 = new Random();
rand2 = new Random();
rand3 = new Random();
rand4 = new Random();
dice1 = rand1.nextInt(6 - 1 + 1) + 1;
dice2 = rand2.nextInt(6 - 1 + 1) + 1;
dice3 = rand3.nextInt(6 - 1 + 1) + 1;
dice4 = rand4.nextInt(6 - 1 + 1) + 1;
}
Box MegaBox, box1, box2, box3, box4, box5, box6, box7, box8, box9, box10,
box11;
Box Minibox1, Minibox2, Minibox3, Minibox4, Minibox5, MiniMegaBox;
Box MegaBox2, box12, box13, box14, box15, box16, box17, box18, box19,
box20, box21, box22, box23;
JLabel TitleLabel, InstructionLabel, Instructions, SelectMode, LoG;
Border spacer1 = BorderFactory.createEmptyBorder(5, 5, 50, 5);
Border spacer2 = BorderFactory.createEmptyBorder(5, 60, 5, 0);
Border spacer3 = BorderFactory.createEmptyBorder(5, 0, 5, 60);
Border spacer4 = BorderFactory.createEmptyBorder(0, 0, 5, 45);
Border spacer5 = BorderFactory.createEmptyBorder(0, 0, 6, 0);
Border spacer6 = BorderFactory.createEmptyBorder(5, 10, 0, 70);
Border spacer7 = BorderFactory.createEmptyBorder(0, 0, 0, 35);
JRadioButton button1, button2;
JButton button3, button4;
JButton button5, button6;
static JSlider Turns;
public GUI_Windows() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
button3.doClick();
}
});
this.setTitle("Bottom Out!");
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setResizable(false);
this.setLocation(500, 125);
this.setSize(350, 421);
MegaBox = Box.createVerticalBox();
box1 = Box.createVerticalBox();
box1.setBorder(spacer1);
box2 = Box.createVerticalBox();
box2.setBorder(spacer2);
box3 = Box.createHorizontalBox();
box4 = Box.createHorizontalBox();
box4.setBorder(spacer3);
box5 = Box.createVerticalBox();
box5.setBorder(spacer5);
box6 = Box.createHorizontalBox();
box7 = Box.createHorizontalBox();
box8 = Box.createHorizontalBox();
box9 = Box.createHorizontalBox();
box10 = Box.createHorizontalBox();
box10.setBorder(spacer7);
box11 = Box.createHorizontalBox();
box11.setBorder(spacer6);
button1 = new JRadioButton();
button1.addActionListener(this);
button2 = new JRadioButton();
button2.addActionListener(this);
TitleLabel = new JLabel("BOTTOM OUT");
TitleLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
TitleLabel.setAlignmentY(1);
InstructionLabel = new JLabel("Instructions:");
InstructionLabel.setAlignmentY(0);
InstructionLabel.setFont(new Font("Arial", Font.BOLD, 15));
Instructions = new JLabel();
Instructions.setAlignmentY(0);
Instructions
.setText("<HTML>Each game will be 3 - 20 turns, with either One Player versus the Computer, or Two Players "
+ "versus each other. Each turn, you will roll two die, and then the two die are totaled up, and "
+ "multiplied by the number of the roll it is for that turn. If this total is equal to, or higher than the "
+ "total of your last scores in that turn, than you add those points to your score for that turn. Then you "
+ "may choose to roll again, or end your turn to lock in your points for that turn.</HTML>");
SelectMode = new JLabel("Select Mode:");
SelectMode.setFont(new Font("Arial", Font.BOLD, 15));
LoG = new JLabel("Select number of Turns:");
Turns = new JSlider(2, 20, 2);
Turns.setMajorTickSpacing(2);
Turns.setMinorTickSpacing(1);
Turns.setPaintTicks(true);
Turns.setPaintLabels(true);
Turns.setSnapToTicks(true);
button3 = new JButton("Quit");
button3.setVisible(true);
button3.addActionListener(this);
button4 = new JButton("Next");
button4.setVisible(true);
button4.addActionListener(this);
button5 = new JButton("Done");
button5.setVisible(true);
// button5.addActionListener(this);
button6 = new JButton("Done");
button6.setVisible(true);
button6.addActionListener(this);
ButtonGroup group1 = new ButtonGroup();
group1.add(button1);
group1.add(button2);
ButtonGroup group2 = new ButtonGroup();
group2.add(button3);
group2.add(button4);
box6.add(TitleLabel);
box7.add(InstructionLabel);
box7.add(Box.createHorizontalGlue());
box7.add(new JLabel(" "));
box8.add(Instructions);
box3.add(SelectMode);
box3.add(Box.createHorizontalGlue());
box3.add(new JLabel(" "));
box4.add(button1);
box4.add(new JLabel(" One Player"));
box4.add(Box.createHorizontalGlue());
box4.add(button2);
box4.add(new JLabel(" Two Players"));
box9.add(LoG);
box9.setBorder(spacer4);
box10.add(Turns);
box10.add(Box.createHorizontalGlue());
box10.add(new JLabel(" "));
box11.add(button3);
box11.add(Box.createHorizontalGlue());
box11.add(button4);
box1.add(box6);
box1.add(box7);
box1.add(box8);
box5.add(box3);
box5.add(box4);
box2.add(box5);
box2.add(box9);
box2.add(box10);
box2.add(box11);
MegaBox.add(box1);
MegaBox.add(box2);
this.add(MegaBox);
this.setVisible(true);
}
int onePlayer = 0;
int isDone = 0;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button3) {
System.exit(0);
}
if (button1.isSelected()) {
onePlayer = 1;
} else if (button2.isSelected()) {
onePlayer = 2;
}
if (e.getSource() == button4 && onePlayer == 0) {
JOptionPane.showMessageDialog(button1,
"You must select the number of players!", "Try again!",
JOptionPane.WARNING_MESSAGE);
} else if (e.getSource() == button4 && onePlayer != 0) {
final JFrame pFrame = new JFrame();
pFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pFrame.setTitle("Bottom Out!");
pFrame.setResizable(false);
pFrame.setLocation(500, 125);
pFrame.setSize(250, 200);
JLabel EnterName1, EnterName2;
final JTextField NameBox1;
final JTextField NameBox2;
Border border1 = BorderFactory.createEmptyBorder(5, 25, 15, 25);
Border border2 = BorderFactory.createEmptyBorder(15, 25, 5, 25);
Border border3 = BorderFactory.createEmptyBorder(5, 0, 5, 0);
EnterName1 = new JLabel("Player 1, please enter your name:");
EnterName2 = new JLabel("Player 2, please enter your name:");
NameBox1 = new JTextField("Miller");
NameBox2 = new JTextField("Julian");
if (onePlayer == 1) {
NameBox2.setEditable(false);
NameBox2.setText("Watson");
}
Minibox1 = Box.createVerticalBox();
Minibox2 = Box.createVerticalBox();
Minibox3 = Box.createVerticalBox();
Minibox4 = Box.createHorizontalBox();
MiniMegaBox = Box.createVerticalBox();
Minibox1.add(EnterName1);
Minibox1.add(NameBox1);
Minibox1.setBorder(border1);
Minibox2.add(EnterName2);
Minibox2.add(NameBox2);
Minibox2.setBorder(border2);
Minibox3.add(Minibox1);
Minibox3.add(Minibox2);
Minibox4.add(new JLabel(" "));
Minibox4.add(Box.createHorizontalGlue());
Minibox4.add(button5);
Minibox4.add(Box.createHorizontalGlue());
Minibox4.add(new JLabel(" "));
Minibox4.setBorder(border3);
MiniMegaBox.add(Minibox3);
MiniMegaBox.add(Minibox4);
pFrame.add(MiniMegaBox);
pFrame.setVisible(true);
this.setVisible(false);
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button5) {
Border spaceBorder1 = BorderFactory.createEmptyBorder(
45, 45, 15, 45);
Border spaceBorder2 = BorderFactory.createEmptyBorder(
15, 45, 30, 45);
Border spaceBorder3 = BorderFactory.createEmptyBorder(
5, 15, 5, 0);
Border spaceBorder4 = BorderFactory.createEmptyBorder(
5, 0, 10, 10);
Border spaceborder5 = BorderFactory.createEmptyBorder(
0, 0, 15, 0);
Border spaceborder6 = BorderFactory.createEmptyBorder(
15, 0, 0, 0);
JFrame gFrame = new JFrame();
gFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gFrame.setTitle("Bottom Out!");
gFrame.setResizable(false);
gFrame.setLocation(500, 125);
gFrame.setSize(350, 421);
TitleLabel = new JLabel("BOTTOM OUT");
TitleLabel.setFont(new Font("Times New Roman",
Font.BOLD, 20));
TitleLabel.setAlignmentY(1);
box23 = Box.createHorizontalBox();
box23.add(TitleLabel);
box23.setBorder(spaceborder6);
box12 = Box.createHorizontalBox();
box12.setBorder(spaceBorder1);
box13 = Box.createHorizontalBox();
box13.setBorder(spaceBorder2);
box14 = Box.createHorizontalBox();
box14.setBorder(spaceborder5);
box15 = Box.createVerticalBox();
box16 = Box.createHorizontalBox();
box16.setBorder(spaceBorder3);
box17 = Box.createHorizontalBox();
box17.setBorder(spaceBorder3);
box18 = Box.createHorizontalBox();
box18.setBorder(spaceBorder3);
box19 = Box.createHorizontalBox();
box19.setBorder(spaceBorder3);
box20 = Box.createHorizontalBox();
box20.setBorder(spaceBorder3);
box21 = Box.createHorizontalBox();
box21.setBorder(spaceBorder4);
box22 = Box.createVerticalBox();
MegaBox2 = Box.createVerticalBox();
JLabel Player1, Player2, P1Score, P2Score;
JButton P1Roll, P2Roll, EndTurn;
JLabel TurnNum, TurnMax, TurnsRem, P1TScore, P2TScore, Winner;
Player1 = new JLabel(NameBox1.getText() + ":");
P1Score = new JLabel("Score");
P1Roll = new JButton("Roll!");
Player2 = new JLabel(NameBox2.getText() + ":");
P2Score = new JLabel("Score");
P2Roll = new JButton("Roll!");
EndTurn = new JButton("End Turn");
TurnNum = new JLabel("Turn Number: ");
TurnMax = new JLabel("Turn max: ");
TurnsRem = new JLabel("Turns left: ");
P1TScore = new JLabel("Player 1 Score: ");
P2TScore = new JLabel("Player 2 Score: ");
Winner = new JLabel("Player is Winning");
box12.add(Player1);
box12.add(Box.createHorizontalGlue());
box12.add(P1Score);
box12.add(Box.createHorizontalGlue());
box12.add(P1Roll);
box13.add(Player2);
box13.add(Box.createHorizontalGlue());
box13.add(P2Score);
box13.add(Box.createHorizontalGlue());
box13.add(P2Roll);
box14.add(new JLabel(" "));
box14.add(Box.createHorizontalGlue());
box14.add(EndTurn);
box14.add(Box.createHorizontalGlue());
box14.add(new JLabel(" "));
box15.add(box23);
box15.add(box12);
box15.add(box13);
box15.add(box14);
box16.add(TurnNum);
box16.add(Box.createHorizontalGlue());
box16.add(new JLabel(" "));
box17.add(TurnMax);
box17.add(Box.createHorizontalGlue());
box17.add(new JLabel(" "));
box18.add(TurnsRem);
box18.add(Box.createHorizontalGlue());
box18.add(new JLabel(" "));
box19.add(P1TScore);
box19.add(Box.createHorizontalGlue());
box19.add(new JLabel(" "));
box20.add(P2TScore);
box20.add(Box.createHorizontalGlue());
box20.add(new JLabel(" "));
box21.add(new JLabel(" "));
box21.add(Box.createHorizontalGlue());
box21.add(Winner);
box22.add(box16);
box22.add(box17);
box22.add(box18);
box22.add(box19);
box22.add(box20);
box22.add(box21);
MegaBox2.add(box15);
MegaBox2.add(box22);
gFrame.add(MegaBox2);
gFrame.setVisible(true);
pFrame.setVisible(false);
P1Roll.addActionListener(new ActionListener(){ public void ActionPerformed(ActionEvent e){
}
#Override
public void actionPerformed(ActionEvent e) {
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- ){
}
}});
}
}
});
}
}}
From an initial reading of the code, it appears you're creating the anonymous ActionListener with incorrect syntax.
P1Roll.addActionListener(new ActionListener(){ public void ActionPerformed(ActionEvent e){
}
#Override
public void actionPerformed(ActionEvent e) {
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- ){
}
}});
Should be
P1Roll.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e)
{
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- )
{
}
});

Categories