How to Add JTextField & JCheckBox to ArrayList Object - java

I'm working on my very first GUI app.
I have an ArrayList of the Parent Class Plant of which I have four child classes.
I have some JTextFields with some information and some JCheckBoxs with other information...
The JTextFields should be converted into Strings and the JCheckBoxs into boolean.
I need to add all of these components to an ArrayList and then display the list of the Plants.
How can I do that?
Example:
public class Flower extends Plant{
private boolean thorns;
private boolean smell;
public Flower(String name, String id, String color, boolean blnThorns, boolean blnSmell){
super(name, id, color);
thorns = blnThorns;
smell = blnSmell;
}
public boolean isThorns(){
return thorns;
}
public void setThorns(boolean blnThorns){
thorns = blnThorns;
}
public boolean isSmell(){
return smell;
}
public void setSmell(boolean blnSmell){
smell = blnSmell;
}
}
This is my ArrayList
ArrayList<Plant> plantList = new ArrayList<Plant>();
Here I try to add the parameters for the Flower:
private void addFlower(ArrayList<Plant> plantList){
//Adding window
JFrame addingFrame = new JFrame();
addingFrame.setTitle("Plant Database Interface");
addingFrame.setSize(600, 200);
addingFrame.setLocationRelativeTo(null);
addingFrame.setVisible(true);
//ADDING FRAME LAYOUT
addingFrame.setLayout(new BorderLayout());
//TRAITS
JPanel fields = new JPanel();
addingFrame.add(fields, BorderLayout.NORTH);
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField(15);
String name = nameField.getText();
JLabel idLabel = new JLabel("ID:");
JTextField idField = new JTextField(10);
String id = idField.getText();
JLabel colorLabel = new JLabel("Color:");
JTextField colorField = new JTextField(10);
String color = colorField.getText();
fields.add(nameLabel);
fields.add(nameField);
fields.add(idLabel);
fields.add(idField);
fields.add(colorLabel);
fields.add(colorField);
JPanel traits = new JPanel();
addingFrame.add(traits , BorderLayout.CENTER );
JCheckBox thornsBox = new JCheckBox("Thorns Present");
thornsBox.setSelected(false);
traits.add(thornsBox);
JCheckBox smellBox = new JCheckBox("Smell Present");
smellBox.setSelected(false);
traits.add(smellBox);
JPanel southPanel = new JPanel();
addingFrame.add(southPanel, BorderLayout.SOUTH);
JButton addPlantBtn = new JButton("Add Plant");
southPanel.add(addPlantBtn, BorderLayout.EAST);
JButton cancelBtn = new JButton("Cancel");
southPanel.add(cancelBtn, BorderLayout.WEST);
boolean blnThorns;
boolean blnSmell;
//I REALLY DON'T KNOW HOW TO DO THIS PART
thornsBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED){
blnThorns =true;
}
else{
blnThorns = false;
}
}
});
smellBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED){
blnSmell =true;
}
else{
blnSmell = false;
}
}
});
addPlantBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//plantList.add(new Flower(name, id, color, blnThorns, blnSmell)); //HOW TO DO????................
}
});
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addingFrame.dispatchEvent(new WindowEvent(addingFrame, WindowEvent.WINDOW_CLOSING));
}
});
}

