Adding a list of images in jscrollpane and show it - java

I need to add some images in jscrollpane and show the correct image when my jlist string is selected with relative image... but i have some doubt to do it.
public class Tela{
private JList<String> list;
public Tela(){
JFrame display = new JFrame();
display.setTitle("Maquina de Refrigerante");
String labels[] = { "Coca-Cola", "Fanta Laranja", "Fanta-Uva",
"Sprite"};
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel secondPanel = new JPanel();
//downPanel.add(BorderLayout.SOUTH);
//downPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 30, 260));
secondPanel.setBackground(Color.WHITE);
secondPanel.setPreferredSize(new Dimension(110,110));
final JButton comprar = new JButton("Comprar");
comprar.setEnabled(false);
list = new JList<String>(labels);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
list.setSelectedIndex(0);
JScrollPane pane = new JScrollPane();
pane.getViewport().add(list);
firstPanel.add(pane);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int selections[] = list.getSelectedIndices();
//String selectedValue = list.getSelectedValue();
Object selectionValues[] = list.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
if (i == 0) {
System.out.println("Value" + selectionValues[i] );
}}
comprar.setEnabled(true);
}
});
ImageIcon image = new ImageIcon("assets/fantalogo.jpg");
JScrollPane jsp = new JScrollPane(new JLabel(image));
panel.add(jsp);
buttonPanel.add(comprar);
buttonPanel.add(Box.createRigidArea(new Dimension(0,4)));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
panel.add(firstPanel);
panel.add(secondPanel);
panel.add(buttonPanel);
//panel.add(buttonPanel, BorderLayout.CENTER);
panel.setBackground(Color.BLACK);
display.add(panel);
display.setSize(550, 500);
display.setLocationRelativeTo(null);
display.setDefaultCloseOperation(display.EXIT_ON_CLOSE);
display.setVisible(true);
comprar.addActionListener(new Paga());
}
}
in my code how i can implemments it and view the correctly output?

Take a look at the section from the Swing tutorial on How to Use Combo Boxes. You find an example that does almost exactly what you want. The example uses a combo box, but the code for a JList will be very similar. That is the combo box contains a list of Strings and when you select an item the matching image is displayed.

Related

Effect on JTextfield due to JComboBox

