I have been doing research on here and have been searching for a solution to the problem. I am new to java so I don't know all of the syntax. I am trying to get my code to transfer items from one jlist to another using the buttons in-between the jlists. The left list has the items to begin with. The code is suppose to move items from the left list to the right list with the add button; also suppose to move whatever items we added to the right list back to the left list with the remove button. My code adds the item from left list to right list but it does not hold the item added. The next item I try to add just replaces the old item. Can anyone help me out please? Below is the entire code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
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.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Window {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Window() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
initialize();
}
public void initialize() {
//Creating the Panel for Menu Bar
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 23);
frame.getContentPane().add(panel);
panel.setLayout(new BorderLayout(0, 0));
//Creating the Menu File Bar
JMenuBar bar = new JMenuBar();
panel.add(bar, BorderLayout.NORTH);
JMenu file = new JMenu("File");
JMenuItem load = new JMenuItem("Load");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
file.add(load);
file.add(save);
file.add(exit);
bar.add(file);
//Populate Left List with part names
final DefaultListModel parts = new DefaultListModel();
parts.addElement("Case");
parts.addElement("Motherboard");
parts.addElement("CPU");
parts.addElement("GPU");
parts.addElement("PSU");
parts.addElement("RAM");
parts.addElement("HDD");
final JList leftList = new JList(parts);
leftList.setBounds(10, 26, 142, 224);
frame.getContentPane().add(leftList);
//create right list
final DefaultListModel partSelected = new DefaultListModel();
final JList rightList = new JList();
rightList.setBounds(282, 26, 142, 224);
frame.getContentPane().add(rightList);
//add event to the button to move items from left list to right list
JButton btnNewButton = new JButton(">>");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rightList.setListData(leftList.getSelectedValues());
for (Object selectedValue : leftList.getSelectedValuesList()) {
partSelected.addElement(selectedValue);
parts.removeElement(selectedValue);
int iSelected = leftList.getSelectedIndex();
if (iSelected == -1) {
return;
}
}
}
});
btnNewButton.setBounds(172, 86, 89, 23);
frame.getContentPane().add(btnNewButton);
//Remove Button
JButton remove = new JButton("<<");
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rightList.setListData(leftList.getSelectedValues());
for (Object selectedValue : rightList.getSelectedValuesList()) {
parts.addElement(selectedValue);
int selected = rightList.getSelectedIndex();
if (selected == -1) {
return;
}
partSelected.removeElement(selectedValue);
}
}
});
remove.setBounds(172, 140, 89, 23);
frame.getContentPane().add(remove);
}
}
#Prob1em I've updated your code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Window {
private final JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Window window = new Window();
window.frame.setVisible(true);
});
}
public Window() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
initialize();
}
public void initialize() {
//Creating the Panel for Menu Bar
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 23);
frame.getContentPane().add(panel);
panel.setLayout(new BorderLayout(0, 0));
//Creating the Menu File Bar
JMenuBar bar = new JMenuBar();
panel.add(bar, BorderLayout.NORTH);
JMenu file = new JMenu("File");
JMenuItem load = new JMenuItem("Load");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
file.add(load);
file.add(save);
file.add(exit);
bar.add(file);
//Populate Left List with part names
final DefaultListModel parts = new DefaultListModel();
parts.addElement("Case");
parts.addElement("Motherboard");
parts.addElement("CPU");
parts.addElement("GPU");
parts.addElement("PSU");
parts.addElement("RAM");
parts.addElement("HDD");
final JList leftList = new JList(parts);
leftList.setBounds(10, 26, 142, 224);
frame.getContentPane().add(leftList);
//create right list
final DefaultListModel partSelected = new DefaultListModel();
final JList rightList = new JList(partSelected);
rightList.setBounds(282, 26, 142, 224);
frame.getContentPane().add(rightList);
//add event to the button to move items from left list to right list
JButton btnNewButton = new JButton(">>");
btnNewButton.addActionListener((ActionEvent arg0) -> {
// rightList.setListData((Vector) leftList.getSelectedValue());
for (Object selectedValue : leftList.getSelectedValuesList()) {
partSelected.addElement(selectedValue);
parts.removeElement(selectedValue);
int iSelected = leftList.getSelectedIndex();
if (iSelected == -1) {
return;
}
}
});
btnNewButton.setBounds(172, 86, 89, 23);
frame.getContentPane().add(btnNewButton);
//Remove Button
JButton remove = new JButton("<<");
remove.addActionListener((ActionEvent arg0) -> {
// rightList.setListData(leftList.getSelectedValues());
for (Object selectedValue : rightList.getSelectedValuesList()) {
parts.addElement(selectedValue);
partSelected.removeElement(selectedValue);
int selected = rightList.getSelectedIndex();
if (selected == -1) {
return;
}
}
});
remove.setBounds(172, 140, 89, 23);
frame.getContentPane().add(remove);
}
}
btw why did you write rightList.setListData(leftList.getSelectedValues()) and its also a deprecated method in Java 8 please follow proper naming conventions while declaring variables though I haven't changed them in this code, the event handling functions are as per Java 8 lambda expression,
Hope this helps
Related
based on my understanding,
`list_1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
}}
will do something when something in the list was selected, and
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
do something when the button have been pushed.
I want to write a code to delete the selected item from one list and add it to another one.
I can't use Jlist methods because it is not in the scope of button.
I am not sure how to do it. and I can't find something that solve my problem on net or books.
Thank you so much
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JList;
import java.awt.GridLayout;
import javax.swing.JSplitPane;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import javax.swing.JSeparator;
import java.awt.Panel;
import java.awt.List;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Color;
import java.awt.Font;
public class Window {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. This is the constructor for this Window class.
* All of the code here will be executed as soon as a Window object is made.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame. This is where Window Builder
* will generate its code.
*/
public void initialize() {
//creates an array for the list of components
String pclist[]={"case","moderboard","CPU","GPU","PSU","RAM","HDD"};
frame = new JFrame();
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmLoad = new JMenuItem("Load");
mnFile.add(mntmLoad);
JMenuItem mntmSave = new JMenuItem("Save");
mnFile.add(mntmSave);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
frame.getContentPane().setLayout(null);
JButton button = new JButton(">>");
button.setBounds(244, 170, 82, 36);
button.setFont(new Font("Tahoma", Font.BOLD, 15));
frame.getContentPane().add(button);
JButton button_1 = new JButton("<<");
button_1.setBounds(244, 219, 82, 36);
button_1.setFont(new Font("Tahoma", Font.BOLD, 15));
frame.getContentPane().add(button_1);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 205, 493);
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
panel.setLayout(null);
JList list = new JList();// implements ActionListener;
list.setBounds(0, 0, 205, 493);
list.setListData(pclist); //populate the Jlist
list.setFont(new Font("Tahoma", Font.BOLD, 18));
panel.add(list);
JPanel panel_1 = new JPanel();
panel_1.setBounds(358, 0, 212, 493);
panel_1.setBackground(Color.WHITE);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JList list_1 = new JList();
list_1.setBounds(203, 0, -200, 480);
list_1.setSelectedIndex(0);
list_1.setFont(new Font("Tahoma", Font.BOLD, 18));
panel_1.add(list_1);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//list_1.addElement("hi");
System.out.println("hoi");
}
});
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent arg0) {
}});
list_1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
}
}
);
}
}
Start by making your JLists instance variables
public class Window {
private JFrame frame;
private JList list;
private JList list_1;
Make sure you're initialising the instance variables and not creating new local variables...
//JList list = new JList();// implements ActionListener;
list = new JList();// implements ActionListener;
//...
panel.add(list);
//JList list_1 = new JList();
list_1 = new JList();
//...
panel_1.add(list_1);
This now means that the JLists are accessible from within the context of an instance of the class...
Then in your ActionListeners, you can simple do something like...
Object selected = list.getSelectedValue();
or...
int index = list.getSelectedIndex();
You can then use these values to modify the state of the underlying ListModel...if it supports those operations...
Edit - #Heuster linked another question that answers this.
I just found out about WindowBuilder and I'm making a simple chat client using it to teach myself. Right now I've got the basic chat frame done, but only some of the components that I've added are accessible in the code. Specifically, I can't access my input JTextArea, taInput. Is there something I need to do to be able to reference it (to get the text in it for sending, etc.)?
Here's a picture of the Design view:
And here's a the generated code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
public class frame extends JFrame
{
private JPanel contentPane;
private JButton btnSend;
private JTextArea taDisplay;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
frame frame = new frame();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public frame()
{
setResizable(false);
setTitle("Client");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 440, 316);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmConnect = new JMenuItem("Connect...");
mnFile.add(mntmConnect);
JMenuItem mntmSaveChatLog = new JMenuItem("Save chat log...");
mnFile.add(mntmSaveChatLog);
JMenuItem mntmSettings = new JMenuItem("Settings...");
mnFile.add(mntmSettings);
JMenuItem mntmClose = new JMenuItem("Close");
mnFile.add(mntmClose);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnView = new JMenu("View");
menuBar.add(mnView);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
btnSend = new JButton("Send");
btnSend.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
taDisplay.append("Send clicked.\n");
}
});
btnSend.setBounds(314, 197, 100, 50);
panel.add(btnSend);
taDisplay = new JTextArea();
taDisplay.setLineWrap(true);
taDisplay.setEditable(false);
taDisplay.setBounds(10, 11, 404, 180);
panel.add(taDisplay);
JScrollPane spInput = new JScrollPane();
spInput.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
spInput.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spInput.setBounds(10, 197, 294, 49);
panel.add(spInput);
JTextArea taInput = new JTextArea();
taInput.setLineWrap(true);
spInput.setViewportView(taInput);
}
}
From the design tab you could right click on the item (taInput) then click rename on the context menu, in the diaog, at the right of the name there where 2 buttons, clic on the (f) button (field) and then ok.
I am making a library database for a school project and am having a little trouble with my menu. So the main problem is that in the Action Listener method when I write
(e.getSource()==m1Frame1)
my program does not detect the menu item and gives me an error. I have looked at multiple tutorials etc. online but cannot seem to find any way to fix it and make it so that if a specific item is clicked a specific action occurs. Any help/resolution regarding this issue would be much appreciated.
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.*;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
import java.awt.event.*;
import javax.swing.Icon;
import java.awt.*;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Color;
public class m1 extends JFrame {
JPanel pane = new JPanel();
JFrame a = new JFrame("Main Frame");
JFrame b = new JFrame("Sub Frame");
JButton checkOutButton = new JButton("check");
JButton returnButton = new JButton("return");
JMenu mb2 = new JMenu("Books");
// mb2.setForeground(Color.white);
JMenu open = new JMenu("Students");
// open.setForeground(Color.white);
public m1() {
JMenuBar mb;
mb = new JMenuBar() {
public void paintComponent(Graphics g) {
g.drawImage(Toolkit.getDefaultToolkit().getImage("G:"), 0, 0, this);
}
};
setSize(400, 400);
setBackground(Color.BLACK);
setTitle("Screen 2");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mb.add(open);
JMenuItem m1Frame1 = new JMenuItem("Create");
JMenuItem m1Frame2 = new JMenuItem("Delete");
JMenu m1Frame3 = new JMenu("Look-Up");
JMenuItem m1Frame4 = new JMenuItem("Check Fine");
JMenuItem m1Frame5 = new JMenuItem("Check Borrowed Books");
JMenuItem subM1 = new JMenuItem("Name");
JMenuItem subM2 = new JMenuItem("Student #");
open.add(m1Frame1);
open.add(m1Frame2);
open.add(m1Frame3);
open.add(m1Frame4);
open.add(m1Frame5);
m1Frame3.add(subM1);
m1Frame3.add(subM2);
mb.add(mb2);
JMenuItem m2Frame1 = new JMenuItem("Create");
JMenuItem m2Frame2 = new JMenuItem("Delete");
JMenu m2Frame3 = new JMenu("Look-Up");
JMenuItem subB1 = new JMenuItem("Title");
JMenuItem subB2 = new JMenuItem("Author");
JMenuItem subB3 = new JMenuItem("Category");
JMenuItem subB4 = new JMenuItem("ISBN");
JMenuItem m2Frame4 = new JMenuItem("Compare Star Rating");
JMenuItem m2Frame5 = new JMenuItem("Check If Checked Out");
JMenuItem m2Frame6 = new JMenuItem("Lost Book");
mb2.add(m2Frame1);
mb2.add(m2Frame2);
mb2.add(m2Frame3);
mb2.add(m2Frame4);
mb2.add(m2Frame5);
mb2.add(m2Frame6);
m2Frame3.add(subB1);
m2Frame3.add(subB2);
m2Frame3.add(subB3);
m2Frame3.add(subB4);
a.setJMenuBar(mb);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setSize(1280, 720);
a.setVisible(true);
b.setSize(600, 400);
m handler = new m();
pane.add(checkOutButton);
pane.add(returnButton);
add(pane);
checkOutButton.setVisible(false);
returnButton.setVisible(false);
checkOutButton.setBounds(60, 440, 220, 30);
returnButton.setBounds(60, 404, 100, 50);
checkOutButton.addActionListener(handler);
returnButton.addActionListener(handler);
}
public class m implements ActionListener, ItemListener {
public void actionPerformed(ActionEvent e) {
(e.getSource() == m1Frame1) {
a.setVisible(false);
setVisible(true);
checkOutButton.setVisible(true);
returnButton.setVisible(true);
}
}
public void itemStateChanged(ItemEvent e) {
}
}
public static void main(String[] args) {
m1 aa = new m1();
}
}
Ok, there are a few issues with your code, but I'll go over the two specifics that answer your question:
1) You're not adding your action listener to any of your MenuItems in your code. When I added your handler to the MenuItems using addActionListener(handler); It started triggering.
2) You're adding handler as the actionListener to two buttons that are invisible (and you've got other layout issues)
I don't know why my scroll bar in text area doesn't work. I found many solutions in internet, but no 1 helped for me.
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
I found that can't be Panel's layout Absolute, if I change It to Group layout the same.
What's wrong? Could you help me? Thank you.
UPDATED:
package lt.kvk.i3_2.kalasnikovas_stanislovas;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextPane;
import javax.swing.DropMode;
import javax.swing.JFormattedTextField;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JMenuItem;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import java.awt.SystemColor;
import java.awt.Font;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JScrollBar;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JToolBar;
public class KDVizualizuotas {
private JFrame frmInformacijaApieMuzikos;
private JTextField txtStilius;
private JTextArea textArea1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KDVizualizuotas window = new KDVizualizuotas();
window.frmInformacijaApieMuzikos.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public KDVizualizuotas() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmInformacijaApieMuzikos = new JFrame();
frmInformacijaApieMuzikos.setResizable(false);
frmInformacijaApieMuzikos.setIconImage(Toolkit.getDefaultToolkit().getImage(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/Sidebar-Music-Blue-icon.png")));
frmInformacijaApieMuzikos.setTitle("Muzikos stiliai");
frmInformacijaApieMuzikos.setBounds(100, 100, 262, 368);
frmInformacijaApieMuzikos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtStilius = new JTextField();
txtStilius.setBounds(10, 34, 128, 20);
txtStilius.setColumns(10);
JButton btnIekoti = new JButton("Ie\u0161koti");
btnIekoti.setBounds(146, 36, 89, 19);
btnIekoti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// textArea1.append(txtStilius.getText()+"\n");
// txtStilius.getText();
Scanner input = new Scanner(System.in);
try {
FileReader fr = new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Stiliai.txt");
BufferedReader br = new BufferedReader(fr);
String stiliuSarasas;
while((stiliuSarasas = br.readLine()) != null) {
System.out.println(stiliuSarasas);
textArea1.append(stiliuSarasas+"\n");
}
fr.close();
}
catch (IOException e) {
System.out.println("Error:" + e.toString());
}
}
});
JPanel panel = new JPanel();
panel.setBounds(10, 65, 224, 243);
panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panel.setBackground(SystemColor.text);
JLabel lblveskiteMuzikosStili = new JLabel("\u012Eveskite muzikos stili\u0173:");
lblveskiteMuzikosStili.setBounds(10, 14, 222, 14);
frmInformacijaApieMuzikos.getContentPane().setLayout(null);
panel.setLayout(null);
frmInformacijaApieMuzikos.getContentPane().add(panel);
JLabel lblInformacijaApieMuzikos = new JLabel("Informacija apie muzikos stili\u0173:");
lblInformacijaApieMuzikos.setBounds(12, 3, 190, 14);
panel.add(lblInformacijaApieMuzikos);
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
frmInformacijaApieMuzikos.getContentPane().add(txtStilius);
frmInformacijaApieMuzikos.getContentPane().add(btnIekoti);
frmInformacijaApieMuzikos.getContentPane().add(lblveskiteMuzikosStili);
JMenuBar menuBar = new JMenuBar();
frmInformacijaApieMuzikos.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mntmExit.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/exitas.png")));
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmHelp = new JMenuItem("Help");
mnHelp.add(mntmHelp);
JMenu mnAbout = new JMenu("About");
menuBar.add(mnAbout);
JMenuItem mntmAbout = new JMenuItem("About");
mntmAbout.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/questionmark.png")));
mnAbout.add(mntmAbout);
}
}
You need to add the component you want to be contained within the scroll pane to it.
You can do this via the JScrollPane's constructor or JScrollPane#setViewportView method
public class ScrollPaneTest {
public static void main(String[] args) {
new ScrollPaneTest();
}
public ScrollPaneTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JPanel bigPane = new JPanel();
bigPane.setBackground(Color.BLUE);
// This is not recommended, but is used for demonstration purposes
bigPane.setPreferredSize(new Dimension(1024, 768));
JScrollPane scrollPane = new JScrollPane(bigPane);
scrollPane.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Updated with proper layout
You should avoid null or absolute layouts, they will only hurt you in the long wrong.
You may also find How to use Scroll Panes of use
public class BadLayout {
public static void main(String[] args) {
new BadLayout();
}
public BadLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField searchField;
private JButton searchButton;
private JTextArea searchResults;
public TestPane() {
setLayout(new BorderLayout());
searchResults = new JTextArea();
searchResults.setLineWrap(true);
searchResults.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(searchResults);
JPanel results = new JPanel(new BorderLayout());
results.setBorder(new EmptyBorder(4, 8, 8, 8));
results.add(scrollPane);
add(results);
JPanel search = new JPanel(new GridBagLayout());
search.setBorder(new EmptyBorder(8, 8, 4, 8));
searchField = new JTextField(12);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.insets = new Insets(0, 0, 0, 4);
search.add(searchField, gbc);
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
search.add(searchButton, gbc);
add(search, BorderLayout.NORTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
}
}
Problem:
Update:
From the Java SE 6 API:
public JComboBox() Creates a JComboBox
with a default data model. The default
data model is an empty list of
objects. Use addItem to add items. By
default the first item in the data
model becomes selected.
So I changed to JComboBox(model) as the API says:
public JComboBox(ComboBoxModel aModel)
Creates a JComboBox that takes its
items from an existing ComboBoxModel.
Since the ComboBoxModel is provided, a
combo box created using this
constructor does not create a default
combo box model and may impact how the
insert, remove and add methods behave.
I tried the following:
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.setSelectedItem(null);
suggestionComboBox = new JComboBox(model);
suggestionComboBox.setModel(model);
But could not get it to work, the first item is still being selected.
Anyone that can come up with a working example would be very much appreciated.
Old part of the post:
I am using JComboBox, and tried using setSelectionIndex(-1) in my code (this code is placed in caretInvoke())
suggestionComboBox.removeAllItems();
for (int i = 0; i < suggestions.length; i++) {
suggestionComboBox.addItem(suggestions[i]);
}
suggestionComboBox.setSelectedIndex(-1);
suggestionComboBox.setEnabled(true);
This is the initial setting when it was added to a pane:
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
suggestionComboBox.addActionListener(new SuggestionComboBoxListener());
When the caretInvoke triggers the ComboBox initialisation, even before the user selects an element, the actionPerformed is already triggered (I tried a JOptionPane here):
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo1.png
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo2.png
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo3.png
The problem is: My program autoinserts the selected text when the user selects an element from the ComboBox. So without the user selecting anything, it is automatically inserted already.
How can I overcome the problem in this situation? Thanks.
Here is my SSCCE: (finally)
package components;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
public class Temp extends JFrame {
JTextPane textPane;
AbstractDocument doc;
JTextArea changeLog;
String newline = "\n";
private JComboBox suggestionComboBox;
private JPanel suggestionPanel;
private JLabel suggestionLabel;
private JButton openButton, saveButton, aboutButton;
public Temp() {
super("Snort Ruleset IDE");
//Create the text pane and configure it.
textPane = new JTextPane();
textPane.setCaretPosition(0);
textPane.setMargin(new Insets(5, 5, 5, 5));
StyledDocument styledDoc = textPane.getStyledDocument();
if (styledDoc instanceof AbstractDocument) {
doc = (AbstractDocument) styledDoc;
//doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));
} else {
System.err.println("Text pane's document isn't an AbstractDocument!");
System.exit(-1);
}
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(700, 350));
//Create the text area for the status log and configure it.
//changeLog = new JTextArea(10, 30);
//changeLog.setEditable(false);
//JScrollPane scrollPaneForLog = new JScrollPane(changeLog);
//Create a JPanel for the suggestion area
suggestionPanel = new JPanel(new BorderLayout());
suggestionPanel.setVisible(true);
suggestionLabel = new JLabel("Suggestion is not active at the moment.");
suggestionLabel.setPreferredSize(new Dimension(100, 50));
suggestionLabel.setMaximumSize(new Dimension(100, 50));
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
//suggestionComboBox.addActionListener(new SuggestionComboBoxListener());
suggestionComboBox.addItemListener(new SuggestionComboBoxListener());
//suggestionComboBox.setSelectedIndex(-1);
//add the suggestionLabel and suggestionComboBox to pane
suggestionPanel.add(suggestionLabel, BorderLayout.CENTER);
suggestionPanel.add(suggestionComboBox, BorderLayout.PAGE_END);
JScrollPane sp = new JScrollPane(suggestionPanel);
JScrollPane scrollPaneForSuggestion = new JScrollPane(suggestionPanel);
//Create a split pane for the change log and the text area.
JSplitPane splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
scrollPane, scrollPaneForSuggestion);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(1.0);
//Disables the moving of divider
splitPane.setEnabled(false);
//splitPane.setDividerLocation(splitPane.getHeight());
//splitPane.setPreferredSize(new Dimension(640,400));
//Create the status area.
JPanel statusPane = new JPanel(new GridLayout(1, 1));
CaretListenerLabel caretListenerLabel =
new CaretListenerLabel("Status: Ready");
statusPane.add(caretListenerLabel);
//Create the toolbar
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setRollover(true);
openButton = new JButton("Open Snort Ruleset");
toolBar.add(openButton);
saveButton = new JButton("Save Ruleset");
toolBar.add(saveButton);
toolBar.addSeparator();
aboutButton = new JButton("About");
toolBar.add(aboutButton);
//Add the components.
getContentPane().add(toolBar, BorderLayout.PAGE_START);
getContentPane().add(splitPane, BorderLayout.CENTER);
getContentPane().add(statusPane, BorderLayout.PAGE_END);
JMenu editMenu = createEditMenu();
JMenu styleMenu = createStyleMenu();
JMenuBar mb = new JMenuBar();
mb.add(editMenu);
mb.add(styleMenu);
setJMenuBar(mb);
//Put the initial text into the text pane.
//initDocument();
textPane.setCaretPosition(0);
//Start watching for undoable edits and caret changes.
textPane.addCaretListener(caretListenerLabel);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textPane.requestFocusInWindow();
}
});
}
//This listens for and reports caret movements.
protected class CaretListenerLabel extends JLabel
implements CaretListener {
public CaretListenerLabel(String label) {
super(label);
}
//Might not be invoked from the event dispatch thread.
public void caretUpdate(CaretEvent e) {
caretInvoke(e.getDot(), e.getMark());
}
protected void caretInvoke(final int dot, final int mark) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Rectangle caretCoords = textPane.modelToView(dot);
//Find suggestion
suggestionComboBox.removeAllItems();
for (int i = 0; i < 5; i++) {
suggestionComboBox.addItem(Integer.toString(i));
}
//suggestionComboBox.setSelectedItem(null);
suggestionComboBox.setEnabled(true);
suggestionLabel.setText("The following keywords are normally used as well. Click to use keyword(s). ");
//changeLog.setText("The following keywords are suggested to be used together: " + str);
} catch (BadLocationException ble) {
setText("caret: text position: " + dot + newline);
System.out.println("Bad Location Exception");
}
}
});
}
}
public class SuggestionComboBoxListener implements ItemListener {
//public void actionPerformed(ActionEvent e) {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox cb = (JComboBox)e.getSource();
String selection = (String) cb.getSelectedItem();
JOptionPane.showMessageDialog(null, "Item is selected", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
}
/*
* Menu Creation
*/
//Create the edit menu.
protected JMenu createEditMenu() {
JMenu menu = new JMenu("Edit");
return menu;
}
protected JMenu createStyleMenu() {
JMenu menu = new JMenu("Style");
return menu;
}
private static void createAndShowGUI() {
//Create and set up the window.
final Temp frame = new Temp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//The standard main method.
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
You need to remove the ItemListener before you make any changes to the combo-box and add it back when you are done.
Something like this:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Suggestions {
private JFrame frame;
private JTextPane textPane;
private JComboBox suggestionComboBox;
private SuggestionComboBoxListener selectionListener;
public Suggestions() {
frame = new JFrame("Snort Ruleset IDE");
textPane = new JTextPane();
textPane.setCaretPosition(0);
textPane.setMargin(new Insets(5, 5, 5, 5));
textPane.addCaretListener(new SuggestionCaretListener());
JScrollPane textEntryScrollPane = new JScrollPane(textPane);
textEntryScrollPane.setPreferredSize(new Dimension(300, 400));
selectionListener = new SuggestionComboBoxListener(frame);
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
suggestionComboBox.addItemListener(selectionListener);
JPanel suggestionPanel = new JPanel(new BorderLayout());
suggestionPanel.add(suggestionComboBox, BorderLayout.PAGE_END);
frame.getContentPane().add(textEntryScrollPane, BorderLayout.NORTH);
frame.getContentPane().add(suggestionPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private final class SuggestionCaretListener implements CaretListener {
#Override
public void caretUpdate(CaretEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generateSuggestions();
}
});
}
}
public static final class SuggestionComboBoxListener implements ItemListener {
Component parent;
public SuggestionComboBoxListener(Component parent) {
this.parent = parent;
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox cb = (JComboBox) e.getSource();
String selection = (String) cb.getSelectedItem();
JOptionPane.showMessageDialog(parent, "The selected item is: " + selection, "Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
void generateSuggestions() {
suggestionComboBox.removeItemListener(selectionListener);
suggestionComboBox.removeAllItems();
for (int i = 0; i < 5; i++) {
suggestionComboBox.addItem(Integer.toString(i));
}
suggestionComboBox.setEnabled(true);
suggestionComboBox.addItemListener(selectionListener);
}
public static void main(String[] args) {
new Suggestions();
}
}
BTW, what you posted is not an SSCCE it is a dump of your code. An SSCCE should only have enough code to reproduce the issue you are experiencing.
use
setSelectedItem(null);
Please try with ItemListener instead of ActionListener.
if You want that after 1st entry you made and immediately you combox is empty then just write down the under mentioned code which is:
jComboBox1.setSelectedIndex(0);
and your combox will reset Automatically