So I'm trying to create a simple test program where the user can enter something into a JTextField, click the "add" JButton, and a JTextArea will add the users string to the the JTextArea (continuously appending with new line).
I added the actionListener for the button and have a stateChanged and an update method, but nothing happens when I click the add button. No errors either. Could someone please point me in the right direction?
Here's my code:
MVCTester (main)
public class MVCTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
MVCController myMVC = new MVCController();
MVCViews myViews = new MVCViews();
myMVC.attach(myViews);
}
}
MVCController
import java.util.ArrayList;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCController {
MVCModel model;
ArrayList<ChangeListener> listeners;
public MVCController(){
model = new MVCModel();
listeners = new ArrayList<ChangeListener>();
}
public void update(String input){
model.setInputs(input);
for (ChangeListener l : listeners)
{
l.stateChanged(new ChangeEvent(this));
}
}
public void attach(ChangeListener c)
{
listeners.add(c);
}
}
MVCModel
import java.util.ArrayList;
public class MVCModel {
private ArrayList<String> inputs;
MVCModel(){
inputs = new ArrayList<String>();
}
public ArrayList<String> getInputs(){
return inputs;
}
public void setInputs(String input){
inputs.add(input);
}
}
MVCViews
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCViews implements ChangeListener {
private JTextField input;
private JTextArea echo;
private ArrayList<String> toPrint = new ArrayList<String>();
MVCController controller;
MVCViews(){
controller = new MVCController();
JPanel myPanel = new JPanel();
JButton addButton = new JButton("add");
echo = new JTextArea(10,20);
echo.append("Hello there! \n");
echo.append("Type something below!\n");
myPanel.setLayout(new BorderLayout());
myPanel.add(addButton, BorderLayout.NORTH);
input = new JTextField();
final JFrame frame = new JFrame();
frame.add(myPanel, BorderLayout.NORTH);
frame.add(echo, BorderLayout.CENTER);
frame.add(input, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
controller.update(input.getText());
}
});
frame.pack();
frame.setVisible(true);
}
#Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
toPrint = controller.model.getInputs();
for(String s: toPrint){
echo.append(s + "\n");
}
}
}
This is my first time trying to follow MVC format, so there might be issues with the model itself as well. Feel free to point them out. Thank you for your help!
The controller within the GUI is not the same controller that is created in main. Note how many times you call new MVCController() in your code above -- it's twice. Each time you do this, you're creating a new and distinct controller -- not good. Use only one. You've got to pass the one controller into the view. You can figure out how to do this. (hint, a setter or constructor parameter would work).
hint 2: this could work: MVCViews myViews = new MVCViews(myMVC);
one solution:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCTester {
public static void main(String[] args) {
MVCController myMVC = new MVCController();
MVCViews myViews = new MVCViews(myMVC);
myMVC.attach(myViews);
// myViews.setController(myMVC); // or this could do it
}
}
class MVCController {
MVCModel model;
ArrayList<ChangeListener> listeners;
public MVCController() {
model = new MVCModel();
listeners = new ArrayList<ChangeListener>();
}
public void update(String input) {
model.setInputs(input);
for (ChangeListener l : listeners) {
l.stateChanged(new ChangeEvent(this));
}
}
public void attach(ChangeListener c) {
listeners.add(c);
}
}
class MVCModel {
private ArrayList<String> inputs;
MVCModel() {
inputs = new ArrayList<String>();
}
public ArrayList<String> getInputs() {
return inputs;
}
public void setInputs(String input) {
inputs.add(input);
}
}
class MVCViews implements ChangeListener {
private JTextField input;
private JTextArea echo;
private ArrayList<String> toPrint = new ArrayList<String>();
MVCController controller;
MVCViews(final MVCController controller) {
// !! controller = new MVCController();
this.controller = controller;
JPanel myPanel = new JPanel();
JButton addButton = new JButton("add");
echo = new JTextArea(10, 20);
echo.append("Hello there! \n");
echo.append("Type something below!\n");
myPanel.setLayout(new BorderLayout());
myPanel.add(addButton, BorderLayout.NORTH);
input = new JTextField();
final JFrame frame = new JFrame();
frame.add(myPanel, BorderLayout.NORTH);
frame.add(echo, BorderLayout.CENTER);
frame.add(input, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (controller != null) {
controller.update(input.getText());
}
}
});
frame.pack();
frame.setVisible(true);
}
public void setController(MVCController controller) {
this.controller = controller;
}
#Override
public void stateChanged(ChangeEvent e) {
if (controller != null) {
toPrint = controller.model.getInputs();
for (String s : toPrint) {
echo.append(s + "\n");
}
}
}
}
Related
i have a multi class program, with each class having its own GUI, my task is to capture details from a class called dataInput and the data must be captured into variables of a class called studentRecords, i must capture about 10 records comprised of name, surname, student number and tests from 1-4, i have a class called RecordsMenu which have Buttons that call the different classes, for example, when i click dataInput button it calls the DataInput class, in the datainput class i must capture data into records class, then i must go back to recordsMenu screen, from there! when i click for example, the display Button , i must be able to see the data i captured, the problem i have is that, when ever i go back to the main screen , all the data i captured get lost and it print nulls when i test whether it captured or not, i will appreciate any kind of help, my code is below.this must be done with out using files, thank you
[here is the picture of the main screen of my application][1]
enter code here
[1]: https://i.stack.imgur.com/I6JyI.jpg
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
public class InputDetails extends JPanel
{
JLabel title,name,surname,studentno,tests,t1,t2,t3,t4;
JTextField nametxf,surnametxf,studentnotxf,t1txf,t2txf,t3txf,t4txf;
JButton submit,home;
JPanel buttons, mainPanel, labels;
public InputDetails()
{
// title
title = new JLabel("Records Menu",SwingConstants.CENTER);
title.setForeground(Color.BLUE);
Font newLabelFont =new Font("Serif",Font.BOLD,70);
title.setFont(newLabelFont);
// buttons and actions
submit = new JButton("Submit");
submit.addActionListener(new Handler());
home = new JButton("Home");
home.addActionListener(new Handler());
//labels
name = new JLabel("Name");
surname = new JLabel("Surname");
studentno= new JLabel("Student Number");
tests = new JLabel("Tests");
// tests
t1 = new JLabel("Test 1");
t2 = new JLabel("Test 2");
t3 = new JLabel("Test 3");
t4 = new JLabel("Test 4");
//textfields
nametxf = new JTextField(10);
surnametxf = new JTextField(10);
studentnotxf = new JTextField(10);
t1txf= new JTextField(10);
t2txf= new JTextField(10);
t3txf= new JTextField(10);
t4txf= new JTextField(10);
buttons = new JPanel(new GridLayout(1,2,5,5));
buttons.add(submit);
buttons.add(home);
// fields
labels = new JPanel(new GridLayout(7,1,5,5));
labels.add(name);
labels.add(nametxf);
labels.add(surname);
labels.add(surnametxf);
labels.add(studentno);
labels.add(studentnotxf);
labels.add(t1);
labels.add(t1txf);
labels.add(t2);
labels.add(t2txf);
labels.add(t3);
labels.add(t3txf);
labels.add(t4);
labels.add(t4txf);
//
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.add(title,BorderLayout.NORTH);
mainPanel.add(labels,BorderLayout.WEST);
mainPanel.add( buttons,BorderLayout.SOUTH);
add(mainPanel);
}
class Handler implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
if(click.getSource()==home)
{
// back to main view
mainPanel.setVisible(false);
add(new RecordsMenu());
}
else if(click.getSource()==submit)
{
String name,surname,studentno;
int test1,test2,test3,test4;
name = nametxf.getText();
surname = surnametxf.getText();
studentno=studentnotxf.getText();
test1 =Integer.parseInt(t1txf.getText());
test2 = Integer.parseInt(t2txf.getText());
test3 = Integer.parseInt(t3txf.getText());
test4 = Integer.parseInt(t4txf.getText());
StudentRecords records = new StudentRecords(name,surname,studentno,test1,test2,test3,test4);
}
}
}
}
import java.io.*;
import javax.swing.JOptionPane;
public class StudentRecords {
String name , Surname, studentno;
int test1,test2,test3,test4;
FileWriter records;
PrintWriter out;
public StudentRecords(String Name, String Surname,String StudentNo,int t1, int t2, int t3, int t4)
{
setName(Name);
setSurname(Surname);
setStudentno(StudentNo);
setTest1(t1);
setTest2(t2);
setTest3(t3);
setTest4(t4);
// saveRecords();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getStudentno() {
return studentno;
}
public void setStudentno(String studentno) {
this.studentno = studentno;
}
public int getTest1() {
return test1;
}
public void setTest1(int test1) {
this.test1 = test1;
}
public int getTest2() {
return test2;
}
public void setTest2(int test2) {
this.test2 = test2;
}
public int getTest3() {
return test3;
}
public void setTest3(int test3) {
this.test3 = test3;
}
public int getTest4() {
return test4;
}
public void setTest4(int test4) {
this.test4 = test4;
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.*;
public class ReadFile extends JPanel{
private JButton read,back;
private JTextArea desplay;
private JLabel title;
private JPanel mainpanel, buttons;
String record,student1,student2,student3,student4,student5,student6,student7,student8,student9,student10;
public ReadFile()
{
// title
title = new JLabel("Read File Contents",SwingConstants.CENTER);
Font newLabelFont =new Font("Serif",Font.BOLD,30);
title.setFont(newLabelFont);
// textarea
desplay = new JTextArea();
// buttons
read = new JButton("Open");
read.addActionListener(new Handler());
back = new JButton("back to main");
back.addActionListener(new Handler());
// panel
buttons = new JPanel(new GridLayout(1,2,5,5));
buttons.add(read);
buttons.add(back);
mainpanel = new JPanel(new BorderLayout(5,5));
mainpanel.add(title,BorderLayout.NORTH);
mainpanel.add(desplay,BorderLayout.CENTER);
mainpanel.add(buttons,BorderLayout.SOUTH);
add(mainpanel);
}
class Handler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent click) {
if(click.getSource()==read)
{
JFileChooser chooser = new JFileChooser();
Scanner input = null;
if(chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
try {
input = new Scanner(selectedFile);
while(input.hasNextLine())
{
record = input.nextLine();
desplay.append(record);
desplay.append("\n");
}
}catch(IOException fileerror) {
JOptionPane.showMessageDialog(null, "you have an error");
}
}
}
else if(click.getSource()==back)
{
mainpanel.setVisible(false);
add(new RecordsMenu());
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Search extends JPanel
{
DisplayDetails d = new DisplayDetails();
JLabel title,stdn;
JTextField studentno;
JPanel mainp,details,buttons;
JButton search,home;
Scanner input;
File records;
String key;
String line;
boolean wordfound = false;
public Search()
{
// title
title = new JLabel("Search a Student",SwingConstants.CENTER);
Font newLabelFont =new Font("Serif",Font.BOLD,30);
title.setFont(newLabelFont);
stdn = new JLabel("Student Number");
studentno = new JTextField(10);
//
search = new JButton("Search");
search.addActionListener(new Handler());
home = new JButton("Home");
mainp = new JPanel(new BorderLayout());
details = new JPanel(new GridLayout(1,2));
details.add(stdn);
details.add(studentno);
buttons = new JPanel(new GridLayout(1,2));
home.addActionListener(new Handler());
buttons.add(search);
buttons.add(home);
mainp.add(title,BorderLayout.NORTH);
mainp.add(details,BorderLayout.WEST);
mainp.add(buttons,BorderLayout.SOUTH);
add(mainp);
}
class Handler implements ActionListener
{
public void actionPerformed(ActionEvent button)
{
if(button.getSource()==search)
{
// define the key
key = studentno.getText();
if(key.matches("^2\\d{8}"))
{
File file =new File("StudentRecords.txt");
Scanner in;
try {
in = new Scanner(file);
while(in.hasNextLine())
{
line=in.nextLine();
if((line.contains(key))) {
wordfound=true;
break;
}
}
if((wordfound)) {
System.out.println(line);
mainp.setVisible(false);
add(d);
d.display.setText(line);
JOptionPane.showMessageDialog(null,"found");
}
else
{
JOptionPane.showMessageDialog(null,"not found");
}
in.close();
} catch(IOException e) {
}
}
else if(!(key.matches("^2\\d{8}")))
{
JOptionPane.showMessageDialog(null,"incorrect student number");
}
}
else if(button.getSource()==home)
{
mainp.setVisible(false);
add(new RecordsMenu());
}
}
}
// methods
public void RecordFOund()
{
}
public void notFound()
{
}
}
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame
{
public Frame()
{
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
add(new RecordsMenu());
// add(new Search());
setVisible(true);
}
}
try this
In the getter methods of the StudentRecords Class make them {return this.variable;}
as an example in the public int getTest1(){return this.test1;}
Hi I have the following code where I have a start and stop button . when start is pressed canvas starts painting but I cannot press stop button until the start operation is done . I need to stop and resume the paint on the button press . Once the start button is pressed the other buttons cannot be pressed till the canvas is painted.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;
public abstract class JUIApp extends JPanel implements ActionListener {
public static CACanvas cacanvas= null;
public ArrayList<int[]> genL;
public JFrame frame = null;
protected JPanel mainPanel = null;
private JButton btn0 = null;
private JButton btn1 = null;
private JButton btn2 = null;
#SuppressWarnings("rawtypes")
DefaultComboBoxModel rules = null;
#SuppressWarnings("rawtypes")
JComboBox rulesCombo =null;
JScrollPane ruleListScrollPane=null;
JLabel lable=null;
JTextField generation=null;
JLabel gLable=null;
public static String Rule;
public static String Generations;
public boolean isChanged =false;
public int gridCellSize=4;
private static final long serialVersionUID = 1L;
public int genCurrent=0;
public int posCurrent=0;
public int i;
public Color cellColor= null;
public Timer waitTimer;
public static boolean waitFlag;
public static boolean alert1Flag=false;
public boolean stopFlag=false;
public JLabel Alert1=new JLabel();
public int genCheck=0;
//private List<Point> fillCells;
public JUIApp() {
initGUI();
}
public void initGUI() {
//fillCells = new ArrayList<>(25);
frame = new JFrame();
frame.setTitle("Cellular Automata Demo");
frame.setSize(1050, 610);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(getMainPanel(),BorderLayout.NORTH);
frame.setVisible(true);
Toolkit.getDefaultToolkit().setDynamicLayout(false);
cacanvas=new CACanvas();
frame.add(cacanvas);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public JPanel getMainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
//cacanvas=new CACanvas();
btn0 = new JButton("Start");
btn0.addActionListener(this);
//waitTimer = new Timer(1000, this);
mainPanel.add(btn0);
JButton btn2 = new JButton("Stop");
btn2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent s)
{
stopFlag=true;
//cacanvas.repaint();
}
});
mainPanel.add(btn2);
btn1 = new JButton("Clear");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
CACanvas.clearFlag=true;
generation.setText("");
alert1Flag=true;
rulesCombo.setSelectedIndex(0);
Alert1.setText("Please enter the number of generations");
Alert1.setBounds(30, 20, 5, 5);
Alert1.setVisible(alert1Flag);
mainPanel.add(Alert1);
cacanvas.repaint();
frame.setSize(1060, 610);
}
});
mainPanel.add(btn1);
lable=new JLabel();
lable.setText("Select Rule :");
mainPanel.add(lable);
rules=new DefaultComboBoxModel();
for (int i=0;i<=100;i++)
{
String p=String.valueOf(i);
rules.addElement(p);
}
rules.addElement("250");
rules.addElement("254");
rulesCombo = new JComboBox(rules);
rulesCombo.setSelectedIndex(0);
ruleListScrollPane = new JScrollPane(rulesCombo);
mainPanel.add(ruleListScrollPane);
//mainPanel.revalidate();
gLable=new JLabel();
gLable.setText("Enter the number of Generations (Max 64)");
generation=new JTextField(2);
mainPanel.add(gLable);
mainPanel.add(generation);
// mainPanel.add(cacanvas);
return mainPanel;
}
public abstract void run();
#Override
public void actionPerformed(ActionEvent arg0) {
Alert1.setVisible(false);
waitFlag=false;
System.out.println("We received an ActionEvent " + arg0);
Generations=generation.getText();
System.out.println(Generations);
Rule = "";
if (rulesCombo.getSelectedIndex() != -1) {
Rule =
(String) rulesCombo.getItemAt
(rulesCombo.getSelectedIndex());
}
System.out.println(Rule);
int rule=Integer.parseInt(Rule);
Hashtable<String,Integer> rules= new Hashtable<String,Integer>();
CARule ruleClass=new CARule();
rules=ruleClass.setRule(rule);
CAGenetationSet sa =new CAGenetationSet(100, false,rules);
genL=new ArrayList<int[]>();
genL=sa.runSteps(Integer.parseInt(Generations));
System.out.println("calling pattern set");
for(int i=0;i<=genL.size()-1;i++)
{
System.out.println("Painting generation :"+i);
if(stopFlag==false)
{
cacanvas.repaint();
}
//genPaint();
//sleep();
int[] newCell=genL.get(i);
for(int r=0;r<newCell.length;r++)
{
if(newCell[r]==1)
{
System.out.println("Generaton is"+i+"CellLife is"+r);
cacanvas.fillCell(i,r);
}
}
}
/*cacanvas.patternSet(genL);
waitFlag=true;
System.out.println("run completed");
// cacanvas.clearFlag=true;
*/
}
public void genPaint()
{
cacanvas.repaint();
}
public void sleep()
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
JUIApp app = new JUIApp() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Run method");
}
};
}
}
Seems like you are using the current Thread on that task, you should create another Thread and add one listeners code to the new Thread.
I just started using Java Swing, and I was going through the following post: Dynamic fields addition in java/swing form.
I implement the code in this post with some modification, and it worked fine. As mentioned in the post, JPanel is not resizing itself when we add more rows. Can someone throw more light on this issue with easy to understand explanation that how can we resize JPanel as soon as we hit +/- button? Here is the code :
Row class
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class Row extends JPanel {
private JTextField quantity;
private JTextField item;
private JTextField price;
private JButton plus;
private JButton minus;
private RowList parent;
public Row(String initialQuantity, String initalPrice, String initialItem, RowList list) {
this.parent = list;
this.plus = new JButton(new AddRowAction());
this.minus = new JButton(new RemoveRowAction());
this.quantity = new JTextField(10);
this.item = new JTextField(10);
this.price = new JTextField(10);
this.quantity.setText(initialQuantity);
this.price.setText(initalPrice);
this.item.setText(initialItem);
add(this.plus);
add(this.minus);
add(this.quantity);
add(this.item);
add(this.price);
}
public class AddRowAction extends AbstractAction {
public AddRowAction() {
super("+");
}
public void actionPerformed(ActionEvent e) {
parent.cloneRow(Row.this);
}
}
public class RemoveRowAction extends AbstractAction {
public RemoveRowAction() {
super("-");
}
public void actionPerformed(ActionEvent e) {
parent.removeItem(Row.this);
}
}
public void enableAdd(boolean enabled) {
this.plus.setEnabled(enabled);
}
public void enableMinus(boolean enabled) {
this.minus.setEnabled(enabled);
}
}
RowList class
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class RowList extends JPanel{
private List<Row> rows;
public RowList() {
this.rows = new ArrayList<Row>();
Row initial = new Row("1","0.00","", this);
//addHeaders();
//addGenerateBillButton();
addItem(initial);
}
public void addHeaders(){
JLabel qty = new JLabel("Quantity");
//qty.setBounds(10, 0, 80, 25);
add(qty);
JLabel item = new JLabel("Item");
//item.setBounds(70, 0, 80, 25);
add(item);
JLabel price = new JLabel("Price");
//price.setBounds(120, 0, 80, 25);
add(price);
}
public void addGenerateBillButton(){
JButton billGenerationButton = new JButton("Generate Bill");
add(billGenerationButton);
}
public void cloneRow(Row row) {
Row theClone = new Row("1","0.00","", this);
addItem(theClone);
}
private void addItem(Row row) {
rows.add(row);
add(row);
refresh();
}
public void removeItem(Row entry) {
rows.remove(entry);
remove(entry);
refresh();
}
private void refresh() {
revalidate();
repaint();
if (rows.size() == 1) {
rows.get(0).enableMinus(false);
}
else {
for (Row e : rows) {
e.enableMinus(true);
}
}
}
}
Main class
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Enter Items");
RowList panel = new RowList();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You can call the pack() of the frame again.
Try this: Add this in your Row class
public class AddRowAction extends AbstractAction
{
public AddRowAction()
{
super("+");
}
public void actionPerformed(ActionEvent e)
{
parent.cloneRow(Row.this);
((JFrame) SwingUtilities.getRoot(parent)).pack(); // <--- THIS LINE
}
}
public class RemoveRowAction extends AbstractAction
{
public RemoveRowAction()
{
super("-");
}
public void actionPerformed(ActionEvent e)
{
parent.removeItem(Row.this);
((JFrame) SwingUtilities.getRoot(parent)).pack(); // <--- THIS LINE
}
}
You can get the root component (JFrame) using the SwingUtilities.getRoot(comp) from the child component and call the pack() method after your new Row is added to your RowList.
This would resize your JPanel. But your RowList will be horizontal. This is where LayoutManager comes into play.
You can know more about different LayoutManagers here.
To fix this problem, in your RowList panel, set your layout to:
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Within your refresh method call doLayout() method after revalidate()
Running into a lot of problems trying to populate a JList after a button press. The code below utilizes a technique that I have employed successfully before, but I have been unable to get this working. The goal is to run a test after pressing a button and display the urls that passed and the urls that failed in separate JLists.
The Action Listener:
//Start button--starts tests when pressed.
JButton start = new JButton("Start");
start.setPreferredSize(new Dimension(400, 40));
start.setAlignmentX(Component.CENTER_ALIGNMENT);
start.addActionListener(new Web(urlA, codeA, cb, passJ, failJ));
panel2.add(start);
The Action Listener Method:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
public class Web implements ActionListener {
private ArrayList<String> urls;
private ArrayList<Integer> statusCodes;
private JComboBox cb;
private JList passJ = new JList();
private JList failJ = new JList();
//constructor--allows other values to be used
public Web(ArrayList<String> urls, ArrayList<Integer> statusCodes, JComboBox cb, JList passList, JList failList ){
this.urls = urls;
this.statusCodes = statusCodes;
this.cb = cb;
this.passJ = passJ;
this.failJ = failJ;
}
#Override
public void actionPerformed(ActionEvent event){
ArrayList<String> resultsP = new ArrayList<String>();
ArrayList<String> resultsF = new ArrayList<String>();
//get source
JButton start = (JButton) event.getSource();
//get value from combobox
String selected = cb.getSelectedItem().toString();
if(selected.equals("ALL")){
}
if(selected.equals("STATUS CODE")){
for(int i = 0; i < urls.size(); i++){
try {
URL u = new URL(urls.get(i));
HttpURLConnection connection = (HttpURLConnection)u.openConnection(); //open connection and cast to HttpURLConnection
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code == statusCodes.get(i)){
System.out.println(i + "."+ urls.get(i)+" \t\t\t PASS");
resultsP.add(urls.get(i));
}
else{
System.out.println(i + "." +urls.get(i)+ "\t\t\t FAIL");
resultsF.add(urls.get(i));
}
} catch (MalformedURLException | ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (String str: resultsP){
System.out.println(str);
}
System.out.println("/////////////////////////////////////////////////////////////////////////////////");
for (String str: resultsF){
System.out.println(str);
}
passJ.removeAll();
failJ.removeAll();
passJ.setListData(resultsP.toArray());
failJ.setListData(resultsF.toArray()) ;
passJ.repaint();
failJ.repaint();
}//StatusCodeTest
}
}
How the lists are added to the GUI:
JList passJ = new JList(urlA.toArray());
JScrollPane scroll1 = new JScrollPane(passJ);
scroll1.setPreferredSize(new Dimension (700, 150));
scroll1.setMaximumSize( scroll1.getPreferredSize() );
scroll1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scroll1);
panel2.add(Box.createRigidArea(new Dimension(0,50)));
JList failJ = new JList(urlA.toArray());
JScrollPane scroll2 = new JScrollPane(failJ);
scroll2.setPreferredSize(new Dimension(700, 150));
scroll2.setMaximumSize(scroll1.getPreferredSize());
scroll2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scroll2);
//spacer
panel2.add(Box.createRigidArea(new Dimension(0,25)));
Any GUIdance would be greatly appreciated.
Seems you have different instances of passJ/failJ in your Web class and GUI class.
passJ.removeAll(); failJ.removeAll(); doesn't clear items of JList, that method from Container.
Here is simple example of adding/clearing items to JList:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestFrame extends JFrame {
private JList<Integer> normal;
private JList<Integer> fail;
private Integer[] vals;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
normal = new JList<Integer>(new DefaultListModel<Integer>());
fail = new JList<Integer>(new DefaultListModel<Integer>());
vals = new Integer[]{1,2,3,4,5,6,7,8,9,33};
JButton add = new JButton("collect data");
add.addActionListener(getCollectListener());
JButton clear = new JButton("clear data");
clear.addActionListener(getClearListener());
JPanel p = new JPanel();
p.add(new JScrollPane(normal));
p.add(new JScrollPane(fail));
JPanel btnPanel = new JPanel();
btnPanel.add(add);
btnPanel.add(clear);
add(p);
add(btnPanel,BorderLayout.SOUTH);
}
private ActionListener getClearListener() {
return new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((DefaultListModel<Integer>)normal.getModel()).removeAllElements();
((DefaultListModel<Integer>)fail.getModel()).removeAllElements();
}
};
}
private ActionListener getCollectListener() {
return new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Integer i : vals){
if(i%3==0){
((DefaultListModel<Integer>)normal.getModel()).addElement(i);
} else {
((DefaultListModel<Integer>)fail.getModel()).addElement(i);
}
}
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}
this code is only allowing me to reject a string the second time to try to drop in a textArea where there is all ready a string.
public GridLayoutTest() {
JFrame frame = new JFrame("GridLayout test");
connection = getConnection();
try {
statement = (PreparedStatement) connection
result = statement.executeQuery();
while (result.next()) {
byte[] image = null;
image = result.getBytes("image");
JPanel cellPanel = new JPanel(new BorderLayout());
cellPanel.add(cellLabel, BorderLayout.NORTH);
cellPanel.add(droplabel, BorderLayout.CENTER);
gridPanel.add(cellPanel);
}
}
catch (SQLException e) {
e.printStackTrace();}
}
So, two things, first...
public void DropTargetTextArea(String string1, String string2) {
Isn't a constructor, it's a method, note the void. This means that it is never getting called. It's also the reason why DropTargetTextArea textArea = new DropTargetTextArea(); works, when you think it shouldn't.
Second, you're not maintaining a reference to the values you pass in to the (want to be) constructor, so you have no means to references them later...
You could try using something like...
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this, true);
}
And then use something like...
if (values[0].equals(dragContents) || values[1].equals(dragContents)) {
In the drop method.
In your dragEnter, dragOver and dropActionChanged methods you have the oppurtunity to accept or reject the drag action using something like dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); or dtde.rejectDrag();
Updated with test code
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DragAndDropExample {
public static void main(String[] args) {
ImageIcon ii1 = new ImageIcon("C:\\Users\\Desktop\\home.jpg");
ImageIcon ii = new ImageIcon("C:\\Users\\Desktop\\images (2).jpg");
// Create a frame
JFrame frame = new JFrame("test");
JLabel label = new JLabel(ii);
JLabel label1 = new JLabel(ii1);
JPanel panel = new JPanel(new GridLayout(2, 4, 10, 10));
JLabel testLabel = new DraggableLabel("test");
JLabel testingLabel = new DraggableLabel("testing");
panel.add(testLabel);
panel.add(testingLabel);
panel.add(label);
panel.add(label1);
Component textArea = new DropTargetTextArea("test", "testing");
frame.add(textArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static class DraggableLabel extends JLabel implements DragGestureListener, DragSourceListener {
DragSource dragSource1;
public DraggableLabel(String text) {
setText(text);
dragSource1 = new DragSource();
dragSource1.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
public void dragGestureRecognized(DragGestureEvent evt) {
Transferable transferable = new StringSelection(getText());
dragSource1.startDrag(evt, DragSource.DefaultCopyDrop, transferable, this);
}
public void dragEnter(DragSourceDragEvent evt) {
System.out.println("Drag enter");
}
public void dragOver(DragSourceDragEvent evt) {
System.out.println("Drag over");
}
public void dragExit(DragSourceEvent evt) {
System.out.println("Drag exit");
}
public void dropActionChanged(DragSourceDragEvent evt) {
System.out.println("Drag action changed");
}
public void dragDropEnd(DragSourceDropEvent evt) {
System.out.println("Drag action End");
}
}
public static class DropTargetTextArea extends JLabel implements DropTargetListener {
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void dragEnter(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag enter");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragOver(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag over");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragExit(DropTargetEvent evt) {
System.out.println("Drop exit");
}
public void dropActionChanged(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject dropActionChanged");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void drop(DropTargetDropEvent evt) {
if (!getText().isEmpty()) {
evt.rejectDrop();
} else {
try {
Transferable transferable = evt.getTransferable();
if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String dragContents = (String) transferable.getTransferData(DataFlavor.stringFlavor);
evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
if (values[0].equals(dragContents) || (values[1]).equals(dragContents)) {
System.out.println("Accept Drop");
setText(getText() + " " + dragContents);
evt.getDropTargetContext().dropComplete(true);
} else {
System.out.println("Reject Drop");
}
}
} catch (IOException e) {
evt.rejectDrop();
evt.dropComplete(false);
} catch (UnsupportedFlavorException e) {
}
}
}
}
}