I am using JCombobox and just below that there is a panel which contains JTextFields. Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself. I don't know what to do. I am unable to post a pic of the problem here because i am a new user and my reputation is below 10.
public class MainClass {
public static void main(String args[]){
Form form = new Form();
int width = 400;
int height = 400;
form.setSize(width, height);
form.setVisible(true);
form.setTitle("Create Network");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
form.setLocation((screenSize.width-width)/2, (screenSize.height-height)/2);
}
}
This is the form class
public class Form extends JFrame {
private JLabel ipAddress, networkTopo, numNodes;
private JTextField nodes;
private JButton addIp;
private JButton removeIp;
private JButton next, back;
private JPanel jPanel, jPanel1, jPanel2, commonPanel;
private JComboBox<String> dropDown;
private String[] topologies = { "Grid", "Diagnol Grid", "Bus", "Ring",
"Star" };
public Form() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
setResizable(false);
this.getContentPane().setBackground(Color.WHITE);
// add(Box.createRigidArea(new Dimension(0,10)));
GridLayout commonPanelLayout = new GridLayout(0, 2);
commonPanelLayout.setVgap(10);
commonPanel = new JPanel(commonPanelLayout);
commonPanel.setVisible(true);
commonPanel.setAlignmentX(commonPanel.LEFT_ALIGNMENT);
commonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
commonPanel.setBackground(Color.white);
numNodes = new JLabel("Number of Nodes");
commonPanel.add(numNodes);
nodes = new JTextField(20);
commonPanel.add(nodes);
networkTopo = new JLabel("Network Topology");
commonPanel.add(networkTopo);
dropDown = new JComboBox<String>(topologies);
dropDown.setBackground(Color.WHITE);
commonPanel.add(dropDown);
add(commonPanel);
add(Box.createRigidArea(new Dimension(0, 10)));
ipAddress = new JLabel("IP Addresses");
ipAddress.setAlignmentX(ipAddress.LEFT_ALIGNMENT);
ipAddress.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
add(ipAddress);
add(Box.createRigidArea(new Dimension(0, 10)));
jPanel = new JPanel(new FlowLayout());
jPanel.setVisible(true);
jPanel.setAlignmentX(jPanel.LEFT_ALIGNMENT);
jPanel.setBackground(Color.WHITE);
// jPanel1.setAutoscrolls(true);
add(jPanel);
GridLayout layout = new GridLayout(0, 1);
jPanel1 = new JPanel();
layout.setVgap(10);
// jPanel1.setBackground(Color.WHITE);
jPanel1.setVisible(true);
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(jPanel1);
scroll.setAutoscrolls(true);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setPreferredSize(new Dimension(300, 150));
jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width,
Integer.MAX_VALUE));
jPanel.add(scroll);
jPanel2 = new JPanel(new GridLayout(0, 1, 10, 10));
jPanel2.setBackground(Color.WHITE);
jPanel2.setVisible(true);
jPanel.add(jPanel2);
addIp = new JButton("Add");
jPanel2.add(addIp);
removeIp = new JButton("Remove");
jPanel2.add(removeIp);
JPanel savePanel = new JPanel(new FlowLayout());
savePanel.setVisible(true);
savePanel.setAlignmentX(savePanel.LEFT_ALIGNMENT);
savePanel.setBackground(Color.white);
back = new JButton("Back");
back.setAlignmentX(next.LEFT_ALIGNMENT);
back.setEnabled(false);
savePanel.add(back);
next = new JButton("Next");
next.setAlignmentX(next.LEFT_ALIGNMENT);
savePanel.add(next);
add(savePanel);
AddIPEvent addIPEvent = new AddIPEvent();
addIp.addActionListener(addIPEvent);
RemoveIPEvent removeIPEvent = new RemoveIPEvent();
removeIp.addActionListener(removeIPEvent);
}
public class AddIPEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel subPanel = new JPanel(new FlowLayout());
// subPanel.setBackground(Color.WHITE);
subPanel.setVisible(true);
JCheckBox jCheckBox = new JCheckBox();
// jCheckBox.setBackground(Color.WHITE);
subPanel.add(jCheckBox);
JTextField ip = new JTextField(12);
subPanel.add(ip);
JTextField nodesInIp = new JTextField(6);
nodesInIp.setVisible(false);
subPanel.add(nodesInIp);
jPanel1.add(subPanel);
jPanel1.repaint();
jPanel1.revalidate();
}
}
public class RemoveIPEvent implements ActionListener {
public void removeIP(Container container) {
for (Component c : container.getComponents()) {
if (c instanceof JCheckBox) {
if (((JCheckBox) c).isSelected()) {
jPanel1.remove(container);
jPanel.revalidate();
jPanel1.repaint();
}
} else if (c instanceof Container) {
removeIP((Container) c);
}
}
}
public void actionPerformed(ActionEvent e) {
removeIP(jPanel1);
}
}
}
After Clicking on the Add button and then clicking on the JComboBox will make portion of JTextField dissapear. Could someone pls point out the mistake?
Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself.
//jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width, Integer.MAX_VALUE));
Don't set the preferred size of components. The layout manager will determine the preferred size as components are added/removed. Then scrollbars will appear as required.
jPanel1.repaint();
jPanel1.revalidate();
The order should be:
jPanel1.revalidate();
jPanel1.repaint();
The revalidate() first invokes the layout manager before it is repainted.
//form.setSize(width, height);
form.pack();
Again, don't try to set the size. Let the layout managers do their jobs. The pack() will size the frame based on the sizes of the components added to the frame.

My JTable doesn't show up