Use your addPlantBtn ActionListener to gather the information you need when it's called
addPlantBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Flower flower = new Flower(nameField.getText(), idField.getText(), colorField.getText(), thornsBox.isSelected(), smellBox.isSelected());
plantList.add(flower);
You would, also, find it easier, if you created a dedicated JPanel, designed to gather the user details and generate a Flower when you requested it to (from the values of the fields). You could then use this panel on some kind of dialog when ever you needed it.
Have a look at How to Make Dialogs for more details
For example...
public class FlowerPane extends JPanel {
JTextField nameField = new JTextField(15);
JTextField idField = new JTextField(10);
JTextField colorField = new JTextField(10);
JCheckBox smellBox = new JCheckBox("Smell Present");
JCheckBox thornsBox = new JCheckBox("Thorns Present");
public FlowerPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(2, 2, 2, 2);
JLabel nameLabel = new JLabel("Name:");
JLabel idLabel = new JLabel("ID:");
JLabel colorLabel = new JLabel("Color:");
add(nameLabel, gbc);
gbc.gridy++;
add(idLabel, gbc);
gbc.gridy++;
add(idLabel, gbc);
gbc.gridx++;
gbc.gridy = 0;
add(nameField, gbc);
gbc.gridy++;
add(idField, gbc);
gbc.gridy++;
add(colorField, gbc);
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(thornsBox, gbc);
gbc.gridy++;
add(smellBox, gbc);
}
public Flower create() {
return new Flower(nameField.getText(), idField.getText(), colorField.getText(), thornsBox.isSelected(), smellBox.isSelected());
}
}
Which you could then use by doing something like...
FlowerPane flowerPane = new FlowerPane();
switch (JOptionPane.showConfirmDialog(null, flowerPane, "Flower", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) {
case JOptionPane.OK_OPTION:
Flower flower = flowerPane.create();
plantList.add(flower);
break;
}
Or add it to some other container

Related

JFrame doesn't dispose()

So, I have a login JFrame which shows up when I run the code. The problem is if the user enters the correct userName and password this login frame needs to be disposed when the other frame is shown up but it doesn't. I tried dispose(), setVisible = false, but still no chance to be hidden or disposed.
class LoggingWindow extends JFrame {
static JFrame loginFrame = new JFrame();
JPanel loginPanel = new JPanel();
JTextField loginNameFld = new JTextField(10);
JPasswordField loginPassFld = new JPasswordField(10);
JTextField statusFld = new JTextField(11);
String userName = "user";
String password = "password";
//Initialize loginFrame
public static void initLoginFrame() {
JFrame loginWindow = new LoggingWindow();
//loginFrame.setTitle("\"Moflo Registration\"");
loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginWindow.setResizable(false);
loginWindow.setUndecorated(true);
loginWindow.setVisible(true);
loginWindow.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
loginWindow.setSize(new Dimension(220, 290));
loginWindow.setLocationRelativeTo(null);
loginWindow.pack();
LoggingWindow() {
loginFrame.add(loginPanel);
loginPanel.setLayout(new GridBagLayout());
GridBagConstraints gbb = new GridBagConstraints();
gbb.insets = new Insets(1, 1, 1, 1);
gbb.anchor = GridBagConstraints.CENTER;
JPanel loginNameAndPasswordPanel = new JPanel();
loginPanel.add(loginNameAndPasswordPanel,gbb);
gbb.gridx = 0;
gbb.gridy = 2;
loginNameAndPasswordPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(0,0,0,0);
JLabel loginNameLab = new JLabel("Нэр : ");
gbc.gridx = 0;
gbc.gridy = 0;
loginNameAndPasswordPanel.add(loginNameLab, gbc);
JLabel loginPassLab = new JLabel("Нууц үг : ");
gbc.gridx = 0;
gbc.gridy = 1;
loginNameAndPasswordPanel.add(loginPassLab, gbc);
loginNameFld.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 0;
loginNameAndPasswordPanel.add(loginNameFld, gbc);
loginPassFld.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 1;
loginNameAndPasswordPanel.add(loginPassFld, gbc);
statusFld.setEditable(false);
loginNameAndPasswordPanel.add(statusFld, gbc);
statusFld.setHorizontalAlignment(JTextField.CENTER);
JPanel buttonsPanel = new JPanel();
loginPanel.add(buttonsPanel,gbb);
gbb.gridx = 0;
gbb.gridy = 3;
buttonsPanel.setLayout(new GridBagLayout());
GridBagConstraints gba = new GridBagConstraints();
gba.anchor = GridBagConstraints.LINE_END;
gba.insets = new Insets(2, 2, 2, 2);
JButton loginBtn = new JButton("Нэвтрэх");
gba.gridx = 0;
gba.gridy = 0;
buttonsPanel.add(loginBtn, gba);
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
String name = loginNameFld.getText();
String pass = loginPassFld.getText();
if(event.getSource() == loginBtn){
if (name.equals(userName) && pass.equals(password)) {
initMainFrame();
loginFrame.dispose();
JOptionPane.showMessageDialog(null, "Системд нэвтэрлээ. Өнөөдөр " + showDate, " ", JOptionPane.INFORMATION_MESSAGE);
} else {
statusFld.setText("Нэр эсвэл нууц үг буруу байна.");
}
}
}
});
JButton closeBtn = new JButton(" Хаах ");
gba.gridx = 1;
gba.gridy = 0;
buttonsPanel.add(closeBtn, gba);
add(loginPanel);
closeBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
//Main method
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initLoginFrame();
}
});
}
}
public class MainFrame extends JFrame {
//Initialzie mainFrame
public static void initMainFrame() {
JFrame mainFrame = new MainFrame();
mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
mainFrame.setMinimumSize(new Dimension(800, 600));
mainFrame.setLocationRelativeTo(null);
}
some, i think unimportant statements are not shown for the sake of brevity
I believe you confused "loginWindow" with "loginFrame". You try to use
loginFrame.dispose();
but your content is on loginWindow, not loginFrame.
I was able to get it to dispose the username window doing the following.
static JFrame loginWindow; <--- create as class variable, not local.
//loginFrame.add(loginPanel); <--- doesn't appear that this is actually used
if(event.getSource() == loginBtn){
if (name.equals(userName) && pass.equals(password)) {
MainFrame.initMainFrame();
//loginFrame.dispose(); <--- again, not used
loginWindow.dispose(); <--- want to dispose
JOptionPane.showMessageDialog(null, "Системд нэвтэрлээ. Өнөөдөр " , " ", JOptionPane.INFORMATION_MESSAGE);
} else {
statusFld.setText("Нэр эсвэл нууц үг буруу байна.");
}
}
You must also change this:
JFrame loginWindow = new LoggingWindow();
to:
loginWindow = new LoggingWindow();
You can always dispatch the "close" event to the JFrame object:
loginFrame.dispatchEvent(new WindowEvent(loginFrame, WindowEvent.WINDOW_CLOSING));
I definitely confused with loginFrame was indeed useless. I created a class variable: static JFrame loginWindow; but it results NullPointerException.

How do you get the gui to restart? (JAVA)

For instance, I want the program to run multiple times without stopping after somebody has pressed the "Please hit to finish process". However, when I do run the GUI method again, only the first panel shows up. Unsure of why this is happening.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
public class Hotel {
public static JFrame frame;
public static JPanel pan;
public static JPanel endPanel;
public static JPanel buttonPanel;
public static GridBagConstraints c;
public static GridBagConstraints f;
public static JButton econ;
public static Boolean openA = true;
public Hotel(){
Frame();
GUI();
}
public static void Frame(){
frame = new JFrame ("Kiosk");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(600,400);
}
public static void GUI (){
pan = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
frame.add(pan);
JLabel l2 = new JLabel("Please fill out your name and room number");
l2.setVisible(false);
pan.add(l2);
buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints GB = new GridBagConstraints();
JButton b1 = new JButton("Check in?");
c.gridx=0;
c.gridy=0;
c.insets = new Insets(10,10,10,10);
buttonPanel.add(b1, c);
JButton b2 = new JButton("Check out?");
c.gridx=1;
c.gridy=0;
c.insets = new Insets(10,10,10,10);
buttonPanel.add(b2, c);
frame.add(buttonPanel);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
buttonPanel.setVisible(false);
Checkin();
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
l2.setVisible(true);
b1.setVisible(false);
b2.setVisible(false);
}
});
}
public static void Checkin(){
JLabel name = new JLabel("What is your name?");
c.gridx=0;
c.gridy=0;
pan.add(name,c);
JLabel number = new JLabel("How many people in your party?");
c.gridx=0;
c.gridy=3;
pan.add(number,c);
JTextField namefield = new JTextField(20);
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=0;
pan.add(namefield,c);
JTextField numberfield = new JTextField(2);
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=3;
pan.add(numberfield,c);
JButton confirm = new JButton("Confirm");
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=4;
pan.add(confirm,c);
JPanel errorPanel = new JPanel(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
errorPanel.setVisible(false);
frame.add(errorPanel);
JButton econ = new JButton("Confirm");
d.insets = new Insets(10,10,10,10);
d.gridx=1;
d.gridy=4;
errorPanel.add(econ,d);
JLabel error = new JLabel("Sorry you must fill in all the fields");
d.insets = new Insets(10,10,10,10);
d.gridx=1;
d.gridy=0;
errorPanel.add(error,d);
confirm.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if((namefield.getText().equals("")) ||
(numberfield.getText().equals(""))){
pan.setVisible(false);
errorPanel.setVisible(true);
econ.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
errorPanel.setVisible(false);
pan.setVisible(true);
}
});
}
else{
endPanel = new JPanel(new GridBagLayout());
f = new GridBagConstraints();
pan.setVisible(false);
frame.add(endPanel);
String hey = namefield.getText();
Memory(hey);
int people =0;
try {
people = Integer.parseInt(numberfield.getText());
}
catch(NumberFormatException ex)
{
System.out.println("Exception : "+ex);
}
Rooms(people);
}
}
});
}
public static void Memory(String h){
ArrayList<String> Guest = new ArrayList<String>();
for(int x=0;x<Guest.size();x++){
if(Guest.get(x).equals(h)){
JLabel duplicate = new JLabel("Duplicate Name - Please refer
to the manager " + h);
JPanel dupPanel = new JPanel();
pan.setVisible(false);
dupPanel.setVisible(true);
frame.add(dupPanel);
econ.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dupPanel.setVisible(false);
pan.setVisible(true);
}
});
}
else{
JLabel nameLab = new JLabel("Have a nice day " + h);
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=0;
endPanel.add(nameLab);
}
Guest.add(h);
}
}
public static void Rooms(Integer n){
JLabel roomLab = new JLabel("Sorry there are no rooms with that
occupany available");
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=0;
endPanel.add(roomLab,f);
JButton restart = new JButton("Please hit to finish process");
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=4;
endPanel.add(restart,f);
int x=0;
if(openA == true && n<2){
openA = false;
x=1;
}
switch(x){
case 1 : roomLab.setText("You have been assigned room A");
}
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
endPanel.setVisible(false);
GUI();
}
});
}
public static void main(String[] args) {
new Hotel();
}
}
If you want to cleanly restart a GUI, and make sure that the new GUI is 100% independent from the previous one, the best way is to dispose of the previous one, and create a brand new instance.
The biggest problem in your case is that all your fields and methods are static. This is wrong. You should typically have something like:
public class Hotel extends JFrame {
public JPanel pan;
...
public Hotel() {
super("Kiosk");
createGUI();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setSize(600,400);
}
public void createGUI(){
pan = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
add(pan);
...
If you want to restart the GUI, it's then very simple:
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
new Hotel();
}
});
If you just want to reset a particular panel within the frame, you can remove it from its container, and add a new instance:
somepanel.remove(somesubpanel);
somepanel.add(createSubpanel());

