Make TitledBorder editable upon double click - java

This is an extension of : Make a TitledBorder title editable
To be more specific, I want the TitledBorder to be editable when the title is double clicked. I'm placing the Border around a java Box that uses BoxLayout. The double click would preferably open a JTextField right there, but if that cannot be done, opening another window to edit the title is acceptable.
TitledBorder editableBorder = new TitledBorder(editableString);
editableBorder.setTitleJustification(TitledBorder.CENTER);
Box containerBox = new Box(BoxLayout.PAGE_AXIS);
containerBox.setBorder(new CompoundBorder(editableBorder, new EmptyBorder(10, 0, 10, 0)));
Box insideBox = new Box(BoxLayout.PAGE_AXIS);
insideBox.add(new JLabel(new ImageIcon(new BufferedImage(200,40,BufferedImage.TYPE_INT_RGB))));
containerBox.add(insideBox);

Here is an example. The MouseListener uses a JPopupMenu to display the text field. This means you can cancel editing by using the Escape key.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitledBorderListener extends MouseAdapter
{
private JPopupMenu editPopup;
private JTextField editTextField;
private TitledBorder titledBorder;
#Override
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount != 2)
return;
// Edit the border on a double click
JComponent component = (JComponent)e.getSource();
Border border = component.getBorder();
if (border instanceof TitledBorder)
{
titledBorder = (TitledBorder)border;
FontMetrics fm = component.getFontMetrics( titledBorder.getTitleFont() );
int titleWidth = fm.stringWidth(titledBorder.getTitle()) + 20;
Rectangle bounds = new Rectangle(0, 0, titleWidth, fm.getHeight());
if (bounds.contains(e.getPoint()))
{
if (editPopup == null)
createEditPopup();
// Position the popup editor over top of the title
editTextField.setText( titledBorder.getTitle() );
Dimension d = editTextField.getPreferredSize();
d.width = titleWidth;
editPopup.setPreferredSize(d);
editPopup.show(component, 0, 0);
editTextField.selectAll();
editTextField.requestFocusInWindow();
}
}
}
private void createEditPopup()
{
editTextField = new JTextField();
// Add an Action to the text field to save the new title text
editTextField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String value = editTextField.getText();
titledBorder.setTitle( value );
editPopup.setVisible(false);
editPopup.getInvoker().revalidate();
editPopup.getInvoker().repaint();
}
});
// Add the editor to the popup
editPopup = new JPopupMenu();
editPopup.setBorder( new EmptyBorder(0, 0, 0, 0) );
editPopup.add(editTextField);
}
private static void createAndShowUI()
{
JPanel panel = new JPanel();
panel.setBorder( new TitledBorder("Double Click to Edit") );
panel.addMouseListener( new TitledBorderListener() );
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Related

Add jbutton TextArea to the jscrollpane

I want a implementation like this.
JscrollPane's panel is divided into two columns.
First column has jtextarea.
Second column should have a jbutton with Ok text.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestScrollPane extends JFrame {
JPanel newScrollPanel;
JPanel leftPanel;
JScrollPane scrollPane;
JEditorPane editorPane;
JButton button;
public TestScrollPane() {
leftPanel = new JPanel();
newScrollPanel = new JPanel();
editorPane = new JEditorPane();
scrollPane = new JScrollPane(editorPane);
button = new JButton("ok");
leftPanel.setBackground(Color.WHITE);
leftPanel.add(button);
editorPane.setEditable(false);
scrollPane.setPreferredSize(new Dimension(250, 140));
scrollPane.setMinimumSize(new Dimension(10, 10));
String text = "";
for(int i=0;i<50;i++){
text = text + "line " + i + "\n";
}
editorPane.setText(text);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
newScrollPanel.setLayout(new BoxLayout(newScrollPanel, BoxLayout.X_AXIS));
newScrollPanel.add(editorPane);
newScrollPanel.add(leftPanel);
scrollPane.getViewport().add(newScrollPanel);
addComponentListener(new ComponentAdapter() {
#Override
public void componentHidden(ComponentEvent evt) { }
#Override
public void componentShown(ComponentEvent evt) {
changePane();
}
});
this.add(scrollPane);
setFrame();
}
private void changePane() {
leftPanel.setLayout(null);
Insets insets = leftPanel.getInsets();
Dimension size = button.getPreferredSize();
int buttonY = (int) (insets.top + scrollPane.getHeight() - size.getHeight());
button.setPreferredSize(size);
leftPanel.setPreferredSize(new Dimension(((int) size.getWidth()), editorPane.getHeight()));
button.setBounds(0, buttonY, size.width, size.height);
}
void setFrame(){
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
TestScrollPane testScrollPane = new TestScrollPane();
}
});
}
}
I have two questions.
In my class the ok button is not placed in the correct place. when scroll bar mover is at the top corner , ok button should be in the right bottom corner of the visible area. Ok button should be completely visible. In my code only visible a part of the button. Is there any issue with determining the Y coordinates ?
int buttonY = (int) (insets.top + scrollPane.getHeight() - size.getHeight());
Even though the scroll is moved, ok button should not move with the scroll bar. Is that possible to implement ?