I'm new to JTable, or GUI for that matter, but i had been given an assignment of building a receipt program inside a GUI. I manage to get the basic things work, but my table looks awful. I need help on how to display the table properly
public static void main (String[] args)
{
ArrayList <item> lol= new ArrayList <item>();
item ayam = new item("ayam",5678);
item kambing= new item("kambing",5014);
item buaya= new item("buaya",3000);
item bocoranquiz= new item("bocoranquiz",5000);
lol.add(ayam);
lol.add(kambing);
lol.add(buaya);
lol.add(bocoranquiz);
JFrame frame= new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 0));
frame.setSize(1000, 1000);
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
String date = sdf.format(new Date());
JComboBox combo1= new JComboBox();
combo1.setPreferredSize(new Dimension(10, 10));
combo1.addItem(ayam.getname());
combo1.addItem(kambing.getname());
combo1.addItem(buaya.getname());
combo1.addItem(bocoranquiz.getname());
JLabel label1= new JLabel("Invoice no: ");
JLabel label2= new JLabel("Invoice Date : " + date);
JLabel label3= new JLabel("Item name " );
JLabel label4= new JLabel("Item Price ");
JLabel label5= new JLabel("Item Quantity : ");
JPanel panel1= new JPanel ();
panel1.setLayout(new GridLayout(3,0));
panel1.add(label1);
panel1.add(label2);
class inputListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JComboBox<String> combo= (JComboBox<String>) event.getSource();
selected= (String) combo.getSelectedItem();
alpha=10;
if (selected.equals("ayam"))
{
alpha=5678;
}
else if (selected.equals("kambing"))
{
alpha=5014;
}
else if (selected.equals("buaya"))
{
alpha=3000;
}
else if (selected.equals("bocoranquiz"))
{
alpha=5000;
}
label3.setText("Item name " + selected);
label4.setText("Item quantity " + alpha);
}
}
ActionListener inputAct = new inputListener();
combo1.addActionListener(inputAct);
panel1.add(combo1);
JTextField tf = new JTextField();
JButton adda = new JButton("Add");
String[] columnNames= {"Name","Price","Quantity","Total"};
DefaultTableModel tablemodel= new DefaultTableModel(columnNames,0);
JTable table = new JTable(tablemodel);
JScrollPane scrollPanel = new JScrollPane(table);
class inputListener2 implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
quantity= Integer.parseInt(tf.getText());
double total= alpha * quantity;
Object[] data= {selected,alpha,quantity,total};
tablemodel.addRow(data);
}
ActionListener inputAct2 = new inputListener2();
adda.addActionListener(inputAct2);
JPanel panel2= new JPanel();
panel2.setLayout(new GridLayout(10,0));
panel2.add(label3);
panel2.add(label4);
panel2.add(label5);
panel2.add(tf);
panel2.add(adda);
panel2.add(scrollPanel);
frame.add(panel1);
frame.add(panel2);
frame.setVisible(true);
}
Your code is a bit of mess, but, the basic problem is your setting your GridLayout with to many rows, for example
frame.setLayout(new GridLayout(3, 0));
should be
frame.setLayout(new GridLayout(2, 0));
since you're only adding 2 components to the frame
Equally,
panel2.setLayout(new GridLayout(10, 0));
should probably be
panel2.setLayout(new GridLayout(6, 0));
Remember, a GridLayout will divide the container into equal sections, even if there is nothing contained within the row/column.
You may also want consider using a different layout manager, like GridBagLayout, or a combination of layouts depending on your basic needs.
See How to use GridBagLayout for more details.

I added a 3D array of JTextField to a JPanel in a JFrame then nothing shows up

It was working before I added the 3D array of textfields, then nothing showed from all I have created. After removing them, still nothing shows up. How do I add a 3D array of JTextFields without ruining the whole layout?
I initialized them first:
int numOfPuzzles;
int puzzleSize;
JTabbedPane tabbedPane;
JPanel[] southPanel;
JPanel[] centerPanel;
JPanel[] sudokuPanel;
JPanel[] buttonsPanel;
JButton[] nextButton;
JButton[] prevButton;
ArrayList<int[][]> sudoku;
JTextField[][][] textFields;
public SudokuSolverUI(ArrayList<int[][]> sudoku){
this.sudoku = sudoku;
this.numOfPuzzles = numOfPuzzles;
this.puzzleSize = puzzleSize;
this.setTitle("Sudoku XY");
this.setVisible(true);
this.setSize(900, 700);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setComponents();
}
then at public void setComponents I instantiated the necessary components, added them to the panel, then:
public void setComponents(){
this.tabbedPane = new JTabbedPane();
centerPanel = new JPanel[this.numOfPuzzles];
sudokuPanel = new JPanel[this.numOfPuzzles];
buttonsPanel = new JPanel[this.numOfPuzzles];
southPanel = new JPanel[this.numOfPuzzles];
nextButton = new JButton[this.numOfPuzzles];
prevButton = new JButton[this.numOfPuzzles];
for(int i=0;i<this.numOfPuzzles;i++){
nextButton[i] = new JButton("Next");
nextButton[i].addActionListener(this);
prevButton[i] = new JButton("Prev");
prevButton[i].addActionListener(this);
centerPanel[i] = new JPanel();
sudokuPanel[i] = new JPanel();
buttonsPanel[i] = new JPanel();
southPanel[i] = new JPanel();
for(int j=0;j<this.sudoku.get(i).length;j++){
for(int k=0;k<this.sudoku.get(i).length;k++){
textFields[i][j][k] tf = new JTextField();
sudokuPanel[i].add(tf);
}
}
southPanel[i].setLayout(new FlowLayout());
southPanel[i].add(prevButton[i]);
southPanel[i].add(nextButton[i]);
centerPanel[i].setLayout(new BorderLayout());
centerPanel[i].add(southPanel[i], BorderLayout.SOUTH);
centerPanel[i].add(sudokuPanel[i], BorderLayout.CENTER);
centerPanel[i].add(buttonsPanel[i], BorderLayout.EAST);
centerPanel[i].setVisible(true);
centerPanel[i].validate();
tabbedPane.addTab("Puzzle #"+(i+1), centerPanel[i]);
this.getContentPane().add(tabbedPane);
}
}
nothing shows up. Please help.
If this is all you'll get a NullPointerException which you should be able to see at the console. You did not initialize numOfPuzzle but you use it as index in setComponents.