Swing: how to get value from JTextfield in every JPanel?

My school project is to create a purchasing system for that I create a JPanel array to list out all the products information and also allow user to input something for every item. And I dont know how to get all the values from jtextfields by clicking one button. The actionPerformed() method always requires a final variable which is quite troublesome for me.
private JButton payBtn;
public void shoppingCartTab(Customer userIn){
contentPanel.removeAll();
bottomPanel.removeAll();
final Customer USER = userIn;
ArrayList<Product> pArray = new ArrayList<Product>();
pArray = loadCartFile.loadCartFile(userIn);
JLabel tabLabel = new JLabel("Shopping Cart");
JPanel cartItems = new JPanel();
cartItems.setLayout(new BoxLayout(cartItems, BoxLayout.Y_AXIS));
final JPanel CONSTANT_CART = cartItems;
JScrollPane scroller = new JScrollPane(cartItems);
if(pArray != null){
JPanel item[] = new JPanel[pArray.size()];
for(int i = 0; i< pArray.size(); i++){
item[i] = new JPanel();
final JPanel JPANEL_TO_DEL = item[i];
item[i].setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.weightx = 0.3;
item[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel icon_small = new JLabel(new ImageIcon("Icons\\" + pArray.get(i).getID() + "_small.jpg"));
JLabel itemID = new JLabel(pArray.get(i).getID());
final String CONSTANT_ID = pArray.get(i).getID();
JLabel itemName = new JLabel(pArray.get(i).getName());
JLabel itemPrice = new JLabel("$" + pArray.get(i).getPrice());
JPanel setQuantity = new JPanel();
JButton plusBtn = new JButton("+");plusBtn.setPreferredSize(new Dimension(45,30));
final JTextField QUANTITY = new JTextField("0");QUANTITY.setColumns(3);
QUANTITY.setPreferredSize(new Dimension(45,30));QUANTITY.setHorizontalAlignment(JTextField.CENTER);
JButton minusBtn = new JButton("-");minusBtn.setPreferredSize(new Dimension(45,30));
plusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())<100)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())+1));
}
});
minusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())>0)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())-1));
}
});
setQuantity.add(plusBtn);
setQuantity.add(QUANTITY);
setQuantity.add(minusBtn);
JButton delBtn = new JButton("Delete");
delBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure to remove this item from your cart?", "Confirm", JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
CONSTANT_CART.remove(JPANEL_TO_DEL);
revalidate();
repaint();
ShoppingCart.removeItem(USER, CONSTANT_ID);
}
}
});
gBC.gridx = 0;
gBC.gridy = 0;
item[i].add(icon_small,gBC);
gBC.gridx = 1;
gBC.gridy = 0;
item[i].add(itemID,gBC);
gBC.gridx = 2;
gBC.gridy = 0;
item[i].add(itemName,gBC);
gBC.gridx = 3;
gBC.gridy = 0;
item[i].add(itemPrice,gBC);
gBC.gridx = 4;
gBC.gridy = 0;
item[i].add(setQuantity,gBC);
gBC.gridx = 5;
gBC.gridy = 0;
item[i].add(delBtn,gBC);
cartItems.add(item[i]);
}
contentPanel.add(tabLabel);
contentPanel.add(scroller);
payBtn = new JButton("Pay");
bottomPanel.add(payBtn); payBtn.addActionListener(this);
}else{
JLabel emptyMsg = new JLabel("Your cart is empty!");
contentPanel.add(emptyMsg);
}
revalidate();
repaint();
}
One solution would be to create a type which extends JPanel, and exposes a public property, which when called returns the value stored in the JTextField. Something like:
public class TextFieldPanel extends JPanel {
private JTextField myTextField;
public TextFieldPanel()
{
//layout init code here
}
public String getText()
{
return myTextField.getText();
}
}
Then just use this class instead of a regular JPanel. Then when your button is clicked, iterate over each of the objects in your collection, and call getText() on them to get your values.

