I want to add some images to my jlist. following code works great
public class MarioList {
private final Map<String, ImageIcon> imageMap;
public MarioList() {
String[] nameList = {"Mario", "Luigi", "Bowser", "Koopa", "Princess"};
imageMap = createImageMap(nameList);
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class MarioListRenderer extends DefaultListCellRenderer {
Font font = new Font("helvitica", Font.BOLD, 24);
#Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
label.setIcon(imageMap.get((String) value));
label.setHorizontalTextPosition(JLabel.RIGHT);
label.setFont(font);
return label;
}
}
private Map<String, ImageIcon> createImageMap(String[] list) {
Map<String, ImageIcon> map = new HashMap<>();
try {
map.put("Mario", new ImageIcon(new URL("http://i.stack.imgur.com/NCsHu.png")));
map.put("Luigi", new ImageIcon(new URL("http://i.stack.imgur.com/UvHN4.png")));
map.put("Bowser", new ImageIcon(new URL("http://i.stack.imgur.com/s89ON.png")));
map.put("Koopa", new ImageIcon(new URL("http://i.stack.imgur.com/QEK2o.png")));
map.put("Princess", new ImageIcon(new URL("http://i.stack.imgur.com/f4T4l.png")));
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MarioList();
}
});
}
}
above code creates a new frame and add a jscrollpane to it. Instead of that I tried to create the frame and jcrollpane mannually using Netbeans. So instead of this code;
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
I used this code;
jList1.add(nameList);
jList1.setCellRenderer(new MarioListRenderer());
Here jList1 is my jlist created via Netbeans and it has been put in a jscrollpane.
but this code doesn't work.
Please tell me a way to get this work... Thank you
Assuming you're using Java 7+...
jList1.add(nameList);
Should be
jList1.setListData(nameList);
Otherwise you will need to wrap the nameList within a ListModel implementation
Related
I have a database with tables. I passed the name of the tables into the buttons. When you click, you need a table with fields and filling to appear. The problem is that I have a new table added every time I click on the button.
Can someone please say me how to do it? Thanks in advance!
public class App extends JPanel {
static List<FieldElement> fields = new ArrayList<>();
static List<Map<String, Object>> data = new ArrayList<>();
static JTable jTable = new JTable();
public static void createGUI() throws SQLException {
TableContent tableContent = new TableContent();
JFrame frame = new JFrame();
MetadataHelper databaseMetadata = new MetadataHelper();
List<ButtonElement> elements = databaseMetadata.showTables();
JPanel panel = new JPanel();
JPanel buttons = new JPanel(new GridLayout(0, 1));
for (ButtonElement buttonElements : elements) {
JButton jButton = new JButton(buttonElements.getTablesInMigrateSchema());
buttons.add(jButton);
jButton.addActionListener(new ActionListener() {
#SneakyThrows
#Override
public void actionPerformed(ActionEvent e) {
fields = tableContent.getDatabaseMetadata().showFields(buttonElements.getTablesInMigrateSchema());
data = tableContent.getDatabaseMetadata().selectAll(buttonElements.getTablesInMigrateSchema());
Object[][] objectRows = data.stream().map(m -> m.values().toArray()).toArray(Object[][]::new);
jTable = new JTable(objectRows, fields.toArray());
panel.add(new JScrollPane(jTable));
frame.revalidate();
frame.repaint();
}
});
}
panel.add(buttons, BorderLayout.EAST);
frame.add(panel);
frame.setTitle("SwingSandbox");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#SneakyThrows
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
createGUI();
}
});
}
}
One easy possibility is to store the JScrollPane in a variable (which holds your table that you want to remove):
static JTable jTable = new JTable();
static JScrollPane jScrollPane;
And then in your actionPerformed method:
public void actionPerformed(ActionEvent e) {
...
if (jScrollPane != null) {
panel.remove(jScrollPane);
}
jTable = new JTable(objectRows, fields.toArray());
jScrollPane = new JScrollPane(jTable);
panel.add(jScrollPane);
frame.revalidate();
frame.repaint();
}
I need to handle the transfer of an object where the drop area consists of one JPanel, which has its own transferhandler, and a JLabel which also has its own transferhandler. The label is inside the panel so when I drop something on the label I want the both transferhandlers to be triggered. Is this possible?
This is a test code that I have made to explain the situation:
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1 ,2));
JTextField text = new JTextField("This is a text to drag!");
JPanel dropPanel = new JPanel();
JLabel dropLabel = new JLabel("Drop here");
text.setSize(30, 10);
text.setDragEnabled(true);
dropPanel.setBackground(Color.green);
dropPanel.setTransferHandler(new TransferHandler(){
#Override
public boolean importData(JComponent comp, Transferable t) {
System.out.println("Dropped on panel");
return true;
}
public boolean canImport(TransferSupport support) {
return true;
}
});
dropLabel.setTransferHandler(new TransferHandler(){
#Override
public boolean importData(JComponent comp, Transferable t) {
System.out.println("Dropped on label");
return true;
}
public boolean canImport(TransferSupport support) {
return true;
}
});
dropPanel.add(dropLabel);
panel.add(text);
panel.add(dropPanel, BorderLayout.LINE_END);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
Thanks in advance!
I have a frame that contains a mainPanel. This last will add other commandPanels (each one contains a button and a textField) Dynamically. the problem is that the JScrollPane does not appear to let me use the unseen commandPanels even if the mainPanel is full.
The below picture shows my case.
To initialize the window I wrote below code:
frame = new JFrame();
frame.setBounds(100, 100, 962, 639);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(264, 6, 692, 500);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
scroll = new JScrollPane();
scroll.getViewport().add(mainPanel);
frame.getContentPane().add(scroll);
and the method that add dynamically the new commandPanels is:
public void loadCommandPanel(String commandName)
{
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
mainPanel.add( scroll, BorderLayout.EAST);
frame.add( mainPanel);
...
}
Any help to get the scrollPane, will be much more than appreciated.
scroll.getViewport().add(mainPanel); is not how you use JViewport or JScrollPane; instead you should using something like this:
scroll.getViewport().setView(newCommandPanel);
or
scroll.setViewportView(newCommandPanel);
Take a look at How to Use Scroll Panes for more details.
Note also, this doesn't makes sense:
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
You add newCommandPanel to mainPanel, then promptly add it to another container (albeit incorrectly).
A component can only reside on a single parent; the moment you add it to another container, it is automatically removed from the previous container.
I have made some changes and it works perfectly now. For those who want the same thing here's my code:
import ...
public class mainUserInterface {
private JFrame frame;
private JPanel mainPanel;
private JPanel commandsPanel;
private JScrollPane commandsScrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainUserInterface window = new mainUserInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainUserInterface() {
initialize();
}
private void initialize() {
frame = new JFrame("CommandsExecutor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 700));
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.setBorder( new TitledBorder("") );
commandsPanel = new JPanel();
commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.Y_AXIS));
for(int i=0; i<15;i++){
commandsPanel.add(new CommandPanel());
}
commandsScrollPane = new JScrollPane(commandsPanel);
mainPanel.add(commandsScrollPane,BorderLayout.CENTER);
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
and Here's the commandPanel class:
import ...
public class CommandPanel extends JPanel {
private JTextField commandResult;
private JButton commandBtn;
public CommandPanel()
{
this.setLayout( new BorderLayout(10,10));
this.setBorder( new TitledBorder("Command:") );
this.setMaximumSize(new Dimension(692,60));
this.setMinimumSize(new Dimension(692,60));
commandBtn = new JButton("Execute");
commandBtn.setMaximumSize(new Dimension(137, 34));
commandBtn.setMinimumSize(new Dimension(137, 34));
this.add(commandBtn, BorderLayout.WEST);
commandResult = new JTextField();
commandResult.setMaximumSize(new Dimension(518, 34));
commandResult.setMinimumSize(new Dimension(518, 34));
this.add(commandResult, BorderLayout.CENTER);
}
public JTextField getCommandResult() {
return commandResult;
}
public JButton getCommandBtn() {
return commandBtn;
}
public void setCommandResult(JTextField commandResult) {
this.commandResult = commandResult;
}
public void setCommandBtn(JButton commandBtn) {
this.commandBtn = commandBtn;
}
}
Thanks for all who answered my question, it really helped.
I am making a battleship game and I'm trying to figure out a way to control buttons in a pane so that I can drag drop them and keep track of their indexes with a default list model.If I add string or ImageIcons it works fine but with buttons I get something different.
Here's my code:
public class ListModelExample extends JPanel {
JList list;
DefaultListModel model;
int counter = 15;
public ListModelExample() {
setLayout(new BorderLayout());
model = new DefaultListModel();
list = new JList(model);
JScrollPane pane = new JScrollPane(list);
JButton addButton = new JButton("Add Element");
JButton removeButton = new JButton("Remove Element");
final JButton button = new JButton("button");
for (int i = 0; i < 5; i++)
model.addElement(button);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addElement(button);
counter++;
}
});
removeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (model.getSize() > 0)
model.removeElementAt(0);
}
});
add(pane, BorderLayout.NORTH);
add(addButton, BorderLayout.WEST);
add(removeButton, BorderLayout.EAST);
}
public static void main(String s[]) {
JFrame frame = new JFrame("List Model Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ListModelExample());
frame.setSize(260, 200);
frame.setVisible(true);
}
}
If I add Buttons I get this result:
So my question is: How is it possible to make buttons appear normally and not as text in a default list model?
this could be done only by Renderer, put only String value to the DefaultListModel
don't put any JComponents to the XxxModel
I'd be use JPanel with JButtons instead of JList as containers (required to change getScrollableBlockIncrement / getScrollableUnitIncrement for natural scrolling in compare with JList or JTable)
example about both a.m. ways
import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
public class ListButtons extends JFrame {
private static final long serialVersionUID = 1L;
public ListButtons() {
setLayout(new GridLayout(0, 2, 10, 10));
DefaultListModel model = new DefaultListModel();
model.addElement(createButtons("one"));
model.addElement(createButtons("two"));
model.addElement(createButtons("three"));
model.addElement(createButtons("four"));
model.addElement(createButtons("five"));
model.addElement(createButtons("six"));
model.addElement(createButtons("seven"));
model.addElement(createButtons("eight"));
model.addElement(createButtons("nine"));
model.addElement(createButtons("ten"));
model.addElement(createButtons("eleven"));
model.addElement(createButtons("twelwe"));
JList list = new JList(model);
list.setCellRenderer(new PanelRenderer());
JScrollPane scroll1 = new JScrollPane(list);
final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar.getValue());
}
});
add(scroll1);
JScrollPane scroll2 = new JScrollPane(createPanel());
add(scroll2);
final JScrollBar scrollBar1 = scroll2.getVerticalScrollBar();
scrollBar1.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar1.getValue());
}
});
}
public static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 1, 1));
panel.add(createButtons("one"));
panel.add(createButtons("two"));
panel.add(createButtons("three"));
panel.add(createButtons("four"));
panel.add(createButtons("five"));
panel.add(createButtons("six"));
panel.add(createButtons("seven"));
panel.add(createButtons("eight"));
panel.add(createButtons("nine"));
panel.add(createButtons("ten"));
panel.add(createButtons("eleven"));
panel.add(createButtons("twelwe"));
return panel;
}
public static JButton createButtons(String text) {
JButton button = new JButton(text);
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ListButtons frame = new ListButtons();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//frame.pack();
frame.setSize(270, 200);
frame.setVisible(true);
}
});
}
class PanelRenderer implements ListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JButton renderer = (JButton) value;
renderer.setBackground(isSelected ? Color.red : list.getBackground());
return renderer;
}
}
}
i'm trying to add a jtable component to my jPanel but i am unable to see it. What am i doing wrong?.
table gui = new table(data,colum);
mainPanel.add(gui.table);
class table extends JFrame
{
public JTable table;
public table(Vector data, Vector colum)
{
setLayout(new FlowLayout());
table = new JTable(data,colum);
table.setPreferredScrollableViewportSize(new Dimension(900,10));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Extending JFrame seems odd; you don't use any of the top level container capabilities. Here's an example that extends JPanel, with a main() that drops the panel into a JFrame.
--Edited to accept an existing JPanel
public class TablePanel
{
public static void addTableToPanel(JPanel jPanel, Vector rowData, Vector columnNames)
{
JTable jTable = new JTable(rowData, columnNames);
jTable.setFillsViewportHeight(true);
JScrollPane jScrollPane = new JScrollPane(jTable);
jScrollPane.setPreferredSize(new Dimension(300, 50));
jPanel.add(jScrollPane);
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeAndWait(new Runnable()
{
#Override
public void run()
{
Vector cols = new Vector();
Vector rows = new Vector();
Vector row1 = new Vector();
cols.add("A");
cols.add("B");
cols.add("C");
row1.add("1");
row1.add("2");
row1.add("3");
rows.add(row1);
rows.add(row1.clone());
rows.add(row1.clone());
rows.add(row1.clone());
JFrame frame = new JFrame("TableTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout(0, 0));
TablePanel.addTableToPanel(jPanel, rows, cols);
frame.getContentPane().add(jPanel);
frame.pack();
frame.setVisible(true);
}
});
}
}