Ad selected panel throw JCombobox

I'm having problem with adding another JPanel to my frame when I'm using combobox.
I want to change the center panel according to the selection in combobox.
I made differehnt panel to all selections but it didn't add to my main panel.
I added the code.
thanks :)
import AllClasses.FlightCompany;
{
public class WorkerDialog extends JFrame {
private JPanel Worker;
private String[] LabelNames = { "Worker Type:", " Worker Name:" };
String [] str = { "Office", "Host",
"Pilot" };
JComboBox<String> ChooseBox = new JComboBox<>(str);
public JPanel MainPanel;
private JPanel [] p= new JPanel[3];
public WorkerDialog(FlightCompany f) {
super("Worker Dialog");
p[0] = new Office_Gui();
p[1] = new Host_Gui();
p[2] = new Pilot_Gui();
Worker = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel LabelName = new JLabel(LabelNames[0]);
JLabel LabelName2 = new JLabel(LabelNames[1]);
JTextField fieldBox = new JTextField();
LabelName.setSize(40, 25);
ChooseBox.setPreferredSize(new Dimension(180, 22));
Worker.add(LabelName);
Worker.add(ChooseBox);
Worker.add(LabelName2);
fieldBox.setPreferredSize(new Dimension(180, 22));
Worker.add(fieldBox);
JPanel AddPanel = new JPanel(new GridLayout(2, 1, 1, 1));
AddPanel.add(new JButton("Add"));
AddPanel.add(new JButton("TakeOff"));
MainPanel = new JPanel(new BorderLayout(3, 3));
AddPanel.setPreferredSize(new Dimension(0, 110));
ChooseBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
//String str = e.getActionCommand();
String jb = (String) ChooseBox.getSelectedItem();
if (jb.equals("Office")){
MainPanel.add(p[0],BorderLayout.CENTER);
System.out.println("Office");}
}
});
MainPanel.add(Worker, BorderLayout.NORTH);
MainPanel.add(AddPanel, BorderLayout.SOUTH);
add(MainPanel);
//pack();
setSize(560, 300);
setAlwaysOnTop(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
What you want to do is use a CardLayout for your mainPanel, that will allow you to easily switch between panels. Then add all your panels to the mainPanel, specifying a name for the panel. That name will go in the combo box. When you want to show a certain panel, just call cardLayout.show(mainPanel, "nameOfPanel")
To learn more about Cardlayout see How to Use CardLayout. You can also see a simple example here
An aside: Use Java naming convention. Variables begin with lower case letters, using camel casing. ie:
ChooseBox → chooseBox
MainPanel → mainPanel
etc.

JList not updating when set to new DefaultListModel

public class MainMenu extends JFrame {
private JPanel panel,file_list_panel;
private JPanel contentPane;
private JMenuBar menuBar;
private JMenu mnNewMenu1,mnNewMenu2,mnNewMenu3;
private JMenuItem mt1,mt2,mt3;
private JPanel right,left ,bottom;
private JSplitPane spver ,sphor;
private JTabbedPane tabbedPane;
private JLabel label;
private JList<String> list_1;
private JScrollPane jscroll_list;
private DefaultListModel listmodel_1 = new DefaultListModel();
public MainMenu() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
int intValue = Integer.parseInt( "EEEEEE",16);
Color aColor = new Color( intValue );
UIManager.put("TabbedPane.background", new Color(230, 216, 174));
UIManager.put("TabbedPane.selected", Color.WHITE);
UIManager.put("TabbedPane.contentAreaColor",aColor );
UIManager.put("TabbedPane.focus", Color.WHITE);
setTitle("Main Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setBounds(100, 100, 848, 680);
//setLocation(10, 10);
setLocationRelativeTo(null); // set jFrame alignment to center
//parent(first) panel
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(2, 2, 2, 2));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
//Main Menu BAR
menuBar = new JMenuBar();
menuBar.setFont(new Font("Tekton Pro Ext", Font.PLAIN, 11));
setJMenuBar(menuBar);
//Menu 1
mnNewMenu1 = new JMenu("New menu");
menuBar.add(mnNewMenu1);
//Menu 1 MenuItem 1
mt1 = new JMenuItem("Browse New Project");
mt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
BrowseScreen frame = new BrowseScreen();
frame.setVisible(true);
}
});
mnNewMenu1.add(mt1);
//second panel
panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
spver =new JSplitPane(JSplitPane.VERTICAL_SPLIT);
spver.setDividerLocation(500);
spver.setEnabled(false);
bottom=new JPanel();
sphor =new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
sphor.setEnabled(false);
spver.setTopComponent(sphor);
spver.setBottomComponent(bottom);
bottom.setLayout(null);
panel.add(spver);
sphor.setDividerLocation(180);
left =new JPanel();
right =new JPanel();
sphor.setRightComponent(right);
right.setLayout(new GridLayout(0, 1, 0, 0));
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
JPanel tab1 = new JPanel();
tabbedPane.addTab("fffa", tab1);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JPanel tab2 = new JPanel();
tabbedPane.addTab("TAB1", tab2);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
right.add(tabbedPane);
sphor.setLeftComponent(left);
left.setLayout(new BorderLayout(0, 0));
file_list_panel= new JPanel();
file_list_panel.setBackground(Color.BLACK);
file_list_panel.setForeground(Color.WHITE);
label = new JLabel("Java Files of Project");
label.setBackground(Color.BLACK);
label.setForeground(Color.WHITE);
label.setFont(new Font("Garamond", Font.BOLD, 14));
file_list_panel.add(label);
left.add(file_list_panel, BorderLayout.NORTH);
list_1 = new JList<String>(listmodel_1);
jscroll_list = new JScrollPane(list_1);
left.add(jscroll_list, BorderLayout.CENTER);
}
public void setList(Vector<String> files){
listmodel_1.removeAllElements();
list_1.removeAll();
for(int i=0;i<files.size();i++)
listmodel_1. addElement(files.elementAt(i));
list_1.setModel(listmodel_1);
this.invalidate();
this.validate();
this.repaint();
}
}
setList is called from the browse window before it calls setVisible(false);
ie . this methods gets called when the browse window disappears .. it does all the things in method but does not update it in the MainMenu
public void setFileList(){
MainMenu mm= new MainMenu();
mm.setList(java_files);
}
list_1 -JList listmodel_1=DefaultListModel
i've tried to refreshing the frame but does not refresh after adding the new list to the Main Window ...
before JList is updated im browsing the the files in another window then it is set to setVisible(false) then MainMenu gets focused and calls the setList method but its not changing
You're creating a new JList<String> and copying the reference to your instance variable - but you're neither removing the old JList from the frame, nor adding the new one. Just changing the variable won't do that.
Rather than creating a new JList<String>, why don't you just replace the model of the existing one? Remove this line:
list_1=new JList<String>(listmodel_1);
and you may find it just works. (You're already setting the model in the subsequent line...)
Basically, you are creating a new JList and associating your model with it, but this has no effect on the JList that is on the screen
public void setList(Vector<String> files){
// Good...
listmodel_1.removeAllElements();
// Not required, has nothing to do with the items in the list
//list_1.removeAll();
// Good
for(int i=0;i<files.size();i++)
listmodel_1. addElement(files.elementAt(i));
// This here is your problem
//list_1=new JList<String>(listmodel_1);
// Because I have no idea what model list_1 is actually using...
list_1.setModel(listmodel_1);
//list_1.setSelectedIndex(0);
//this.invalidate();
//this.validate();
//this.repaint();
}

Categories