Toggling text wrap in a JTextpane - java

How would I go about toggling text wrap on a JTextpane?
public JFrame mainjFrame = new JFrame("Text Editor");
public JTextPane mainJTextPane = new JTextPane();
public JScrollPane mainJScrollPane = new JScrollPane(mainJTextPane);
mainjFrame.add(mainJScrollPane);

See No Wrap Text Pane.
Edit:
Well, if you want to toggle the behaviour, then you would also need to toggle the getScrollableTracksViewportWidth() value. See Scrollable Panel. You should be able to toggle between FIT and STRETCH.

package test;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class TestVisual extends JFrame {
private boolean wrapped;
private JButton toggleButton = null;
private JTextPane textPane = null;
private JPanel noWrapPanel = null;
private JScrollPane scrollPane = null;
public TestVisual() {
super();
init();
}
public void init() {
this.setSize(300, 200);
this.setLayout(new BorderLayout());
wrapped = false;
textPane = new JTextPane();
noWrapPanel = new JPanel( new BorderLayout() );
noWrapPanel.add( textPane );
scrollPane = new JScrollPane( noWrapPanel );
toggleButton = new JButton("wrap");
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (wrapped == true){
scrollPane.setViewportView(noWrapPanel);
noWrapPanel.add(textPane);
toggleButton.setText("wrap");
wrapped = false;
}else {
scrollPane.setViewportView(textPane);
toggleButton.setText("unWrap");
wrapped = true;
}
}
});
this.add(scrollPane, BorderLayout.CENTER);
this.add(toggleButton, BorderLayout.NORTH);
}
}
I don't know any other way for what you are looking for..
But this is working well.
( Based on camickr's answer.. +1 )

Related

Oppening a new JFrame with a JButton click [duplicate]

I want to open a new JFrame by clicking a button (btnAdd); I have tried to create an actionlistener but I am having no luck; the code runs but nothing happens when the button is clicked. The methods in question are the last two in the following code. Any help is much appreciated!
package AdvancedWeatherApp;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionListener;
import weatherforecast.FetchWeatherForecast;
public class MainFrame extends JFrame implements ListSelectionListener {
private boolean initialized = false;
private Actions actions = new Actions();
private javax.swing.JScrollPane jspFavouritesList = new javax.swing.JScrollPane();
private javax.swing.DefaultListModel<String> listModel = new javax.swing.DefaultListModel<String>();
private javax.swing.JList<String> favouritesList = new javax.swing.JList<String>(
listModel);
private javax.swing.JLabel lblAcknowledgement = new javax.swing.JLabel();
private javax.swing.JLabel lblTitle = new javax.swing.JLabel();
private javax.swing.JButton btnAdd = new javax.swing.JButton();
private javax.swing.JButton btnRemove = new javax.swing.JButton();
public void initialize() {
initializeGui();
initializeEvents();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
/**
*
*/
private void initializeGui() {
if (initialized)
return;
initialized = true;
this.setSize(500, 400);
Dimension windowSize = this.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(screenSize.width / 2 - windowSize.width / 2,
screenSize.height / 2 - windowSize.height / 2);
Container pane = this.getContentPane();
pane.setLayout(new BorderLayout());
setLayout(new BorderLayout());
setTitle("Favourite Weather Locations");
JPanel jpSouth = new JPanel();
jpSouth.setLayout(new FlowLayout());
JPanel jpNorth = new JPanel();
jpNorth.setLayout(new FlowLayout());
JPanel jpCenter = new JPanel();
jpCenter.setLayout(new BoxLayout(jpCenter, BoxLayout.PAGE_AXIS));
JPanel jpEast = new JPanel();
JPanel jpWest = new JPanel();
getContentPane().setBackground(Color.WHITE);
jpEast.setBackground(Color.WHITE);
jpWest.setBackground(Color.WHITE);
jpCenter.setBackground(Color.WHITE);
getContentPane().add(jspFavouritesList);
jpCenter.add(jspFavouritesList);
jspFavouritesList.setViewportView(favouritesList);
favouritesList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
favouritesList.addListSelectionListener(this);
jpCenter.add(btnAdd);
jpCenter.add(btnRemove);
jpCenter.setAlignmentY(CENTER_ALIGNMENT);
btnAdd.setText("Add Location");
btnAdd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnAdd.setFont(new Font("Calibri", Font.PLAIN, 18));
jpCenter.add(btnRemove);
btnRemove.setText("Remove Location");
btnRemove.setAlignmentX(Component.CENTER_ALIGNMENT);
btnRemove.setFont(new Font("Calibri", Font.PLAIN, 18));
getContentPane().add(jpEast, BorderLayout.EAST);
getContentPane().add(jpWest, BorderLayout.WEST);
getContentPane().add(jpSouth);
jpSouth.add(lblAcknowledgement);
add(lblAcknowledgement, BorderLayout.SOUTH);
lblAcknowledgement.setText(FetchWeatherForecast.getAcknowledgement());
lblAcknowledgement.setHorizontalAlignment(SwingConstants.CENTER);
lblAcknowledgement.setFont(new Font("Tahoma", Font.ITALIC, 12));
getContentPane().add(jpNorth);
jpNorth.add(lblTitle);
add(lblTitle, BorderLayout.NORTH);
lblTitle.setText("Your Favourite Locations");
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setFont(new Font("Calibri", Font.PLAIN, 32));
lblTitle.setForeground(Color.DARK_GRAY);
getContentPane().add(jpCenter);
}
private void initializeEvents() {
// TODO: Add action listeners, etc
}
public class Actions implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
command = command == null ? "" : command;
// TODO: add if...if else... for action commands
}
}
public void dispose() {
// TODO: Save settings
// super.dispose();
System.exit(0);
}
public void setVisible(boolean b) {
initialize();
super.setVisible(b);
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
public void actionPerformed(ActionEvent evt){
if (evt.getSource() == btnAdd) {
showNewFrame();
//OPEN THE SEARCH WINDOW
}
}
private void showNewFrame() {
JFrame frame = new JFrame("Search Window" );
frame.setSize( 500,120 );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
Although you have implemented the actionPerformed method as per the ActionListener interface, you class is not of that that type as you haven't implemented the interface. Once you implement that interface and register it with the JButton btnAdd,
btnAdd.addActionListener(this);
the method will be called.
A more compact alternative might be to use an anonymous interface:
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle button ActionEvent & display dialog...
}
});
Side notes:
Using more than one JFrame in an application creates a lot of overhead for managing updates that may need to exist between frames. The preferred approach is to
use a modal JDialog if another window is required. This is discussed more here.
Use this :
btnAdd.addActionListener(this);
#Override
public void actionPerformed(ActionEvent e)
{
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
Type this inside the button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
ActionListener ActList = new ActionListener();
ActList.setVisible(true);
}
see my last line
{
ActList.setVisible(true);
}