JPanel titled border with tooltip text for the title

I am using setBorder(BorderFactory.createTitledBorder(title)) in my JPanel in order to group its content in a rectangle with a title above it. How can I set a tooltip text for the title?
A possible approach is nesting components. As Borders are not components they can not have tooltips, but you can have a component with the sole purpose of holding border and the tooltip:
JPanel outer = new JPanel();
outer.setBorder(BorderFactory.createTitledBorder("Title"));
outer.setToolTipText("sample text");
JPanel inner = new JPanel();
outer.add(inner);
and then use inner as the container for the components you want to group.
You can override the getToolTipText() method of the panel to check if the mouse of over the title text:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitledBorderTest
{
private static void createAndShowUI()
{
UIManager.getDefaults().put("TitledBorder.titleColor", Color.RED);
Border lowerEtched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
TitledBorder title = BorderFactory.createTitledBorder(lowerEtched, "Title");
// title.setTitleJustification(TitledBorder.RIGHT);
Font titleFont = UIManager.getFont("TitledBorder.font");
title.setTitleFont( titleFont.deriveFont(Font.ITALIC + Font.BOLD) );
JPanel panel = new JPanel()
{
#Override
public String getToolTipText(MouseEvent e)
{
Border border = getBorder();
if (border instanceof TitledBorder)
{
TitledBorder tb = (TitledBorder)border;
FontMetrics fm = getFontMetrics( tb.getTitleFont() );
int titleWidth = fm.stringWidth(tb.getTitle()) + 20;
Rectangle bounds = new Rectangle(0, 0, titleWidth, fm.getHeight());
return bounds.contains(e.getPoint()) ? super.getToolTipText() : null;
}
return super.getToolTipText(e);
}
};
panel.setBorder( title );
panel.setToolTipText("Title With ToolTip");
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
This code assumes the title is on the left. If you want the title on the right then you would need to adjust the X value of the text bounds.
I don't think you can add setToolTipText to TitledBorder. you can provide tooltip for JComponent but TitledBorder is not derived from JComponent.
You can try to use JPanel instead:
ToolTipManager.sharedInstance().registerComponent(new JPanel());
//ToolTipManager.sharedInstance().setDismissDelay(800000);
TollTip isn't right Components for experiments, all goog workaround for popup or tooltips are based on JWindow/ undecorated JDialog
maybe not necessary, keys in UIManager are accesible, but in this case all TollTips has the same settings
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.*;
public class ColoredToolTipExample extends JFrame {
private static final long serialVersionUID = 1L;
public ColoredToolTipExample() {
Border line, raisedbevel, loweredbevel, title, empty;
line = BorderFactory.createLineBorder(Color.black);
raisedbevel = BorderFactory.createRaisedBevelBorder();
loweredbevel = BorderFactory.createLoweredBevelBorder();
title = BorderFactory.createTitledBorder("");
empty = BorderFactory.createEmptyBorder(1, 1, 1, 1);
Border compound;
compound = BorderFactory.createCompoundBorder(empty, line);
UIManager.put("ToolTip.foreground", new ColorUIResource(Color.red));
UIManager.put("ToolTip.background", new ColorUIResource(Color.yellow));
UIManager.put("ToolTip.font", new FontUIResource(new Font("Verdana", Font.PLAIN, 18)));
UIManager.put("ToolTip.border", new BorderUIResource(compound));
JButton button = new JButton("Hello, world");
button.setToolTipText("<html> - myText <br> - myText <br> - myText <br>");
getContentPane().add(button);
JFrame frame = new JFrame("Colored ToolTip Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ColoredToolTipExample();
}
});
}
}