can't change ImageIcon from anonymous class inside a JPanel

I'm currently building a picture sorter. I have a JList which has filenames, to the left of this I have an ImageIcon which should show the picture for the current file_chosen in the JList.
The problem is I can't find a way of updating the ImageIcon contained inside a JLabel; since the change appears inside the anonymous class where the ListSelectionListener() is.
Below is the code:
public class MemeList extends JPanel{
public MemeList(){
// load/update the file list.
updateFileList();
this.setLayout(new GridBagLayout());
JPanel east = new JPanel();
east.setLayout(new GridBagLayout());
gbc.gridx = 1;
gbc.gridy = 0;
this.add(east,gbc);
west = new JPanel();
west.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
this.add(west,gbc);
filearray = flist.toArray(new String[flist.size()]);
list = new JList(filearray);
list.addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
file_chosen = (String) list.getSelectedValue();
System.out.println("selected = "+file_chosen);
}
}
});
meme_preview_icon = new ImageIcon(path + "/" + file_chosen); // file_chosen
label2 = new JLabel("", meme_preview_icon, JLabel.CENTER);
gbc.gridx = 0;
gbc.gridy = 0;
west.add(label2,gbc);
updateIcon();
JScrollPane pane = new JScrollPane();
pane.getViewport().add(list);
pane.setPreferredSize(new Dimension(320, 340));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(0,0,0,0);
east.add(pane, gbc);
}
Below here is the method for changing ImageIcon
public void updateIcon(){
//west.removeAll();
meme_preview_icon = new ImageIcon(path + "/" + file_chosen); // file_chosen
label2.setIcon(meme_preview_icon);
west.revalidate();
west.repaint();
}
I figured out the problem with my flatmate.
I just needed to call the method updateIcon() inside the ListSelectionListener(). I got confused because it told me before it had to be static and then the listener can't be static. But there it is.
list.addListSelectionListener(new ListSelectionListener()
#Override
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
file_chosen = (String) list.getSelectedValue();
System.out.println("selected = "+file_chosen);
updateIcon();
}
}
});