Menubar not added in a java split pane

I have written a small test program which creates a split pane in which one of the pane's is a text area. I have added a meubar and menuitems to the pane but i donot see them in the gui that is created.
Could anyone pls point out what the wrong thing did i do over here in the below program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenuBar;
import java.util.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.io.IOException;
//SplitPaneDemo itself is not a visible component.
public class SplitPaneDemo extends JFrame
implements ActionListener {
private JTextArea ta;
private JMenuBar menuB;
private JMenu dbM;
private JMenuItem cnadb,bsmdb,cdmdb;
private JLabel picture;
private JSplitPane splitPane;
public SplitPaneDemo() {
ta = new JTextArea(); //textarea
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke )
{
int code = ke.getKeyCode();
int modifiers = ke.getModifiers();
if(code == KeyEvent.VK_ENTER && modifiers == KeyEvent.CTRL_MASK)
{
System.out.println("cmd in table:");
}
}
});
JScrollPane taPane = new JScrollPane(ta);
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
JScrollPane pictureScrollPane = new JScrollPane(picture);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
taPane, pictureScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(450);
//Provide minimum sizes for the two components in the split pane.
Dimension minimumSize = new Dimension(100, 100);
taPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
//Provide a preferred size for the split pane.
splitPane.setPreferredSize(new Dimension(900, 900));
menuB = new JMenuBar(); //menubar
dbM = new JMenu("DB"); //file menu
cnadb = new JMenuItem("CNA");
bsmdb = new JMenuItem("BSM");
cdmdb = new JMenuItem("CDM");
setJMenuBar(menuB);
menuB.add(dbM);
dbM.add(cnadb);
dbM.add(bsmdb);
dbM.add(cdmdb);
cnadb.addActionListener(this);
bsmdb.addActionListener(this);
cdmdb.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
public void valueChanged(ListSelectionEvent e) {
}
public JSplitPane getSplitPane() {
return splitPane;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SplitPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
frame.getContentPane().add(splitPaneDemo.getSplitPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You add the JMenuBar in your SplitPaneDemo class, but when you actually call createAndShowGUI, you make a new JFrame and only add the SplitPane to it with the call to getSplitPane. This new frame has no knowledge of the menu bar.
If you are extending JFrame in SplitPaneDemo, why not use that to make the frame for your gui?

JLabel misplaced after adding JPanel

I'm almost blind after reading lots of java swing articles, and still can not get panel to work.
When i add 2 JLabels, they are nicely aligned to left, with 5px padding defined by EmptyBorder, just as i want them to be.
I found that after adding ProgressBar with extra border for padding, does not work as expected, added 1 more panel, where i add ProgressBar. Progress looks good, but all my labels are displaced.
And finally it look like this (RED background is for debug, to see how JPanel draws):
Question1: How to fix this?
Question2: Is it standard approach for swing to place panel inside of other panel with other panels just to get formating i want?
Source:
public class AppInitProgressDialog {
private static final int VIEW_PADDING_VAL = 5;
private static final Border viewPaddingBorder = new EmptyBorder( VIEW_PADDING_VAL, VIEW_PADDING_VAL, VIEW_PADDING_VAL, VIEW_PADDING_VAL );
private JPanel view; // Dialog view
private JPanel panel;
private JPanel progressPanel;
private JLabel title;
private JLabel progressDesc;
private JProgressBar progressBar;
private void initPanel( int w, int h ) {
view = new JPanel();
view.setBorder( BorderFactory.createRaisedSoftBevelBorder() );
view.setBackground( Color.LIGHT_GRAY );
view.setSize( w, h );
view.setLayout( new BorderLayout() );
panel = new JPanel();
panel.setBorder( viewPaddingBorder );
panel.setLayout( new BoxLayout(panel, BoxLayout.PAGE_AXIS) );
//panel.setLayout( new SpringLayout() );
panel.setOpaque( false );
JFrame parent = AppContext.getMe().getAppWindow().getFrame();
int posx = (parent.getWidth() - w)/2;
int posy = (parent.getHeight() - h)/2;
view.add( panel, BorderLayout.CENTER );
view.setLocation( posx, posy );
}
private void initTitle() {
title = new JLabel( "Progress title" );
title.setAlignmentX( JComponent.LEFT_ALIGNMENT );
panel.add(title);
}
private void initProgress() {
progressPanel = new JPanel( new BorderLayout() );
progressPanel.setBackground( Color.LIGHT_GRAY );
progressPanel.setBorder( new EmptyBorder( 15, 30, 15, 30) );
progressPanel.setBackground( Color.RED );
progressBar = new JProgressBar(0, 10000);
progressBar.setStringPainted(true);
progressBar.setAlignmentX( JComponent.LEFT_ALIGNMENT );
progressPanel.add(progressBar);
panel.add( progressPanel );
progressDesc = new JLabel( "Progress description" );
panel.add(progressDesc);
}
public AppInitProgressDialog() {
initPanel( 400, 100 );
initTitle();
initProgress();
}
public JComponent getView() {
return view;
}
}
Alternatively, you can use BorderLayout for panel:
panel = new JPanel(new BorderLayout());
...
panel.add(title, BorderLayout.NORTH);
...
panel.add(progressPanel); // default CENTER
...
panel.add(progressDesc, BorderLayout.SOUTH);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.EmptyBorder;
/**
* #see http://stackoverflow.com/a/16837816/230513
*/
public class Test {
private JFrame f = new JFrame("Test");
private void display() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new AppInitProgressDialog().getView());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
class AppInitProgressDialog {
private static final int VIEW_PADDING_VAL = 5;
private JPanel view; // Dialog view
private JPanel panel;
private JPanel progressPanel;
private JLabel title;
private JLabel progressDesc;
private JProgressBar progressBar;
private void initPanel(int w, int h) {
view = new JPanel();
view.setBorder(BorderFactory.createRaisedBevelBorder());
view.setBackground(Color.LIGHT_GRAY);
view.setSize(w, h);
view.setLayout(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
panel.setOpaque(false);
view.add(panel, BorderLayout.CENTER);
}
private void initTitle() {
title = new JLabel("Progress title");
title.setAlignmentX(JComponent.LEFT_ALIGNMENT);
panel.add(title, BorderLayout.NORTH);
}
private void initProgress() {
progressPanel = new JPanel(new BorderLayout());
progressPanel.setBackground(Color.LIGHT_GRAY);
progressPanel.setBorder(new EmptyBorder(15, 30, 15, 30));
progressPanel.setBackground(Color.RED);
progressBar = new JProgressBar(0, 10000);
progressBar.setStringPainted(true);
progressBar.setAlignmentX(JComponent.LEFT_ALIGNMENT);
progressPanel.add(progressBar);
panel.add(progressPanel);
progressDesc = new JLabel("Progress description");
panel.add(progressDesc, BorderLayout.SOUTH);
}
public AppInitProgressDialog() {
initPanel(400, 100);
initTitle();
initProgress();
}
public JComponent getView() {
return view;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}
Use Layout Managers rather than just adding panels to each other. Specifically in your case I think you can use GridLayout.
panel.setLayout(new GridLayout(1,1,0,0));
Fore more details on layout refer to this tutorial.

JTabbedPane perform action above and below

I want to put JTabbedPane in the middle,and clicking any tab I want to change will reflect in both above and below panel of tabbedpane.
I tried it but it works only on the below panel.
How to overcome from this problem? Please help me.
Thanks in advance.
Here is my code:
jTabbedPane1 = new javax.swing.JTabbedPane();
jTabbedPane1.addTab("Daily Market", jScrollPane1);
jTabbedPane1.addTab("Weekly Market", jScrollPane2);
On assumption that you want to change something in the panels above and below your tabbed pane. Sample code changing text of a label in top and bottom panel below:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestJTabbedPane extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private void init(){
this.setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
final JLabel topLabel = new JLabel("North");
topPanel.add(topLabel);
this.add(topPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel firstTabCont = new JPanel();
firstTabCont.add(new JLabel("First"));
tabbedPane.addTab("First", firstTabCont);
JPanel secondTabCont = new JPanel();
secondTabCont.add(new JLabel("Second"));
tabbedPane.addTab("Second", secondTabCont);
this.add(tabbedPane, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
final JLabel bottomLabel = new JLabel("South");
bottomPanel.add(bottomLabel);
this.add(bottomPanel, BorderLayout.SOUTH);
tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent evt) {
JTabbedPane pane = (JTabbedPane)evt.getSource();
int selectedIndex = pane.getSelectedIndex();
if(selectedIndex == 0){
topLabel.setText("");
topLabel.setText("Hi");
bottomLabel.setText("");
bottomLabel.setText("Bye");
} else {
topLabel.setText("");
topLabel.setText("Bye");
bottomLabel.setText("");
bottomLabel.setText("Hi");
}
}
});
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new TestJTabbedPane().init();
}
}

How to configure JComboBox not to select FIRST element when created?

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

Categories

Resources