JRadioButtons before every line - java

I have this program that reads questions with multiple choice answers from a text file and then displays a random set of them in a JOptionPane (very question in a new Pane). In my text file the questions and the 4 options of answers are all in one line and then I divide them into new lines. Now I want to try to add JRadioButtons before every single answer. Is there someone who can help me. Thank you very much in advance. Here is my code:
Random random = new Random();
for (int i = 0; i < newRanQues; i++) {
int randIndex = random.nextInt(32) + 0;
String randomQuestion = questions.get(randIndex);
randomQuestions.add(randomQuestion);
String different = randomQuestion.replaceAll(";", "\n");
{
JOptionPane.showMessageDialog(null, different, "Question", JOptionPane.INFORMATION_MESSAGE);
JRadioButton answerA = new JRadioButton("A) " + answer[0]);
JRadioButton answerB = new JRadioButton("B) " + answer[1]);
JRadioButton answerC = new JRadioButton("C) " + answer[2]);
JRadioButton answerD = new JRadioButton("D) " + answer[3]);
ButtonGroup group = new ButtonGroup();
group.add(optionA);
group.add(optionB);
group.add(optionC);
group.add(optionD);
return;
}

This should do it:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class RadioButtonExample {
public static void main(String[] args) {
init();
}
private static void init() {
// create the jframe
JFrame jframe = new JFrame("Question");
// create the answers
String[] answer = { "red", "green", "yellow", "blue, no, red, no... arrrrrg" };
// create the radio buttons
JRadioButton answerA = new JRadioButton("A) " + answer[0]);
JRadioButton answerB = new JRadioButton("B) " + answer[1]);
JRadioButton answerC = new JRadioButton("C) " + answer[2]);
JRadioButton answerD = new JRadioButton("D) " + answer[3]);
// create the button group
ButtonGroup group = new ButtonGroup();
group.add(answerA);
group.add(answerB);
group.add(answerC);
group.add(answerD);
// add the question to the jframe
jframe.add(new JLabel("What is your favorite colour?"), BorderLayout.NORTH);
// create gridbag layout and constraints
GridBagLayout gbl = new GridBagLayout();
// create the panel using the gbl
JPanel pan = new JPanel(gbl);
// create the constraints
GridBagConstraints cons = new GridBagConstraints();
cons.gridwidth = 1;
cons.fill = GridBagConstraints.HORIZONTAL;
// answer 1
cons.gridx = 0;
cons.gridy = 1;
pan.add(answerA, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 2;
pan.add(answerB, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 3;
pan.add(answerC, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 4;
pan.add(answerD, cons);
// add the panel to the jframe
jframe.add(pan, BorderLayout.CENTER);
// show the jframe
jframe.setSize(400, 400);
jframe.setVisible(true);
}
}

Related

Java AWT controls issue

I'd like to create a calculator using Java AWT library, however I'm having problems putting a label and a textfield on the same row. Also, everything is mixing up. When I run the program, at first it shows 2 labels and 2 textfields on the same row, but if I resize it, the labels, buttons & textfields are one on top of another. Could you please help me?
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Calculator extends Frame {
public static void main(String[] args) {
Frame frame= new Frame();
frame.setTitle("Mini Calculator App");
frame.setVisible(true);
frame.setSize(300,300);
LayoutManager gridBagLayout = new GridBagLayout();
frame.setLayout(gridBagLayout);
Label firstNumber = new Label("Add a number");
frame.add(firstNumber);
TextField numar1 = new TextField();
frame.add(numar1);
Label secondNumber = new Label("Add another number");
frame.add(secondNumber);
TextField numar2 = new TextField();
frame.add(numar2);
Choice operatie = new Choice();
operatie.add("+"); operatie.add("-");
operatie.add("*"); operatie.add("/");
frame.add(operatie);
Button calcul = new Button("Calculate");
frame.add(calcul);
Label result = new Label("Result is");
frame.add(result);
GridBagConstraints afisare;
afisare = new GridBagConstraints();
afisare.gridx = 0;
afisare.gridy = 0;
frame.add(firstNumber, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 0;
afisare.gridy = 1;
afisare.gridwidth = 10;
afisare.gridheight = 10;
frame.add(numar1, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 1;
afisare.gridy = 0;
frame.add(secondNumber, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 1;
afisare.gridy = 1;
frame.add(numar2, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 2;
afisare.gridy = 1;
frame.add(operatie, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 4;
afisare.gridy = 0;
frame.add(result, afisare);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
enter image description here
enter image description here

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.

ScrollPane adding to grid layout

in my code I am calling a few items(my buttons with their names leading to different project. The names and everything are taken from a database)
I want a J ScrollPane to surround my buttons, what can I do? I just want the buttons to be called inside the scroll pane. Here is my code
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AdminClass implements ActionListener {
ProjectButton[] buttons = new ProjectButton[35];
//Creating data field for unique Ids in the form of array list
ArrayList<Integer> uniqueIDList = new ArrayList<Integer>();
String[] projectNames;
int[] uniqueIds;
Connection conn1 = null;
Statement stmt1 = null;
JFrame frame = new JFrame("Admin Panel");
private JPanel panel = new JPanel();
JButton btnNewButton = new JButton("Add New Project");
public AdminClass() {
panel.setLayout(new GridLayout(10, 1));
panel.add(new JLabel("Welcome to Admin Panel"));
btnNewButton.addActionListener(this);
panel.add(btnNewButton);
panel.add(new JLabel("Existing Projects"));
conn1 = sqliteConnection.dbConnector();
try{
Class.forName("org.sqlite.JDBC");
conn1.setAutoCommit(false);
stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery( "SELECT * FROM Project;" );
List<String> projectNameList = new ArrayList<String>();
while ( rs1.next() ){
int id = rs1.getInt("uniqueid");
String projectName = rs1.getString("name");
projectNameList.add(projectName);
uniqueIDList.add(id);
}
// Converting array list to array
projectNames = new String[projectNameList.size()];
projectNameList.toArray(projectNames);
uniqueIds = convertIntegers(uniqueIDList);
rs1.close();
stmt1.close();
conn1.close();
}
catch ( Exception e1 ) {
JOptionPane.showMessageDialog(null, e1);
}
// Adding buttons to the project
try{
for (int i = 0; i < projectNames.length; i++){
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panel.add(buttons[i]);
buttons[i].addActionListener(this);
}
}
catch (Exception e2){
JOptionPane.showMessageDialog(null, e2);
}
frame.add(panel);
frame.setVisible(true);
frame.setSize(500, 500);
}
public void actionPerformed(ActionEvent e) {
for (int j = 0; j < buttons.length; j ++){
if (e.getSource() == buttons[j]){
AdminStatus sc = new AdminStatus(buttons[j].getId());
frame.dispose();
}
}
if (e.getSource() == btnNewButton){
frame.dispose();
WindowProjectAdmin wpa = new WindowProjectAdmin();
}
}
//Method to convert integar array list to integar array
public int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
}
This may seem very normal but it's really not, for some reason they are not visible or are not called inside a scroller. Please edit my code maybe?
Start by adding the buttons to their own container, this way you can control the layout of the buttons separately from the rest of the UI
JPanel panelFullOfButtons = new JPanel();
try {
for (int i = 0; i < projectNames.length; i++) {
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panelFullOfButtons.add(buttons[i]);
buttons[i].addActionListener(this);
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
Then add the "main" panel to the NORTH position of the frame and the "buttons" panel to the CENTER
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(panelFullOfButtons), BorderLayout.CENTER);
Mind you, in this case, I'd be very tempted to use something like a JList instead. See How to Use Lists for more details
I have done the same, can you tell me what's wrong?
// Problem #1...
JScrollPane pane = new JScrollPane();
pane.add(buttonPanel);
//...
// Problem #2...
panel.add(pane);
frame.add(panel);
These are competing with each other, moving the content around and overlapping with existing content...
public AdminClass() {
panel.setLayout(new GridLayout(3, 1));
panel.add(new JLabel("Welcome to Admin Panel"));
btnNewButton.addActionListener(this);
panel.add(btnNewButton);
panel.add(new JLabel("Existing Projects"));
List<String> projectNameList = new ArrayList<String>();
for (int index = 0; index < 1000; index++) {
projectNameList.add("Project " + index);
}
projectNames = projectNameList.toArray(new String[0]);
// Adding buttons to the project
buttons = new JButton[projectNameList.size()];
try {
for (int i = 0; i < projectNames.length; i++) {
buttons[i] = new JButton(projectNames[i]);
btnPnl1.add(buttons[i]);
buttons[i].addActionListener(this);
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(btnPnl1), BorderLayout.CENTER);
frame.setVisible(true);
frame.setSize(500, 500);
}
In this case I'd prefer to use either a JList to show the projects or a WrapLayout for laying out the buttons
Its useless to create a GridLayout like this: panel.setLayout(new GridLayout(10, 1));. If you declare the rows as a non zero value, the column count will be ignored. When you declare the maximum number of rows as ten, you force the eleventh component to be added in a second column (then a third, a forth and so on). Use panel.setLayout(new GridLayout(0, 1)); instead to force the only one column and frame.add(new JScrollPane(panel)); to create the ScrollPane.
But note that GridLayout will try to shrink your components the maximum as possible to fit the container size before scrolling is enabled.
I just want the button part to be inside J Scroll Pane
If you just want the JButton's (those added within the loop):
Create a new JPanel that you add the buttons to
Add (1) to a JScrollPane
Add (2) to panel
For example:
JPanel buttonPanel = new JPanel(new FlowLayout());
for (int i = 0; i < projectNames.length; i++){
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panel.add(buttons[i]);
buttonPanel[i].addActionListener(this);
}
JScrollPane scroller = new JScrollPane(buttonPanel);
panel.add(scroller);
You might also consider using a different Component that doesn't require a JScrollPane, of course depending upon your needs - for instance a JComboBox.

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.

Why does this code work in Vista but not 7?

For some reason every time I have someone run this program in Vista it works flawlessly but as soon as I move it over to a Windows 7 PC it stops in the middle of the ActionListener's Action Performed Method meaning I can click my choices but it will never say size selected.
Is there any way to fix this?
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SizerFrame extends JFrame {
ButtonGroup buttons = new ButtonGroup();
JTextField width = new JTextField(2);
JTextField height = new JTextField(2);
double inchesPerTimeline = 2.1;
public SizerFrame()
{
super("Timeline Application");
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(screen.width/2-125,screen.height/2-90,250,180);
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
int[] gridX = new int[]{0,0,0,0};
int[] gridY = new int[]{0,1,2,3};
int[] gridW = new int[]{1,1,2,5};
String[] titles = new String[]{"6\"","9\"","10\"","Custom"};
String[] actions = new String[]{"6","9","10","C"};
for (int a = 0; a < 4; a++)
{
JRadioButton current = new JRadioButton(titles[a]);
current.setActionCommand(actions[a]);
c.gridx = gridX[a];
c.gridy = gridY[a];
c.gridwidth = gridW[a];
buttons.add(current);
getContentPane().add(current,c);
}
c.gridwidth = 1;
String[] title = new String[]{" ","Width","Height"};
gridX = new int[]{9,10,12};
for (int a = 0; a< 3; a++)
{
c.gridx = gridX[a];
getContentPane().add(new JLabel(title[a]),c);
}
c.gridx = 11;
getContentPane().add(width,c);
c.gridx = 13;
getContentPane().add(height,c);
c.gridx = 11;
c.gridy = 0;
c.gridwidth = 2;
JButton button = new JButton("Done");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel x = buttons.getSelection();
String size = "XXX";
System.out.println("Getting screen resolution");
int screenRes = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println("Successfully got screen resolution");
if (x!=null)
size = x.getActionCommand();
try{
TimeTable.width = new Integer(size)*screenRes;
TimeTable.height = (int)((TimeTable.titleCount+1)*inchesPerTimeline*screenRes);
}
catch(NumberFormatException ex)
{
try{
TimeTable.width = (int)(new Double(width.getText().trim())*screenRes);
TimeTable.height = (int)(new Double(height.getText().trim())*screenRes);
}
catch (NumberFormatException except)
{
return;
}
}
TimeTable.ready = true;
System.out.println("Size selected");
dispose();
}
});
getContentPane().add(button,c);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent winEvt){
System.exit(0);
}
});
setVisible(true);
}
}
Concise explanation :
I have a macro that runs out of Excel in Windows Vista and I tried to distribute it to a Computer running Windows 7. Upon execution the code failed to continue executing after this point i.e. it never printed out the words "Size selected". The rest of the program brings in a csv file from a C:\Users\?\AppData\TimeLineMacroProgram folder and later creates an image in the same directory. But this is the portion of the code that is currently broken. Whenever the GUI pops up I select the option for 9" and click done which should pass in 9 as a parameter and then print out "Size Selected" but it doesn't it only disposes the window. Please help.
Longshot guess:
There is an exit from your action listener if width and height text fields don't have content: you return after two NumberFormatExceptions. This would prevent "Size selected" from being displayed, and not dispose the frame. If you got the output "Successfully got screen resolution" and then it appeared to stop working, this could possibly be why. But if you experience that, and then click something else and then Done, it would print size selected.

Categories