Can't get Java GUI Layout to Show Correctly

I'm working on this application and I just can't get the GUI to display properly. I'm using FlowLayout, and everything just looks all jumbled (any other layout looks even worse). If there were just some way to add a horizontal rule between sections, that would work, but nothing I tried works.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class ConnectToDB implements ActionListener {
public static void main(String[] args){
//GUI STUFF
//constants
final int windowX = 640; //pixels
final int windowY = 655; //pixels
final int fieldX = 20; //characters
final FlowLayout LAYOUT_STYLE = new FlowLayout();
//window
JFrame window = new JFrame("Mike's MySQL GUI Client");
//Connection Details
JLabel enterInfo = new JLabel("Enter Connection Details: ");
JLabel driver = new JLabel("Database Driver: ");
JTextField driverText = new JTextField(fieldX);
JLabel dburl = new JLabel("Database URL: ");
JTextField dburlText = new JTextField(fieldX);
JLabel dbuser = new JLabel("Username: ");
JTextField dbuserText = new JTextField(fieldX);
JLabel dbpass = new JLabel("Password: ");
JTextField dbpassText = new JTextField(fieldX);
//Enter a SQL Command
JLabel enterSQL = new JLabel("Enter a SQL Command:");
JTextArea enterSQLText = new JTextArea(10, 30);
//Connection Status and Command Buttons
JLabel connectionStatus = new JLabel ("No Connection Now");
JButton connectButton = new JButton("Connect");
JButton executeButton = new JButton("Execute SQL Command");
JButton clearCommandButton = new JButton("Clear Command");
//SQL Execution Result
JLabel executionResult = new JLabel("SQL Execution Result:");
JButton clearResultsButton = new JButton("Clear Results");
JTextArea executionResultText = new JTextArea(20, 50);
//Configure GUI
window.setSize(windowX, windowY);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
driverText.setEditable(false);
dburlText.setEditable(false);
dbuserText.setEditable(false);
dbpassText.setEditable(false);
executionResultText.setEditable(false);
//Register Event Listeners
connectButton.addActionListener(null);
executeButton.addActionListener(null);
clearCommandButton.addActionListener(null);
clearResultsButton.addActionListener(null);
//Construct Container
Container c = window.getContentPane();
c.setLayout(LAYOUT_STYLE);
c.add(enterInfo);
c.add(driver);
c.add(driverText);
c.add(dburl);
c.add(dburlText);
c.add(dbuser);
c.add(dbuserText);
c.add(dbpass);
c.add(dbpassText);
c.add(connectionStatus);
c.add(connectButton);
c.add(enterSQL);
c.add(enterSQLText);
c.add(executeButton);
c.add(clearCommandButton);
c.add(new JSeparator(SwingConstants.VERTICAL));
c.add(executionResult);
c.add(clearResultsButton);
c.add(executionResultText);
window.setVisible(true);//END GUI STUFF
//DB Connection details
System.out.println("Attempting to connect to database...");
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "project3";
String DBdriver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "OMGnpw=-0";
driverText.setText(DBdriver);
dburlText.setText(url);
dbuserText.setText(userName);
dbpassText.setText(password);
try
{
//Connect to DB and notify user
Class.forName(DBdriver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
/*>>>>>>Do everything you need to do while connected to DB<<<<<<*/
//HOW TO EXECUTE A STATEMENT AND PRINT IT
//Create a statement
Statement statement = conn.createStatement();
//Execute a statement
ResultSet resultSet = statement.executeQuery("SELECT * FROM riders");
//Process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
System.out.printf("%20s\t", metaData.getColumnName(i));
}
System.out.println();
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
System.out.printf("%20s\t", resultSet.getObject(i));
}
System.out.println();
}
/*>>>>>>Finish DB activities<<<<<<*/
//Disconnect from DB
conn.close();
System.out.printf("Disconnected from database");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e){
System.out.println("Button Works!");
}
}
I may need to use a different layout, but FlowLayout is the only one I'm familiar with. Can anyone suggest an easy fix?
Try a box layout. And add some panels to it. Make the panels flow layout and put a pair of label and textfield in each panel
|-----container with box layout-----|
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]sqltextfields]
panel[[flow]buttons]
|-----------------------------------|
and near the bottom put your sql textfields and buttons
http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
So, we a little playing around you can achieve this...
This uses a combination of card layout, border layout, grid bag layout and flow layout
Connection Pane...
Query Pane
public class TestLayout11 {
public static void main(String[] args) {
new TestLayout11();
}
public TestLayout11() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SQLPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class SQLPane extends JPanel {
private ConnectionPane connectionPane;
private QueryPane queryPane;
public SQLPane() {
setLayout(new CardLayout(8, 8));
connectionPane = new ConnectionPane();
connectionPane.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Perform login...
((CardLayout) getLayout()).show(SQLPane.this, "query");
}
});
queryPane = new QueryPane();
add(connectionPane, "connection");
add(queryPane, "query");
((CardLayout) getLayout()).show(this, "connection");
}
}
public static class ConnectionPane extends JPanel {
protected static final int FIELD_CHARACTER_WIDTH = 20; //characters
private JButton connectButton;
private JTextField driverText;
private JTextField dburlText;
private JTextField dbuserText;
private JTextField dbpassText;
public ConnectionPane() {
JLabel enterInfo = new JLabel("Enter Connection Details: ");
JLabel driver = new JLabel("Database Driver: ");
driverText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dburl = new JLabel("Database URL: ");
dburlText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dbuser = new JLabel("Username: ");
dbuserText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dbpass = new JLabel("Password: ");
dbpassText = new JTextField(FIELD_CHARACTER_WIDTH);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = 2;
gbc.insets = new Insets(2, 2, 2, 2);
add(enterInfo, gbc);
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = 1;
gbc.gridy++;
add(driver, gbc);
gbc.gridy++;
add(dburl, gbc);
gbc.gridy++;
add(dbuser, gbc);
gbc.gridy++;
add(dbpass, gbc);
gbc.gridx++;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.WEST;
add(driverText, gbc);
gbc.gridy++;
add(dburlText, gbc);
gbc.gridy++;
add(dbuserText, gbc);
gbc.gridy++;
add(dbpassText, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 2;
connectButton = new JButton("Connect");
add(connectButton, gbc);
}
public void addActionListener(ActionListener listener) {
connectButton.addActionListener(listener);
}
public void removeActionListener(ActionListener listener) {
connectButton.removeActionListener(listener);
}
}
public static class QueryPane extends JPanel {
private JTextArea enterSQLText;
public QueryPane() {
JLabel enterSQL = new JLabel("Enter a SQL Command:");
enterSQLText = new JTextArea(10, 30);
JButton clearResultsButton = new JButton("Clear Results");
JButton executeButton = new JButton("Execute SQL Command");
setLayout(new BorderLayout());
add(enterSQL, BorderLayout.NORTH);
add(new JScrollPane(enterSQLText));
JPanel buttons = new JPanel();
buttons.add(executeButton);
buttons.add(clearResultsButton);
add(buttons, BorderLayout.SOUTH);
executeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute query...
String text = enterSQLText.getText();
enterSQLText.setText("I've being executed....");
}
});
clearResultsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
enterSQLText.setText(null);
}
});
}
}
}

Categories