Code is underneath. Basically what I'm trying to do is I have display going on in my JPanel of a JTextPane. I have a button that edits the value of the string that's supposed to be displayed in the JTextPane. I can't figure out how to update the JTextPane however. I've tried revalidate(), validate(), repaint(), none of those seemed to work.
The code is complete, it should be able to run.
import java.awt.Canvas;
public class windowBuild extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private int health = 20;
private int energy = 4;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
windowBuild frame = new windowBuild();
frame.setVisible(true);
}
});
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
if (which.equals("Claw")){
energy = energy-1;
System.out.println("Player one's dragon clawed the opponent. Dragon's energy is now at: "+ energy);}
else if (which.equals("Wait")){
System.out.println("Turn succesfully skipped");}
System.out.println(getEnergy());
}
}
public windowBuild() {
ButtonHandler bh;
System.out.println("Starting frame...");
bh = new ButtonHandler();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new TitledBorder(null, "Dragon Duel",
TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnClaw = new JButton("Claw");
btnClaw.setBounds(288, 511, 109, 39);
contentPane.add(btnClaw);
btnClaw.addActionListener(bh);
if (energy == 0)
btnClaw.setEnabled(false);
JButton btnWait = new JButton("Wait");
btnWait.setBounds(645, 511, 109, 39);
contentPane.add(btnWait);
btnWait.addActionListener(bh);
StringBuilder sb = new StringBuilder();
String strB = Integer.toString(health);
sb.append("H: ").append(strB).append("/20");
String healthString = sb.toString();
JTextPane txtpnH_1 = new JTextPane();
txtpnH_1.setEditable(false);
txtpnH_1.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH_1.setText(healthString);
txtpnH_1.setBounds(134, 511, 109, 39);
contentPane.add(txtpnH_1);
String strR = Integer.toString(energy);
String energyString = "E: ";
energyString += strR;
energyString += "/4";
JTextPane txtpnH = new JTextPane();
txtpnH.setEditable(false);
txtpnH.setText(energyString);
txtpnH.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH.setBounds(39, 511, 85, 39);
contentPane.add(txtpnH);
}
}
Thanks so much!!
Take the time to read through the Code Conventions for the Java Programming Language
Make use of appropriate layout managers, see A Visual Guide to Layout Managers and Using Layout Managers for more details
For what it's worth, use JTextField instead JTextPane, you're gaining little to no benefit by using JTextPane for what you seem to be trying to achieve. In fact, you might actually be better of us just using JLabel, seen as you don't want them to be editable
Avoid overriding top level containers, like JFrame, instead start with something like JPanel, build your UI on it and then deploy it to what ever top level container you want.
The problem you have is a reference issue. In the constructor of your windowBuild, you are defining all your UI components. This means that there is no way you can reference them anywhere else from with your program. Instead, make those components you need to reference else where instance fields.
public class WindowBuild extends JFrame {
//...//
private JTextPane txtpnH_1;
private JTextPane txtpnH;
//...//
public WindowBuild() {
//...//
txtpnH_1 = new JTextPane();
//...//
txtpnH = new JTextPane();
//...//
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
// Now you can use txtpnH_1.setText and txtpnH.setText
}
}
Related
I am just throwing together a quick and dirty GUI to display some data when I ran into an odd issue. The last label I add to the JFrame doesn't want to be positioned or display the border I put on it, so it looks like this:
Here is my code:
public DisplayData (Connection tConn)
{
ID = tID;
conn = tConn;
setupObjects();
setupFrame();
}
private void setupObjects()
{
JLabel caseLabel = new JLabel ("Case #:");
JLabel dateLabel = new JLabel ("Date:");
JLabel reportLabel = new JLabel ("Report:");
JLabel offenceLabel = new JLabel ("Offence:");
JLabel descriptionLabel = new JLabel ("Description:");
this.add(caseLabel);
this.add(dateLabel);
this.add(reportLabel);
this.add(offenceLabel);
this.add(descriptionLabel);
caseLabel.setBounds(50, 50, 130, 25); //x, y, width, height
dateLabel.setBounds(50, 100, 130, 25);
reportLabel.setBounds(50, 150, 130, 25);
offenceLabel.setBounds(50, 200, 130, 25);
descriptionLabel.setBounds(100, 50, 130, 25);
caseLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
dateLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
reportLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
offenceLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
descriptionLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
private void setupFrame()
{
this.setTitle("Data Display");
this.setSize (650, 700); //Width, Height
this.setLocation(300, 10);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(null);
}
Yes, I know I should be using a proper layout manager, but like I said i just wanted something quick and dirty. Plus, I will not be beaten by something that should be this simple. Any ideas would be appreciated.
EDIT:
As Compass and Neophyte pointed out, my order of operations was off. Flipped my method calls and all is good again in the world. Thanks for the 2nd pair of eyes.
Contrary to the original poster's strategy, or any of the answers so far, the best approach to this problem is to use layouts.
Here is an example that shows how easy it is to position fields using layouts, and to change the GUI on later updates to the specification.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class CourtDetailsGUI {
private JComponent ui = null;
static final String[] FIELD_NAMES = {
"Case #:",
"Date:",
"Report:",
"Offence:",
"Plaintiff:",
"Defendant:"
};
CourtDetailsGUI(int num) {
initUI(num);
}
public void initUI(int num) {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
ui.add(getFieldsPanel(num), BorderLayout.PAGE_START);
JTextArea ta = new JTextArea(5, 40);
JScrollPane sp = new JScrollPane(ta);
JPanel p = new JPanel(new GridLayout());
p.add(sp);
p.setBorder(new TitledBorder("Details"));
ui.add(p);
}
private JPanel getFieldsPanel(int num) {
JPanel outerPanel = new JPanel(new FlowLayout());
JPanel innerPanel = new JPanel(new GridLayout(0, 1, 15, 15));
outerPanel.add(innerPanel);
for (int ii=1; ii<num; ii++) {
JLabel l = new JLabel(FIELD_NAMES[ii]);
l.setBorder(new LineBorder(Color.BLACK));
innerPanel.add(l);
}
return outerPanel;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
for (int ii=0; ii<FIELD_NAMES.length; ii++) {
CourtDetailsGUI o = new CourtDetailsGUI(ii+1);
JFrame f = new JFrame("Data " + (ii+1));
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
}
};
SwingUtilities.invokeLater(r);
}
}
Your order of operations is incorrect.
You initially call setupObjects();
This plays your objects out onto a JFrame, which has the default LayoutManager of BorderLayout.
By using the default add(Component comp) method, with BorderLayout, you end up putting the component into null for BorderLayout, which is not supposed to be normal. Furthermore, the reason you can't see the border for this object is because the border is actually the size of the frame. If you explicitly set a region for BorderLayout, then you'll see it work, but setting to no region seems to just break BorderLayout.
Additional add calls appear to free the previous item from the BorderLayout null management, allowing the bounds to take over.
Afterwards, you call setupFrame(); which removes the layout manager, but does not refresh what is currently rendered.
This sets the layout to null, which does nothing to how the frame is displayed, but just removes the layout.
To avoid this issue, call setupFrame(); prior to setupObjects();, and then setVisible(true) can be called at the end of setupObjects();
In Food Tab, I want to achieve this
But I only able to get this
How can I increase the width of the JTextField which are in Food Tab ? Below is my code
public class FoodOrdering {
static private JFrame frame;
static private JTextField textField;
static private GridBagConstraints gbc;
static private JLabel[] foodLabel;
static private JLabel[] labels;
static private JTextField[] qtyField;
static private JLabel[] foodImage;
static private File[] file;
private static final int ELEMENTS = 9;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FoodOrdering window = new FoodOrdering();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* #throws IOException
*/
public FoodOrdering() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
*
* #throws IOException
*/
static void initialize() throws IOException {
frame = new JFrame();
frame.setBounds(100, 100, 700, 550);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setLocationRelativeTo(null);
JLabel lblFoodOrdered = new JLabel("Food Ordered");
lblFoodOrdered.setBounds(529, 11, 81, 14);
frame.getContentPane().add(lblFoodOrdered);
TextArea textArea = new TextArea();
textArea.setBounds(462, 31, 199, 275);
frame.getContentPane().add(textArea);
JLabel lblTotal = new JLabel("Total : ");
lblTotal.setBounds(519, 315, 46, 14);
frame.getContentPane().add(lblTotal);
textField = new JTextField();
textField.setBounds(575, 312, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnOrder = new JButton("Order");
btnOrder.setBounds(521, 352, 89, 23);
frame.getContentPane().add(btnOrder);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
addIt(tabbedPane, "Foods");
addIt1(tabbedPane, "Drinks");
addIt1(tabbedPane, "Desserts");
tabbedPane.setBounds(23, 11, 400, 450);
frame.getContentPane().add(tabbedPane);
frame.setVisible(true);
}
static void addIt1(JTabbedPane tabbedPane, String text) {
JLabel label = new JLabel(text);
JButton button = new JButton(text);
JPanel panel = new JPanel();
panel.add(label);
panel.add(button);
tabbedPane.addTab(text, panel);
}
static void addIt(JTabbedPane tabbedPane, String text) throws IOException {
JPanel panel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(1, 1, 1, 1);
foodImage = new JLabel[ELEMENTS];
foodLabel = new JLabel[ELEMENTS];
labels = new JLabel[ELEMENTS];
qtyField = new JTextField[ELEMENTS];
file = new File[ELEMENTS];
try {
file[0] = new File("C:\\Users\\tony\\Desktop\\MedSalad.png");
file[1] = new File("C:\\Users\\tony\\Desktop\\JapanesePanNoodles.png");
file[2] = new File("C:\\Users\\tony\\Desktop\\Spaghetti.png");
file[3] = new File("C:\\Users\\tony\\Desktop\\PadThai.png");
file[4] = new File("C:\\Users\\tony\\Desktop\\RamenNoodles.png");
file[5] = new File("C:\\Users\\tony\\Desktop\\SpaghettiAndMeatBalls.png");
file[6] = new File("C:\\Users\\tony\\Desktop\\chickenRice.jpg");
file[7] = new File("C:\\Users\\tony\\Desktop\\thaiFood.jpeg");
file[8] = new File("C:\\Users\\tony\\Desktop\\vietnamFood.jpg");
foodLabel[0] = new JLabel("Salad");
foodLabel[1] = new JLabel("Japanese Noodles");
foodLabel[2] = new JLabel("Spaghetti");
foodLabel[3] = new JLabel("Spaghetti Meat Balls");
foodLabel[4] = new JLabel("Noodles");
foodLabel[5] = new JLabel("Kids Spaghetti");
foodLabel[6] = new JLabel("Chicken Rice");
foodLabel[7] = new JLabel("Thai Food");
foodLabel[8] = new JLabel("Vietnam Food");
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < ELEMENTS; i++) {
Image image = ImageIO.read(file[i]);
Image imageScaled = image.getScaledInstance(80, 95, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(imageScaled);
qtyField[i] = new JTextField(3);
foodImage[i] = new JLabel(imageIcon);
}
gbc.gridx = 0;
for (int i = 0; i < ELEMENTS; i++) {
if (i % 3 == 0) {
gbc.gridy += 2;
gbc.gridx = 0;
}
panel.add(foodImage[i], gbc);
gbc.gridy++;
panel.add(foodLabel[i], gbc);
gbc.gridy--;
gbc.gridx++;
panel.add(qtyField[i], gbc);
gbc.gridx++;
tabbedPane.addTab(text, panel);
}
}
public void setVisible(boolean b) throws IOException {
}
}
The JTextfield objects are so narrow because of a very old "bug" in GridBagLayout which causes it to ignore the preferred size of its contents.
There are several possible ways to work-around this bug:
Create a class called PreferredGridBagLayout as explained in the link and use that instead of GridBagLayout.
Set the minimum size of each of your qtyField instances with qtyField[i].setMinimumSize(qtyField[i].getPreferredSize()).
Create subclasses of JTextField which override the method getMinimumSize() to return the same value as getPreferredSize(), or some other reasonable minimum size.
Because this problem is so common when using GridBagLayout, solution #1 is the easiest in the long term.
Afterwards, you'll need to make your tabbedPane object a little wider, or switch to a layout manager in the main panel that automatically determines the size of the tabbed pane.
There are multiple things that could be improved in your code. Creating good layouts in Swing is not easy, and you will need much more work to make a pretty layout. But this will solve your problem with collapsing text fields.
This problem simply can be solved by setting the
qtyField[i].setMinimumSize(new Dimension(33,20));
function. The reason for setting minimum size is that the GridBagLayout dont have enough space to arrange all those components properly so it only takes the minimum size of the empty textField.
Just add the code after the line
qtyField[i] = new JTextField(3);
and you will be also needed to increase the width of tabbedPane a little bit more to make the components(qtyField) visible
Instead of using null layout. use some other layout like border layout. Then use just one line:
frame.pack();
This will display all the components at their preferred sizes.
Just a coding practice: instead of setting bounds use panels to add components and then add these panels to a main panel.
Like use one different panel to add your Jlabel of food ordered, textarea, Jlabel for order and order button. And then add that panel to your main panel.
Hope you understand. :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to make a nice gui for downloading some stuff and I'm trying to add some text explaining how to use the gui. The only problem is the text isn't appearing. Here is all relevant code.
public static class Dissplay extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("Please enter you plugin folder location and what you want to install.", 30, 20);
}
}
static JTextField input;
static JCheckBox villagesBox;
static JCheckBox slabsBox;
static JFrame window;
static boolean clicked;
public static void main(String[] args) {
clicked = false;
input = new JTextField("Enter plugin folder location here");
input.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(clicked){
} else {
input.setText("");
clicked = true;
}
}
});
JPanel content1 = new JPanel();
JPanel content2 = new JPanel();
JPanel content3 = new JPanel();
content3.setLayout(new BorderLayout());
content1.setLayout(new BorderLayout());
content2.setLayout(new GridLayout(0,2));
content3.add(input, BorderLayout.SOUTH);
content3.add(new Dissplay(), BorderLayout.CENTER);
villagesBox = new JCheckBox("Villages");
content1.add(content3, BorderLayout.NORTH);
villagesBox.setSelected(false);
slabsBox = new JCheckBox("Slabs");
slabsBox.setSelected(false);
content2.add(villagesBox);
content2.add(slabsBox);
JButton button = new JButton("Go");
ActionListener buttonLisener = new Button();
button.addActionListener(buttonLisener);
content1.add(button, BorderLayout.SOUTH);
window = new JFrame();
window.setContentPane(content1);
window.add(content2, 0);
window.setSize(200, 150);
window.setLocation(100, 100);
window.setVisible(true);
}
No clue what's wrong.
Found the solution to your woes. You need to call the setPreferredSize method on your JPanel object. It quite bizarrely defaults to a 10x10 Dimension initially. Once you up that, you'll be able to see your drawn text.
public static class Dissplay extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
public Dissplay() {
super();
this.setPreferredSize(new java.awt.Dimension(600, 100));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("Please enter you plugin folder location and what you want to install.", 30, 20);
}
}
You may try to set font, color, etc. Something like this :
g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));
g.setColor(Color.red);
g.drawString("some string", 40, 40);
I have a Main class that has a public static void main(String[] args) {}. I also have a class called appGUI. I have been trying to get the GUI to load when i run the Main class, but nothing occurs, not even any errors... :(
Here is the Main class:
public class Main {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
appGUI gui = new appGUI();
}
}
And here is the appGUI class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* Created by JFormDesigner on Wed Apr 03 19:24:35 BST 2013
*/
/**
* #author Hrach Ghapantsyan
*/
public class appGUI extends JFrame {
public appGUI() {
initComponents();
}
private void loginButtonActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - Hrach Ghapantsyan
loginPasswordField = new JPasswordField();
loginUsernameField = new JTextField();
usernameLabel = new JLabel();
passwordLabel = new JLabel();
loginButton = new JButton();
titleLabel = new JLabel();
//======== this ========
setTitle("Experimental X | Administrator Login");
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.add(loginPasswordField);
loginPasswordField.setBounds(80, 65, 100, loginPasswordField.getPreferredSize().height);
contentPane.add(loginUsernameField);
loginUsernameField.setBounds(80, 35, 100, loginUsernameField.getPreferredSize().height);
//---- usernameLabel ----
usernameLabel.setText("Username:");
contentPane.add(usernameLabel);
usernameLabel.setBounds(20, 40, 55, usernameLabel.getPreferredSize().height);
//---- passwordLabel ----
passwordLabel.setText("Password:");
contentPane.add(passwordLabel);
passwordLabel.setBounds(20, 70, 55, passwordLabel.getPreferredSize().height);
//---- loginButton ----
loginButton.setText("Login");
loginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loginButtonActionPerformed(e);
}
});
contentPane.add(loginButton);
loginButton.setBounds(80, 95, 100, loginButton.getPreferredSize().height);
//---- titleLabel ----
titleLabel.setText("Experimental X | Administrator Login");
contentPane.add(titleLabel);
titleLabel.setBounds(45, 10, 190, titleLabel.getPreferredSize().height);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < contentPane.getComponentCount(); i++) {
Rectangle bounds = contentPane.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = contentPane.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
contentPane.setMinimumSize(preferredSize);
contentPane.setPreferredSize(preferredSize);
}
setSize(270, 170);
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - Hrach Ghapantsyan
private JPasswordField loginPasswordField;
private JTextField loginUsernameField;
private JLabel usernameLabel;
private JLabel passwordLabel;
private JButton loginButton;
private JLabel titleLabel;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
I have tried running the main class on Eclipse and netbeans, but it runs and then stops after a few seconds. I do not get any errors. Do any of you here have any suggestions? Thanks.
You haven't called JFrame#setVisible:
gui.setVisible(true);
Some notes:
Avoid using null layout. Always use a layout manager
Don't use the setXXXSize methods. Override getPreferredSize method to determine component sizes
Rather than extending a JFrame, you typically want to create one and use directly.
Consider creating the JFrame in the EDT by using initial threads
Make sure you call setVisible(true) on the GUI.
public class appGUI extends JFrame {
setVisible(true);
// ----
}
place this code to make visible.
Just add:
this.setVisible(true);
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.