Is there anyway to add text inside picture in JFrame?

EDIT:Damn, my english is a bit off. I meant to ask how to add text "inside" picture not over(above) it , with the text be at the center of picture.
thank you for previous helps anyway :).
One way is to use OverlayLayout. For the text to be at the center of the image in both axes an alignment value of 0.5 should be used for both X & Y for both JLabel components shown below.
public class OverlayLabelApp {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Overlay App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
LayoutManager overlay = new OverlayLayout(panel);
panel.setLayout(overlay);
JLabel label1 = new JLabel("Centered Text");
label1.setForeground(Color.GREEN);
label1.setFont(new Font("SansSerif", Font.BOLD, 16));
label1.setAlignmentX(0.5f);
label1.setAlignmentY(0.5f);
panel.add(label1);
JLabel label2 =
new JLabel(new ImageIcon(OverlayLabelApp.class.getResource("/images/sunset.png"))); label2.setAlignmentX(0.5f);
label2.setAlignmentY(0.5f);
panel.add(label2);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
}
}
Sure. Paint the text direct to the picture. Display the picture in a label.
E.G.
How to edit a text that is converted into image?
How to resize text in java
Of course, if you want it 'simpler' there are other options. One is OverlayLayout as described by #Reimeus. Here is another. It utilizes the fact that we can set a layout for a label, and show components within it. This technique was popularized by #mKorbel.
import java.awt.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
class TextOnImage {
public static void main(String[] args) throws Exception {
URL url = new URL("http://i.stack.imgur.com/zJ8am.png");
final BufferedImage image = ImageIO.read(url);
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
JLabel l = new JLabel(new ImageIcon(image));
l.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel text = new JLabel("Hi!");
l.add(text);
JOptionPane.showMessageDialog(null, l);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
with the text be at the center of picture.
4 more approaches. The first is the easiest and sounds like what you want:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class LabelImageText extends JPanel
{
public LabelImageText()
{
JLabel label1 = new JLabel( new ColorIcon(Color.ORANGE, 100, 100) );
label1.setText( "Easy Way" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
add( label1 );
//
JLabel label2 = new JLabel( new ColorIcon(Color.YELLOW, 200, 150) );
label2.setLayout( new BoxLayout(label2, BoxLayout.Y_AXIS) );
add( label2 );
JLabel text = new JLabel( "More Control" );
text.setAlignmentX(JLabel.CENTER_ALIGNMENT);
label2.add( Box.createVerticalGlue() );
label2.add( text );
label2.add( Box.createVerticalStrut(10) );
//
JLabel label3 = new JLabel( new ColorIcon(Color.GREEN, 200, 150) );
add( label3 );
JLabel text3 = new JLabel();
text3.setText("<html><center>Text<br>over<br>Image<center></html>");
text3.setLocation(20, 20);
text3.setSize(text3.getPreferredSize());
label3.add( text3 );
//
JLabel label4 = new JLabel( new ColorIcon(Color.CYAN, 200, 150) );
add( label4 );
JTextPane textPane = new JTextPane();
textPane.setText("Add some text that will wrap at your preferred width");
textPane.setEditable( false );
textPane.setOpaque(false);
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
StyledDocument doc = textPane.getStyledDocument();
doc.setParagraphAttributes(0, doc.getLength(), center, false);
textPane.setBounds(20, 20, 75, 100);
label4.add( textPane );
}
public static class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("LabelImageText");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new LabelImageText() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Add components to JDialog

When I run this, an empty title bar is displayed. I just want to be able to see the components and work from there, but nothing is displayed. The dialog is designed to allow the user to select a color by moving sliders, then return to color to the main page.
import java.awt.*;
import javax.swing.*;
public class ColourDialog extends JDialog
{
String colorNames[] = {"Red: ", "Green: ", "Blue: "};
Label labels[] = new Label[3];
JSlider slider[]= new JSlider[3];
Label lb;
static ColourDialog d;
public void ColourDialog()
{
setModal(true);
Container c = getContentPane();
c.setLayout(new BorderLayout());
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(0, 1));
for (int i = 0; i < slider.length; i++)
{
labels[i] = new Label(colorNames[i] + 255);
sliderPanel.add(labels[i]);
slider[i] = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
slider[i].setMinorTickSpacing(10);
slider[i].setMajorTickSpacing(50);
slider[i].setPaintTicks(true);
slider[i].setPaintLabels(true);
sliderPanel.add(slider[i]);
//slider[i].addChangeListener(this);
}
lb = new Label("Colour");
c.add(sliderPanel, BorderLayout.CENTER);
c.add(lb, BorderLayout.SOUTH);
setSize(500, 450);
setLocation(200,200);
setTitle("Colour Dialog");
}
public static Color showDialog()
{
if (d == null)
d = new ColourDialog();
d.show();
//return new Color(red,green,blue);
return new Color(0,0,0);
}
public static void main(String args[])
{
ColourDialog.showDialog();
}
}
I think that you have look at JColorChooser, this JComponent can returns selected Color
there I can't fout out correct definitions and initializations for JSlider
EDIT
there are lots of mistakes starting with extends JDialog end with public static Color showDialog(), that returns empty container typos with initializations for ColourDialog()
import java.awt.*;
import javax.swing.*;
public class ColourDialog {
private JDialog dialog = new JDialog();
private String colorNames[] = {"Red: ", "Green: ", "Blue: "};
private Label labels[] = new Label[3];
private JSlider slider[] = new JSlider[3];
private Label lb;
public ColourDialog() {
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(0, 1));
for (int i = 0; i < slider.length; i++) {
labels[i] = new Label(colorNames[i] + 255);
sliderPanel.add(labels[i]);
slider[i] = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
slider[i].setMinorTickSpacing(10);
slider[i].setMajorTickSpacing(50);
slider[i].setPaintTicks(true);
slider[i].setPaintLabels(true);
sliderPanel.add(slider[i]);
}
lb = new Label("Colour");
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setModal(true);
dialog.add(sliderPanel, BorderLayout.CENTER);
dialog.add(lb, BorderLayout.SOUTH);
dialog.pack();
dialog.setLocation(200, 200);
dialog.setTitle("Colour Dialog");
dialog.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ColourDialog colourDialog = new ColourDialog();
}
});
}
}
I think it might be because you say "public void ColourDialog()" this is an invalid constructor. Try getting rid of the "void" and try again.
You never call the method ColorDialog(). This is a good spot to mention "start methods with a lower case letter). To fix you code:
Change:
d = new ColourDialog();
To:
d = new ColourDialog();
d.ColourDialog();

