When Eclipse compiles this code everything works fine except the GUI freezes after the user clicks the "add" button. The answer is displayed and the work is shown. Can anyone shine some light on this problem and maybe give me some advice for the layout as well?
import Aritmathic.MathEquation;
public class GUI extends JFrame implements ActionListener{
private JTextField field1;
private JTextField field2;
private JButton add, subtract, multiply, divide;
private JLabel lanswer, label1, label2;
private String input1, input2, sanswer;
private int answer = 0;
JPanel contentPanel, answerPanel;
public GUI(){
super("Calculator");
field1 = new JTextField(null, 15);
field2 = new JTextField(null, 15);
add = new JButton("add");
subtract = new JButton("subtract");
multiply = new JButton("multiply");
divide = new JButton("divide");
lanswer = new JLabel("", SwingConstants.CENTER);
label1 = new JLabel("Value 1:");
label2 = new JLabel("Value 2:");
add.addActionListener(this);
Dimension opSize = new Dimension(110, 20);
Dimension inSize = new Dimension(200, 20);
lanswer.setPreferredSize(new Dimension(200,255));
field1.setPreferredSize(inSize);
field2.setPreferredSize(inSize);
add.setPreferredSize(opSize);
subtract.setPreferredSize(opSize);
multiply.setPreferredSize(opSize);
divide.setPreferredSize(opSize);
contentPanel = new JPanel();
contentPanel.setBackground(Color.PINK);
contentPanel.setLayout(new FlowLayout());
answerPanel = new JPanel();
answerPanel.setPreferredSize(new Dimension(230, 260));
answerPanel.setBackground(Color.WHITE);
answerPanel.setLayout(new BoxLayout(answerPanel, BoxLayout.Y_AXIS));
contentPanel.add(answerPanel);
contentPanel.add(label1); contentPanel.add(field1);
contentPanel.add(label2); contentPanel.add(field2);
contentPanel.add(add); contentPanel.add(subtract); contentPanel.add(multiply); contentPanel.add(divide);
this.setContentPane(contentPanel);
}
public void actionPerformed(ActionEvent e) {
JButton src = (JButton)e.getSource();
if(src.equals(add)){
add();
}
}
private void add(){
input1 = field1.getText();
input2 = field2.getText();
MathEquation problem = new MathEquation(input1, input2);
Dimension lineSize = new Dimension(10, 10);
JPanel line1 = new JPanel(); line1.setBackground(Color.WHITE);
JPanel line2 = new JPanel(); line2.setBackground(Color.WHITE);
JPanel line3 = new JPanel(); line3.setBackground(Color.WHITE);
JPanel line4 = new JPanel(); line4.setBackground(Color.WHITE);
JPanel line5 = new JPanel(); line4.setBackground(Color.WHITE);
JLabel[] sumLabels = problem.getSumLabels();
JLabel[] addend1Labels = problem.getAddend1Labels();
JLabel[] addend2Labels = problem.getAddend2Labels();
JLabel[] carriedLabels = problem.getCarriedLabels();
for(int i = 0; i < carriedLabels.length; i++){
line1.add(carriedLabels[i]);
}
for(int i = 0; i < addend1Labels.length; i++){
line2.add(addend1Labels[i]);
}
for(int i = 0; i < addend2Labels.length; i++){
line3.add(addend2Labels[i]);
}
String answerLine = "__";
for(int i = 0; i < sumLabels.length; i++){
answerLine += "__";
}
line4.add(new JLabel(answerLine));
for(int i = 0; i < sumLabels.length; i++){
line5.add(sumLabels[i]);
}
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(line1);
answerPanel.add(line1);
answerPanel.add(line2);
answerPanel.add(line3);
answerPanel.add(line4);
answerPanel.add(line5);
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
this.setContentPane(answerPanel);
}
}
You have to revalidate your JFrame after you change the content pane.
After
this.setContentPane(answerPanel);
add
revalidate();
Java docs about revalidate()
Your add() method should now look like:
private void add(){
input1 = field1.getText();
input2 = field2.getText();
MathEquation problem = new MathEquation(input1, input2);
Dimension lineSize = new Dimension(10, 10);
JPanel line1 = new JPanel(); line1.setBackground(Color.WHITE);
JPanel line2 = new JPanel(); line2.setBackground(Color.WHITE);
JPanel line3 = new JPanel(); line3.setBackground(Color.WHITE);
JPanel line4 = new JPanel(); line4.setBackground(Color.WHITE);
JPanel line5 = new JPanel(); line4.setBackground(Color.WHITE);
JLabel[] sumLabels = problem.getSumLabels();
JLabel[] addend1Labels = problem.getAddend1Labels();
JLabel[] addend2Labels = problem.getAddend2Labels();
JLabel[] carriedLabels = problem.getCarriedLabels();
for(int i = 0; i < carriedLabels.length; i++){
line1.add(carriedLabels[i]);
}
for(int i = 0; i < addend1Labels.length; i++){
line2.add(addend1Labels[i]);
}
for(int i = 0; i < addend2Labels.length; i++){
line3.add(addend2Labels[i]);
}
String answerLine = "__";
for(int i = 0; i < sumLabels.length; i++){
answerLine += "__";
}
line4.add(new JLabel(answerLine));
for(int i = 0; i < sumLabels.length; i++){
line5.add(sumLabels[i]);
}
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(line1);
answerPanel.add(line1);
answerPanel.add(line2);
answerPanel.add(line3);
answerPanel.add(line4);
answerPanel.add(line5);
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
this.setContentPane(answerPanel);
this.revalidate();//
}
When I tested this it works. By works I mean did not freeze and set the content pane to the answerPanel.
Related
I'm trying to create a hangman game using the Swing class and Graphics class for a APCS class I have.
I created a JButton that would take the guess typed in by the user and either add it to the "misses" or fill in all of the corresponding letters in the word. I have a separate txt file where I pick a random word from.
When I run the program, all of the components show up, but the button does not do anything. I have been working on this for a few days and don't know what I am doing wrong. I have only learnt how to use the Swing class recently, so it may be a stupid mistake for all I know. I have put all of the code down below.
public class Hangman extends JFrame {
DrawPanel panel = new DrawPanel();
Graphics g = panel.getGraphics();
JTextField guess;
JTextField outputWord;
JTextField missesString;
boolean play;
JButton button = new JButton();
String output = "";
String word;
int misses = 0;
public Hangman() {
int again = 0;
String[] dictionary = new String[1000];
In words = new In("words.txt");
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setSize(500, 500);
for (int i = 0; i < 1000; i++) {
dictionary[i] = words.readLine();
}
do {
int num = (int) (Math.random() * 1000);
word = dictionary[num].toLowerCase();
String answer = word;
word = "";
for (int i = answer.length(); i > 0; i--) {
word = word + "*";
}
int length = answer.length();
app.setLayout(new BorderLayout());
JLabel letter = new JLabel();
letter.setFont(new Font("Arial", Font.BOLD, 20));
letter.setText("Enter Your guess");
guess = new JTextField(10);
JLabel output = new JLabel();
output.setFont(new Font("Arial", Font.BOLD, 20));
output.setText("The Word is");
outputWord = new JTextField(30);
outputWord.setText(word);
outputWord.setEditable(false);
JLabel misses = new JLabel();
misses.setFont(new Font("Arial", Font.BOLD, 20));
misses.setText("Misses:");
missesString = new JTextField(52);
missesString.setEditable(false);
button = new JButton("Guess");
button.addActionListener(new ButtonListener());
JPanel panels = new JPanel();
panels.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.add(letter);
panel1.add(guess);
panel1.add(button);
JPanel panel2 = new JPanel();
panel2.add(output);
panel2.add(outputWord);
JPanel panel3 = new JPanel();
panel3.add(misses);
panel3.add(missesString);
app.add(panel1, BorderLayout.NORTH);
app.add(panel2, BorderLayout.EAST);
app.add(panel3, BorderLayout.SOUTH);
app.add(panels);
app.setVisible(true);
again = JOptionPane.showConfirmDialog(null, "Do you want to play again?");
} while (again == JOptionPane.YES_OPTION);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guess) {
output = "";
}
for (int i = 0; i <= word.length() - 1; i++) {
if (guess.getText().equalsIgnoreCase(word.substring(i, i + 1))) {
output = output.substring(0, i) + guess + output.substring(i + 1, word.length() - 1);
outputWord.setText(output);
} else {
misses++;
missesString.setText(missesString.getText() + guess + " ");
}
}
}
}
}
The components show up perfectly on the screen, it is only the button that is giving me a hard time by not working as expected.
I want to make a simple agenda but somehow when I run the compiler it doesn't load the label's text and sometimes it does. How do i fix this?
example:
(can't show pictures)
13:00pm(this is what always shows up) Course A
13:30pm Course b
and sometimes it does this:
13:00pm(always shows up) (then nothing)
13:30pm
(please keep it simple cause I am a beginner and from The Netherlands).
CODE:
(I am a beginner so don't look at that copy and paste stuff)
import javax.swing.*;
import java.awt.*;
class P{
public static void main(String [] args){
JFrame frame = new JFrame(" Agenda 10/13/2014");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(620,620);
frame.setResizable(false);
frame.setVisible(true);
JLabel labeltime1 = new JLabel("1:00 - 1:30pm: ");
JLabel labeltime2 = new JLabel("1:30 - 2:00pm: ");
JLabel labeltime3 = new JLabel("2:00 - 2:30pm: ");
JLabel labeltime4 = new JLabel("2:30 - 3:00pm: ");
JLabel labeltime5 = new JLabel("3:00 - 3:30pm: ");
labeltime1.setForeground(Color.red);
labeltime2.setForeground(Color.red);
labeltime3.setForeground(Color.red);
labeltime4.setForeground(Color.red);
labeltime5.setForeground(Color.red);
JLabel space1 = new JLabel("\n");
JLabel space2 = new JLabel("\n");
JLabel space3 = new JLabel("\n");
JLabel space4 = new JLabel("\n");
JLabel space5 = new JLabel("\n");
JPanel timeP = new JPanel();
timeP.setBackground(Color.black);
timeP.setLayout(new BoxLayout(timeP, BoxLayout.Y_AXIS));
timeP.add(space5);
timeP.add(labeltime1);
timeP.add(space1);
timeP.add(labeltime2);
timeP.add(space2);
timeP.add(labeltime3);
timeP.add(space3);
timeP.add(labeltime4);
timeP.add(space4);
timeP.add(labeltime5);
frame.getContentPane().add(BorderLayout.WEST, timeP);
JPanel courses = new JPanel();
courses.setLayout(new BoxLayout(courses, BoxLayout.Y_AXIS));
courses.setBackground(Color.black);
frame.getContentPane().add(BorderLayout.CENTER,courses);
//Enter your course
JLabel course1 = new JLabel(" Course A");
JLabel course2 = new JLabel(" Course B");
JLabel course3 = new JLabel(" Course C");
JLabel course4 = new JLabel(" Course D");
JLabel course5 = new JLabel(" Course E");
course1.setForeground(Color.yellow);
course2.setForeground(Color.yellow);
course3.setForeground(Color.yellow);
course4.setForeground(Color.yellow);
course5.setForeground(Color.yellow);
JLabel space6 = new JLabel("\n");
JLabel space7 = new JLabel("\n");
JLabel space8 = new JLabel("\n");
JLabel space9 = new JLabel("\n");
JLabel space10 = new JLabel("\n");
courses.add(space6);
courses.add(course1);
courses.add(space7);
courses.add(course2);
courses.add(space8);
courses.add(course3);
courses.add(space9);
courses.add(course4);
courses.add(space10);
courses.add(course5);
}
}
moving frame.setVisible(true); to lastline will fix your problem.you need to call setvisible after you add component .or you can call repaint(),revalidate();
import javax.swing.*;
import java.awt.*;
class P{
public static void main(String [] args){
JFrame frame = new JFrame(" Agenda 10/13/2014");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(620,620);
frame.setResizable(false);
//frame.setVisible(true);//don't call this method here
JLabel labeltime1 = new JLabel("1:00 - 1:30pm: ");
JLabel labeltime2 = new JLabel("1:30 - 2:00pm: ");
JLabel labeltime3 = new JLabel("2:00 - 2:30pm: ");
JLabel labeltime4 = new JLabel("2:30 - 3:00pm: ");
JLabel labeltime5 = new JLabel("3:00 - 3:30pm: ");
labeltime1.setForeground(Color.red);
labeltime2.setForeground(Color.red);
labeltime3.setForeground(Color.red);
labeltime4.setForeground(Color.red);
labeltime5.setForeground(Color.red);
JLabel space1 = new JLabel("\n");
JLabel space2 = new JLabel("\n");
JLabel space3 = new JLabel("\n");
JLabel space4 = new JLabel("\n");
JLabel space5 = new JLabel("\n");
JPanel timeP = new JPanel();
timeP.setBackground(Color.black);
timeP.setLayout(new BoxLayout(timeP, BoxLayout.Y_AXIS));
timeP.add(space5);
timeP.add(labeltime1);
timeP.add(space1);
timeP.add(labeltime2);
timeP.add(space2);
timeP.add(labeltime3);
timeP.add(space3);
timeP.add(labeltime4);
timeP.add(space4);
timeP.add(labeltime5);
frame.getContentPane().add(BorderLayout.WEST, timeP);
JPanel courses = new JPanel();
courses.setLayout(new BoxLayout(courses, BoxLayout.Y_AXIS));
courses.setBackground(Color.black);
frame.getContentPane().add(BorderLayout.CENTER,courses);
//Enter your course
JLabel course1 = new JLabel(" Course A");
JLabel course2 = new JLabel(" Course B");
JLabel course3 = new JLabel(" Course C");
JLabel course4 = new JLabel(" Course D");
JLabel course5 = new JLabel(" Course E");
course1.setForeground(Color.yellow);
course2.setForeground(Color.yellow);
course3.setForeground(Color.yellow);
course4.setForeground(Color.yellow);
course5.setForeground(Color.yellow);
JLabel space6 = new JLabel("\n");
JLabel space7 = new JLabel("\n");
JLabel space8 = new JLabel("\n");
JLabel space9 = new JLabel("\n");
JLabel space10 = new JLabel("\n");
courses.add(space6);
courses.add(course1);
courses.add(space7);
courses.add(course2);
courses.add(space8);
courses.add(course3);
courses.add(space9);
courses.add(course4);
courses.add(space10);
courses.add(course5);
frame.setVisible(true);//call here
}
}
What I'm trying to do with this GUI is having the person browse for a txt file, and then reading it. When the person clicks the "Read File" button, they should be prompted to choose a file, and then it will read the file and set various values. I am having a few problems with this. First, I'm using scanner to try and set the values, though I am not sure that is the best way. Second, I'm not sure if the file is even being read. I can get the browse for file dialogue to open, but then it freezes, and I have to restart eclipse. How can I use JFileChooser to read a file and set values by reading it?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Display extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 350;
private static final int FRAME_X_ORIGIN = 100;
private static final int FRAME_Y_ORIGIN = 75;
private JFrame mainFrame;
private JCheckBox avgHSCheckBox;
private JCheckBox avgTSCheckBox;
private JCheckBox homeworkSDCheckBox;
private JCheckBox testSDCheckBox;
private JRadioButton firstClass;
private JRadioButton secondClass;
private JRadioButton thirdClass;
private JRadioButton fourthClass;
private JButton readFileButton;
private JButton exitButton;
private JButton statsButton;
private JButton clearButton;
static int numberOfClasses = 3;
static int numberOfAssignments = 6;
static int numberOfStudents;
static int numberOfLabs = 15;
static int totalHomeworkScore = 0;
static int totalTestScore = 0;
static String classYear;
static String semester;
public static void main(String[] args) {
Display frame = new Display();
frame.setVisible(true);
}
public Display() {
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle("CSCE155A Course Offering Viewer");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// header
JPanel header = new JPanel();
header.setLayout(new GridLayout(2, 1));
header.setSize(350, 75);
header.setBorder(BorderFactory.createLineBorder(Color.BLACK));
header.add(new JLabel("CSCE155A Course Offering Viewer"));
header.add(new JLabel("First Last"));
add(header, BorderLayout.NORTH);
// select stats
JPanel statsSelect = new JPanel();
statsSelect.setLayout(new GridLayout(5, 1));
statsSelect.setSize(100, 100);
statsSelect.setBorder(BorderFactory.createLineBorder(Color.BLACK));
statsSelect.add(new JLabel("Please Select: "));
avgHSCheckBox = new JCheckBox("View Average Homework Score");
statsSelect.add(avgHSCheckBox);
avgTSCheckBox = new JCheckBox("View Average Test Score");
statsSelect.add(avgTSCheckBox);
homeworkSDCheckBox = new JCheckBox("View SD for Homework Scores");
statsSelect.add(homeworkSDCheckBox);
testSDCheckBox = new JCheckBox("View SD for Test Scores");
statsSelect.add(testSDCheckBox);
add(statsSelect, BorderLayout.WEST);
// Course offerings
JPanel courseOfferings = new JPanel();
courseOfferings.setLayout(new GridLayout(5, 1));
courseOfferings.setSize(100, 100);
courseOfferings.setBorder(BorderFactory.createLineBorder(Color.BLACK));
courseOfferings.add(new JLabel("Please Select: "));
firstClass = new JRadioButton(semester + classYear);
courseOfferings.add(firstClass);
secondClass = new JRadioButton(semester + classYear);
courseOfferings.add(secondClass);
thirdClass = new JRadioButton(semester + classYear);
courseOfferings.add(thirdClass);
fourthClass = new JRadioButton(semester + classYear);
courseOfferings.add(fourthClass);
add(courseOfferings, BorderLayout.EAST);
// statistics
JPanel statistics = new JPanel();
statistics.setLayout(new GridLayout(5, 1));
statistics.setSize(200, 150);
statistics.setBorder(BorderFactory.createLineBorder(Color.BLACK));
statistics.add(new JLabel("Statistics:"));
add(statistics, BorderLayout.CENTER);
// buttons
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout());
buttons.setSize(200, 150);
buttons.setBorder(BorderFactory.createLineBorder(Color.BLACK));
readFileButton = new JButton("Read File");
buttons.add(readFileButton);
exitButton = new JButton("Exit");
buttons.add(exitButton);
statsButton = new JButton("Stats");
buttons.add(statsButton);
clearButton = new JButton("Clear");
buttons.add(clearButton);
add(buttons, BorderLayout.SOUTH);
avgHSCheckBox.addActionListener(this);
avgTSCheckBox.addActionListener(this);
homeworkSDCheckBox.addActionListener(this);
testSDCheckBox.addActionListener(this);
firstClass.addActionListener(this);
secondClass.addActionListener(this);
thirdClass.addActionListener(this);
fourthClass.addActionListener(this);
readFileButton.addActionListener(this);
exitButton.addActionListener(this);
statsButton.addActionListener(this);
clearButton.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event) {
Scanner scanner = new Scanner(System.in);
CourseOffering myCourseOffering = new CourseOffering();
ComputeStatistics myComputeStatistics = new ComputeStatistics();
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
if (buttonText.equals("Read File")) {
// Create a file chooser
String filename = File.separator;
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(this);
File selFile = fc.getSelectedFile();
numberOfClasses = scanner.nextInt();
for (int i = 0; i < numberOfClasses; i++) {
myCourseOffering.setDescription(scanner.next()); // CSCE
myCourseOffering.setDescription(scanner.next()); // 155A
myCourseOffering.setDescription(scanner.next()); // -
myCourseOffering.setDescription(scanner.next()); // Semester
semester = myCourseOffering.getDescription();
myCourseOffering.setDescription(scanner.next()); // Year
classYear = myCourseOffering.getDescription();
numberOfStudents = scanner.nextInt(); // Number Of Students
myCourseOffering.students = new Student[numberOfStudents];
for (int j = 0; j < numberOfStudents; j++) {
myCourseOffering.students[j] = new Student();
totalTestScore = 0;
totalHomeworkScore = 0;
// Sets first and last name
myCourseOffering.students[j].setFirstName(scanner.next());
myCourseOffering.students[j].setLastName(scanner.next());
// call assignscores array
int[] assignScores = new int[numberOfAssignments];
for (int k = 0; k < numberOfAssignments; k++) {
assignScores[k] = scanner.nextInt();
totalHomeworkScore += assignScores[k];
}
myCourseOffering.students[j]
.setAssignmentScores(assignScores);
int[] labScores = new int[numberOfLabs];
for (int l = 0; l < numberOfLabs; l++) {
labScores[l] = scanner.nextInt();
totalHomeworkScore += labScores[l];
}
myCourseOffering.students[j].setLabScores(labScores);
myCourseOffering.students[j].setMidTerm1(scanner.nextInt());
totalTestScore += myCourseOffering.students[j]
.getMidterm1();
myCourseOffering.students[j].setMidterm2(scanner.nextInt());
totalTestScore += myCourseOffering.students[j]
.getMidterm2();
myCourseOffering.students[j]
.setFinalExam(scanner.nextInt());
totalTestScore += myCourseOffering.students[j]
.getFinalExam();
myCourseOffering.students[j]
.setQuizScore(scanner.nextInt());
totalTestScore += myCourseOffering.students[j]
.getQuizScore();
myCourseOffering.students[j].setAttendanceScore(scanner
.nextInt());
totalHomeworkScore += myCourseOffering.students[j]
.getAttendanceScore();
myCourseOffering.students[j].setPatScore(scanner.nextInt());
totalTestScore += myCourseOffering.students[j]
.getPatScore();
myCourseOffering.students[j].setZyanteScore(scanner
.nextInt());
totalTestScore += myCourseOffering.students[j]
.getZyanteScore();
myCourseOffering.students[j]
.setTotalHomeworkScore(totalHomeworkScore);
myCourseOffering.students[j]
.setTotalTestScore(totalTestScore);
}
}
}
}
}
The scanner you created uses System.in. You need to create a scanner that operates on the file: Scanner scanner = new Scanner(selFile);.
Also, just FYI, that is an atrocious way to do ActionListeners. I know that tons of examples do that, including the ones from Sun/Oracle, but it's just awful. Attach separate listeners to each button so you're not creating one giant listener that's responsible for everything.
I'm using a vector to store the information displayed in the JList and I want to use the index of the selected index to copy the data of that row into the JTextField and JTextArea. I am having some issues where the selected item isn't be shown in the JTextField/Area but instead showing the data of a previous selected index. Every second index has an issue of showing the wrong data, 2, 4, 6, 8, 10 and then 11. Each of them will only show the right data if you select first when the program has just been executed. The print lines that I have added to the ListSelectionEvent listener shows the correct data of the selected index but it doesn't correctly copy it into the JTextArea/JTextField.
Selected right after the program was executed.
I selected a few other indices then tried to select it again
code:
public class EditFlashcardGui implements ListSelectionListener {
private JFrame frame;
private JPanel listPanel;
private Vector<Vector> flashcardMasterVector = new Vector<Vector>();
private JList list;
private JPanel tablePanel, dataPanel, textFieldPanel;
private JButton submitButton, cancelButton;
private JTextField frontTextField;
private JTextArea reverseTextArea;
private GridBagLayout gridBagLayout;
private GridBagConstraints constraints;
private JLabel frontTextLabel, reverseTextLabel;
Vector<Vector> masterVector = new Vector<Vector>();
public EditFlashcardGui() {
frame = new JFrame("Edit / Delete Flashcards");
frame.setSize(500, 200);
Container con = frame.getContentPane();
con.setLayout(new BorderLayout());
listPanel = new JPanel(new BorderLayout());
Vector<String> columnNames = new Vector<String>();
columnNames.add("id");
columnNames.add("front text");
columnNames.add("reverse text");
list = new JList(populateList());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(this);
Font font1 = new Font("SansSerif", Font.BOLD, 20);
list.setFont(font1);
tablePanel = new JPanel();
tablePanel.add(list);
JScrollPane scrollPane = new JScrollPane(list);
con.add(scrollPane, BorderLayout.NORTH);
// south panel
gridBagLayout = new GridBagLayout();
constraints = new GridBagConstraints();
textFieldPanel = new JPanel(gridBagLayout);
// cancelButton = new JButton("Cancel");
// dataPanel.add(cancelButton, BorderLayout.SOUTH);
frontTextLabel = new JLabel("Front Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 0;
gridBagLayout.setConstraints(frontTextLabel, constraints);
textFieldPanel.add(frontTextLabel);
frontTextField = new JTextField();
frontTextField.setColumns(30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 1;
gridBagLayout.setConstraints(frontTextField, constraints);
textFieldPanel.add(frontTextField);
reverseTextLabel = new JLabel("Reverse Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 2;
gridBagLayout.setConstraints(reverseTextLabel, constraints);
textFieldPanel.add(reverseTextLabel);
reverseTextArea = new JTextArea(3, 30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 3;
gridBagLayout.setConstraints(reverseTextArea, constraints);
textFieldPanel.add(reverseTextArea);
submitButton = new JButton("Submit");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 4;
gridBagLayout.setConstraints(submitButton, constraints);
textFieldPanel.add(submitButton);
con.add(textFieldPanel, BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public Vector<Vector> populateList() {
//flashcardMasterVector = flashcardDB.getList();
//Vector<String> flashcardVector = new Vector<String>();
Integer temp = 0;
for(int i = 0; i <= 20; i++) {
Vector<String> flashcardVector = new Vector<String>();
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
masterVector.add(i, flashcardVector);
temp++;
}
return masterVector;
}
public static void main(String[] args) {
EditFlashcardGui gui = new EditFlashcardGui();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (! e.getValueIsAdjusting())
{
System.out.print("id : " );
System.out.println(masterVector.get(list.getSelectedIndex()).get(0));
System.out.print("front text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(1));
frontTextField.setText(masterVector.get(e.getFirstIndex())
.get(1).toString());
System.out.print("reverse text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(2));
reverseTextArea.setText(masterVector.get(e.getFirstIndex())
.get(2).toString());
}
}
}
have to read Oracles tutorial about How to Use JList
you can't put Vector<Vector> to the JList directly,
put value and to use XxxListModel only, but in this case have to create crazy workaround for AbstractListModel, use simple array instead
JList is based on one dimensional array have to use Vector<Object (or String or Double...)>
don't complicate simple things put this array to the JTable (to the XxxTableModel), remove all synchronizations columns, remove JTableHeader if required, then output to the GUI looks like as JList
JTable.removeColumn remove only column from view, all data are still presented and stored into XxxTableModel without any changes
then selected (have to test for -1 == none of row is selected) row (have to convertViewToModel in the case that JTable is sorted or filtered) returns all required data from XxxTableModel
Use list.getSelectedIndex() instead of e.getFirstIndex() method.
Code :
frontTextField.setText( masterVector.get(list.getSelectedIndex() ).get(1).toString() );
reverseTextArea.setText(masterVector.get( list.getSelectedIndex()).get(2).toString() );
Clean Code:
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
Vector masterVec = masterVector.get( list.getSelectedIndex() );
System.out.print("id : ");
System.out.println(masterVec.get(0));
System.out.print("front text : ");
System.out.println(masterVec.get(1));
System.out.print("reverse text : ");
System.out.println(masterVec.get(2));
frontTextField.setText(masterVec.get(1).toString());
reverseTextArea.setText(masterVec.get(2).toString());;
}
}
I was wondering how I would be able to account for spaces in my Calculator program. Right now it is set up to only work if there is a space after every value. I want it to be able to work if there is multiple spaces as well. I tried doing something (in my action performed, under the '=' sign test), but it didn't really work. So wanted to know how I could make it account for multiple spaces (like if there are more than one space before the next value, then it should recognize that that is the case, and delete the extra spaces). Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
int counter = 0;
if (text.equals("="))
{
doMath math = new doMath();
for(int i = 0; i <b.length(); i++)
{
String c = b.substring(i,(i+1));
String d = b.substring((i+1),(i+2));
String temp = "";
if( c.equals(" ") && c.equals(d))
{
temp = b.substring(0,i)+(b.substring(i+1));
b = temp;
}
}
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
counter ++;
if(counter <2)
{
b+= " ";
display.setText(b);
}
else
{
b+="";
display.setText(b);
}
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
counter = 0;
}
}
This method requires knowledge of regular expressions. For each string, simply replace any instance of multiple consecutive spaces with a single space. In other words, using regular expressions, you would replace "\\s+", which means "more than one space," with " ", which is just the space character.
Example:
String c = ...
c = c.replaceAll("\\s+", " ");
String str = "your string";
Pattern _pattern = Pattern.compile("\\s+");
Matcher matcher = _pattern.matcher(str);
str = matcher.replaceAll(" ");
Instead of using a substring, use a Scanner which takes a String as a parameter.
Or you can disable the "Space" button after it's pressed, enabling it back, when a different button is pressed.
If b is not empty you could try looking at the previous character using charAt and if it is a space do nothing.