Problem: the buttons aren't being removed with lPanel.bListPanel.removeAll() included in the code.
My goal: when the button is clicked, I need the old buttons to disappear and a new list of buttons to populate.
Note: this button listener is in a separate class from the lPanel.
Thanks!
RoPanel class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class RoPanel extends JPanel {
public LPanel lPanel;
public RPanel rPanel;
private Ly l;
private ArrayList<JButton> bButtonList;
private JTextField newLoadField;
private JButton theButton;
public String bText;
private Border simpleBorder;
public RoPanel() {
this.setLayout(new BorderLayout());
simpleBorder = BorderFactory.createLineBorder(Color.GRAY);
l = new Ly();
lPanel = new LPanel();
rPanel = new RPanel();
this.setBorder(simpleBorder);
this.add(lPanel, BorderLayout.WEST);
this.add(rPanel, BorderLayout.EAST);
titleBooks = new ArrayList();
lPanel.getLoadButton();
lPanel.getLoadButton().addActionListener(new LoadButtonListener());
newLoadField = lPanel.getLoadField();
bookButtonList = new ArrayList();
bookText = new String();
}
private class LoadButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String loadStringfile = newLoadField.getText();
l.loadFromCSV(loadStringfile);
lPanel.bListPanel.removeAll();
// for loop that creates buttons
for (int i = 0; i < l.size(); i++) {
BButton b = new BButton();
bButtonList.add(theButton);
lPanel.bListPanel.add(theButton);
}
lPanel.bListPanel.revalidate();
lPanel.bListPanel.repaint();
}
}
}
LPanel class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.*;
public class LPanel extends JPanel {
private JTextField loadField;
private JButton loadButton;
private Border simpleBorder;
private Border lowerBorder;
JPanel bListPanel;
JPanel importPanel;
public LPanel() {
this.setLayout(new BorderLayout());
simpleBorder = BorderFactory.createLineBorder(Color.GRAY);
lowerBorder = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
bListPanel = new JPanel();
bListPanel.setLayout(new BoxLayout(bListPanel, BoxLayout.Y_AXIS));
importPanel = new JPanel();
this.add(importPanel, BorderLayout.SOUTH);
// create a jscrollpane that contains all buttons
JScrollPane scrollPane = new JScrollPane();
scrollPane.setLocation(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.getViewport().add(bListPanel);
this.add(scrollPane);
// loadfield and load button for iPanel
loadField = new JTextField();
loadField.setPreferredSize(new Dimension(170, 25));
importPanel.add(loadField);
loadButton = new JButton();
loadButton.setText("Load");
importPanel.add(loadButton);
}
}
Related
Actually I want to add image and text both in combo box . I have use JLabel for that but it doesn't work so how can I achieve this.
Here is my code :
package swing;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ComboBox {
public ComboBox() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("ComboBOx");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = frame.getContentPane();
JLabel ar[] = new JLabel[5];
ar[0] = new JLabel("ganesh",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[1] = new JLabel("ganes",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[2] = new JLabel("gane",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[3] = new JLabel("gan",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[4] = new JLabel("ga",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
JComboBox<JLabel> box = new JComboBox<JLabel>(ar);
con.add(box);
con.setBackground(Color.white);
con.setLayout(new FlowLayout());
frame.setVisible(true);
frame.pack();
}
public static void main(String args[]) {
new ComboBox();
}
}
#MadProgrammer Thanks, I find my answer
package swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class ComboBox {
ImageIcon imageIcon[] = { new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg"),
new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg") };
Integer array[] = {1,2,3,4,5};
String names[] = {"img1","img2","img3","img4","img5"};
public ComboBox() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("ComboBOx");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = frame.getContentPane();
ComboBoxRenderar rendrar = new ComboBoxRenderar();
JComboBox box = new JComboBox(array);
box.setRenderer(rendrar);
con.add(box);
con.setLayout(new FlowLayout());
frame.setVisible(true);
frame.pack();
}
public class ComboBoxRenderar extends JLabel implements ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
int offset = ((Integer)value).intValue() - 1 ;
ImageIcon icon = imageIcon[offset];
String name = names[offset];
setIcon(icon);
setText(name);
return this;
}
}
public static void main(String args[]) {
new ComboBox();
}
}
*edited so it might be helpful to others:
I was struggling with why an ImageIcon was being padded in a JPanel, but not in a JToolBar even though they were added in the same way, using the same file (see the folder icon):
Cutting down the code to an sscce has shown that VGR's answer below is right - it's has to be how each component deals with JButtons, rather than the layout.
This code should run, but you'll have to have "images/open.png" in the source folder.
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.border.Border;
class CandidatePanel extends JPanel{
private JPanel panel = new JPanel();
private JToolBar tb = new JToolBar();
private JButton tbButton = new JButton();
private JButton cvButton = new JButton();
public static void main(String[] args){
JFrame frame = new JFrame();
frame.add(new CandidatePanel());
frame.pack();
frame.setVisible(true);
}
public CandidatePanel(){
setLayout(new GridBagLayout());
tbButton.setIcon(new PanelHelper().createIcon("images/open.png", ""));
tb.add(tbButton);
cvButton.setIcon(new PanelHelper().createIcon("images/open.png", ""));
cvButton.setFocusPainted(false);
cvButton.setContentAreaFilled(false);
cvButton.setBorderPainted(true);
addComponents();
add(tb);
add(panel);
}
private void addComponents(){
panel.setLayout(new GridBagLayout());
int row =0;
//new row
JPanel cvButtonPanel = (JPanel)PanelHelper.addTestBorder(new JPanel(),Color.BLUE);
cvButtonPanel.add(cvButton);
cvButtonPanel.add(PanelHelper.addTestBorder(new JPanel(), Color.RED));
panel.add(tb, new GBC(1,row));
panel.add(cvButtonPanel, new GBC(1,++row));
}
}
class PanelHelper{
public static JComponent addTestBorder(JComponent comp, Color color){
Border border = BorderFactory.createLineBorder(color);
comp.setBorder(border);
return comp;
}
public ImageIcon createIcon(String path, String btnName){
URL url = getClass().getResource(path);
if(url == null)
System.err.println("\nThe "+btnName+" Icon Path Cannot Be Found: "+path);
return new ImageIcon(url);
}
}
it was just as simple as setting the button margin, as mentioned in the comments below.
button.setMargin(new Insets(0,0,0,0))
I am trying to get values from a database via Jlist; but when I select a value of Jlist, no values return and the "Jtable" becomes empty instead of titles. That's my code for UI.
Thanks for your help...
package ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import model.Category;
import model.Person;
import service.AddressBookService;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JSplitPane;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.AbstractListModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class UserInterfaceMain extends JFrame {
private JPanel contentPane;
private JPanel panel;
private JButton btnNew;
private JSplitPane splitPane;
private JList list;
private JTable table;
private JScrollPane scrollPane;
private List<Category> categories = new ArrayList<>();
private List<Person> personList = new ArrayList<>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserInterfaceMain frame = new UserInterfaceMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public UserInterfaceMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 624, 395);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
btnNew = new JButton("NEW");
panel.add(btnNew);
splitPane = new JSplitPane();
contentPane.add(splitPane, BorderLayout.CENTER);
list = new JList();
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
do_list_valueChanged(arg0);
}
});
splitPane.setLeftComponent(list);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.EAST);
table = new JTable();
splitPane.setRightComponent(table);
scrollPane.setViewportView(table);
loadCategories();
}
public void loadCategories() {
categories = new AddressBookService().getAllCategories();
DefaultListModel<Category> listModel = new DefaultListModel<>();
for (int i = 0; i < categories.size(); i++) {
listModel.addElement(categories.get(i));
//listModel.addElement(categories.get(i).getName());
}
list.setModel(listModel);
}
public void loadPersonList() {
String[] columns = new String[] { "NAME", "LAST NAME", "E-MAIL", "CITY" };
Object[][] personData = new Object[personList.size()][];
for (int i = 0; i < personData.length; i++) {
personData[i] = new Object[] { personList.get(i).getName(), personList.get(i).getLastName(),
personList.get(i).getEmail(), personList.get(i).getCity() };
}
TableModel tableModel = new DefaultTableModel(personData, columns);
table.setModel(tableModel);
}
protected void do_list_valueChanged(ListSelectionEvent arg0) {
personList = new AddressBookService().getPersonsForTable(((Category)list.getSelectedValue()).getId());
loadPersonList();
System.out.println(personList.size());
}
}
I don't understand exactly what you want, but I modified your code to run it in this way:
Obviously I have all hardcoded in order to run your program. If your problem is that in the left side instead of the names of the categories appears the hash code of the object "com.mypackage.Category#12AAAF", you must modify your Category class and override the toString method.
#Override
public String toString() {
return getName();
}
If it isn't your problem, please add a comment describing it.
I'm trying to make a GUI window in Java with 4 tabs at the top Home, Booking, Guest, Room. However, the problem is that I'm not sure how to implement buttons in specific tab.
More specific, I made a class called GuestTab and I made 1 button and 1 textfield, but I don't know how can I convey those informations to a Guest tab.
So, if I wasn't so clear, when I click on Guest tab I want to have buttons and text fields that I made in GuestTab class.
I'll put the code of "SEP" class, where I have my GUI main design and "GuestTab" class where I'm adding stuff for Guest tab.
SEP.java:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SEP extends JFrame
{
private GuestTab GuestTab;
private JTabbedPane tPane;
private MyButtonListener buttonListener;
private MyTabListener tabListener;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem exitMenuItem;
public SEP()
{
super("Deer Alley Hotel");
buttonListener = new MyButtonListener();
tabListener = new MyTabListener();
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(buttonListener);
fileMenu = new JMenu("File");
setJMenuBar(menuBar);
tPane = new JTabbedPane();
tPane.addTab(" Home ", new JPanel(
new FlowLayout()));
tPane.addTab(" Booking ", new JPanel(
new FlowLayout()));
tPane.addTab(" Guest ", GuestTab);
tPane.addTab(" Room ", new JPanel(new FlowLayout()));
tPane.addChangeListener(tabListener);
add(tPane);
setSize(575, 452);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == exitMenuItem)
{
int choice = JOptionPane.showConfirmDialog(null,
"Do you really want to exit the program?", "Exit",
JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
}
public class MyTabListener implements ChangeListener
{
public void stateChanged(ChangeEvent e)
{
}
}
}
GuestTab.java:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GuestTab extends JPanel
{
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JPanel panel1;
private JPanel panel2;
private JTextField text;
public GuestTab()
{
panel1 = new JPanel();
button1 = new JButton("Edit Note");
button2 = new JButton("Check out");
button3 = new JButton("Edit Form");
button4 = new JButton("Search");
text = new JTextField(15);
add(panel1);
panel1.setPreferredSize(new Dimension(280, 300));
panel1.add(button4);
panel1.add(text);
setVisible(true);
}
}
You aren't defining your GuestTab properly.
In this line:
tPane.addTab("Guest", guestTab);
Change it to:
tPane.addTab("Guest", new GuestTab());
Or you can initialize the JPanel. You never actually do this you just say
there is a guest tab but you never do anything with it so you can also do:
private GuestTab guestTab;
and then later:
guestTab = new GuestTab();
Side note, never use the same case for the variable definition and class call. Make sure you are using proper camel case.
I'm having trouble getting my GUI to contain any of my JButtons or JTextField. I have two classes One "SnowballFight" class that contains my main method and frame constructor. Then I also have "GameBoard" which sets up my GUI. My problem is that my GUI appears, but appears empty.
"SnowballFight" class:
package snowballfight;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SnowballFight extends JFrame implements ActionListener{
public SnowballFight(){
setLayout(new BorderLayout(1,2));
}
public static void main(String[] args) {
SnowballFight frame = new SnowballFight();
GameBoard game = new GameBoard(frame);
}
public void actionPerformed(ActionEvent event) {
}
}
"GameBoard" class:
package snowballfight;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameBoard extends JFrame implements ActionListener{
private JButton[][] game = new JButton[10][10];
private JTextField display = new JTextField("Welcome to the SnowBall fight!");
private Opponent[] opponents = new Opponent[4];
public GameBoard(SnowballFight frame){
JPanel panel = new JPanel();
panel.setLayout(new GridLayout( 10, 10));
for (int row = 0; row < game.length; row++) {
for (int col = 0; col < game[row].length; col++) {
game[row][col] = new JButton();
game[row][col].setBackground(Color.gray);
game[row][col].addActionListener(this);
panel.add(game[row][col]);
}
}
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.SOUTH);
frame.setTitle("Snowball Fight");
frame.setSize(200, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public boolean isGameOver(){
for (int opponent = 0; opponent < opponents.length; opponent++) {
if(opponents[opponent].isSoaked() == false ){
return false;
}
}
return true;
}
public void actionPerformed(ActionEvent event) {
}
}
Not sure why there are two frames, but I think you're adding display and panel to the wrong frame.
Try changing:
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.SOUTH);
to:
frame.add(display, BorderLayout.NORTH);
frame.add(panel, BorderLayout.SOUTH);
You never make the GameBoard JFrame visible
game.setVisible(true);
Some notes:
The frame SnowballFight has no apparent function
It's not necessary to extend JFrame since no functionality is being added
Read The Use of Multiple JFrames, Good/Bad Practice?