JRadioButton Will not appear until Mouse over

import java.awt.Frame;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class IndicatorWindow implements ItemListener {
JRadioButton RMA, EMA, SMA, Williams, Stochastic;
JPanel IndPan, RadioPanel, title;
JLabel Lab;
JButton OK;
public JPanel createContentPane() {
JPanel GUI = new JPanel();
GUI.setLayout(null);
title = new JPanel();
title.setLayout(null);
title.setLocation(0, 0);
title.setSize(500, 145);
GUI.add(title);
Lab = new JLabel("Please Select Indicator Type");
Lab.setLocation(5, 0);
Lab.setSize(200, 30);
title.add(Lab);
ButtonGroup bg1 = new ButtonGroup();
RadioPanel = new JPanel();
RadioPanel.setLayout(null);
RadioPanel.setLocation(10, 30);
RadioPanel.setSize(190, 220);
GUI.add(RadioPanel);
RMA = new JRadioButton("RMA");
RMA.setLocation(0, 0);
RMA.addItemListener(this);
RMA.setSize(110, 20);
bg1.add(RMA);
RadioPanel.add(RMA);
EMA = new JRadioButton("EMA");
EMA.setLocation(0, 30);
EMA.addItemListener(this);
EMA.setSize(110, 20);
bg1.add(EMA);
RadioPanel.add(EMA);
SMA = new JRadioButton("SMA");
SMA.setLocation(0, 60);
SMA.addItemListener(this);
SMA.setSize(110, 20);
bg1.add(SMA);
RadioPanel.add(SMA);
Stochastic = new JRadioButton("Stochastic");
Stochastic.setLocation(0, 90);
Stochastic.addItemListener(this);
Stochastic.setSize(110, 20);
bg1.add(Stochastic);
RadioPanel.add(Stochastic);
Williams = new JRadioButton("Williams");
Williams.setLocation(0, 120);
Williams.addItemListener(this);
Williams.setSize(110, 20);
bg1.add(Williams);
RadioPanel.add(Williams);
OK = new JButton();
OK.setText("Confirm");
OK.setLocation(45, 150);
OK.addItemListener(this);
OK.setSize(90, 30);
RadioPanel.add(OK);
//GUI.setOpaque(true);
return GUI;
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == RMA) {
System.out.print("Browse");
} else if (source == EMA) {
System.out.print("EMA");
} else if (source == SMA) {
System.out.print("SMA");
} else if (source == Williams) {
System.out.print("Williams");
} else if (source == Stochastic) {
System.out.print("Stochastic");
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Indicators");
IndicatorWindow ind = new IndicatorWindow();
frame.setContentPane(ind.createContentPane());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(200, 250);
frame.setLayout(null);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setState(Frame.NORMAL);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
My problem is that when i compile and run this code, the jFrame appears but there is only one problem, 3 JRadioButtons dont appear until you put your mouse over them. The RMA and Williams radiobuttons appear, the 3 in the middle do not though, any thoughts on why this is?
http://i.stack.imgur.com/gNnIb.jpg
You should be using layout managers. People think using a "null layout" is easier, but it is not and you are more prone to having errors with your code. Layout managers will position and size components properly to make sure all components are displayed. Sometimes you even use multiple different layout managers to achieve the layout you desire.
Your problem in this case is that you have two components occupying the same space in your container. So one component gets painted over top of the other. After you mouse over your radio button, the button is repainted because of the rollover effect of the button. However, now try resizing the frame and the radio buttons will disappear because all the components are repainted and the component is painted over top of the buttons again.
The following line of code is the problem:
// title.setSize(500, 145);
title.setSize(500, 20);
But the real solution is to rewrite the code and use layout managers. While you are at it use proper Java naming conventions. Variable names do NOT start with an uppercase letter. You got "title" and "bg1" correct. So fix "EMA", "RMA" etc...
#camickr is correct. Note how using layout managers (and a little re-factoring) can actually simplify your code. Also, the relevant tutorial suggests using an action listener, rather than an item listener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/** #see http://stackoverflow.com/questions/5255337 */
public class IndicatorWindow implements ActionListener {
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
JRadioButton rma, ema, sma, stochastic, williams;
ButtonGroup bg = new ButtonGroup();
public JPanel createContentPane() {
JPanel gui = new JPanel(new BorderLayout());
JPanel title = new JPanel();
JLabel lab = new JLabel("Please Select Indicator Type");
title.add(lab);
gui.add(title, BorderLayout.NORTH);
createRadioButton(rma, "RMA");
createRadioButton(ema, "EMA");
createRadioButton(sma, "SMA");
createRadioButton(stochastic, "Stochastic");
createRadioButton(williams, "Williams");
gui.add(radioPanel, BorderLayout.CENTER);
JButton ok = new JButton();
ok.setText("Confirm");
ok.addActionListener(this);
radioPanel.add(ok);
return gui;
}
private void createRadioButton(JRadioButton jrb, String name) {
jrb = new JRadioButton(name);
bg.add(jrb);
jrb.addActionListener(this);
radioPanel.add(jrb);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Indicators");
frame.add(new IndicatorWindow().createContentPane());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setAlwaysOnTop(true);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You should add your JRadioButtons with a method:
private void bgAdd (String name, int y)
{
JRadioButton rb = new JRadioButton (name);
rb.setLocation (0, y);
rb.addItemListener (this);
rb.setSize (110, 19);
bg1.add (rb);
radioPanel.add (rb);
}
Calling code:
bgAdd ("RMA", 0);
bgAdd ("EMA", 30);
bgAdd ("SMA", 60);
bgAdd ("Stochastic", 90);
bgAdd ("Williams", 120);
Action:
public void itemStateChanged (ItemEvent e) {
Object button = e.getItemSelectable ();
String source = ((JRadioButton) button).getText ();
System.out.print (source + " ");
}
Then add BoxLayout to the page, for example.

Categories