So for fun I've been working on developing this simple stock-chart GUI, which grabs charts from YahooFinance and displays them into a tabbed-Jpanel. I've been able to get the tabs to populate with user-defined stocks and all. However, I've developed some buttons that allow one to query different chart aspects (boll bands, moving averages, etc.) and would like the be able to "redraw" the panel with this update chart.
Problem: I'm not sure how to access the individual panels that I create via the method below. I need to be able to select a panel (say panel1 created when i=1 below) and have it update in an ActionListener. I'm really just wondering how Java defines these panels in the loop so I can access them later and redraw the label! Cheers.
public static void urlstock(String options,final String[] s, final JFrame f,final
JTabbedPane tpane) throws IOException{
for(int i=0;i<s.length;i++){
String path = "http://chart.finance.yahoo.com/z?s="+s[i]+options;
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
JPanel panel=new JPanel();
tpane.addTab(s[i],null, panel);
panel.add(label);
}
So I've tried this which cues on a button press, but it doesn't work because it doesn't recognize panel as variable for a reason that is beyond my understanding:
public void actionPerformed(ActionEvent e)
{ //Execute when button is pressed
System.out.println("MAButton");
tpane.getComponentAt(1);
tpane.remove(panel);
//Container.remove();
String path = "http://chart.finance.yahoo.com/z?s=GOOG&t=7m&z=l&q=l&a=ss,sfs";
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
JPanel panel=new JPanel();
tpane.setComponentAt(1,panel);
panel.add(label);
}
Grab an index of the tab in question using it's name (s[i]) JTabbedPane#indexOfTab(String)
Get a reference to the component at the retrieved index (JTabbedPane#getComponentAt(int))
Remove the contents of the retrieved component Container#removeAll()
Add the new label....
UPDATED with Example
public class TestTabPane {
public static void main(String[] args) {
new TestTabPane();
}
public TestTabPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JTabbedPane tabPane = new JTabbedPane();
JPanel panel = new JPanel();
JButton updateButton = new JButton("Update me");
panel.add(updateButton);
updateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int indexOfTab = tabPane.indexOfTab("Testing");
JPanel panel = (JPanel) tabPane.getComponentAt(indexOfTab);
panel.removeAll();
panel.add(new JLabel("I've begin updated"));
panel.repaint();
}
});
tabPane.addTab("Testing", panel);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(tabPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Related
I am new to creating GUI. I want to know how to create multiple windows. I want to show another frame if a button is to be clicked. I have searched how and i saw that some people are making another GUI form and just calling the other form i a button was clicked, but i dont understand how.
There are numerous ways to do this. One of the main ways is to create a new Java Class with its own properties. Here is a nexample:
JButton button = new JButton("Button_Leads_To_This_Window");
button.addActionListener( new ActionActionListener()
{
public void actionPerformed(ActionEvent e)
{
NewFrame();
}
});
This will allow the button to call a new window, similar as the way you called the "My Empire" window. For example NewFrame() class will look like this:
public static void newFrame()
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(true);
JTextArea textArea = new JTextArea(15, 50);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setFont(Font.getFont(Font.SANS_SERIF));
JScrollPane scroller = new JScrollPane(textArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new FlowLayout());
JTextField input = new JTextField(20);
JButton button = new JButton("Enter");
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
panel.add(scroller);
inputpanel.add(input);
inputpanel.add(button);
panel.add(inputpanel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setResizable(false);
input.requestFocus();
}
});
}
Here is more information to the matter:
https://www.thoughtco.com/create-a-simple-window-using-jframe-2034069
https://www.youtube.com/watch?v=RMz9LYY2g4A
Good luck.
I'm trying to make a registration form for a game(assignment) for school and i have finished it but i wanted to add an image on it but it blocks everything, JButton,JTextField etc.. How can i fix this? EDITED : I MADE THE CODE A LITTLE SHORTER SAME PROBLEM OCCURS.
public class MyGUI {
JLabel xyz;
JButton b1;
public JPanel createContentPane () {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(null);
xyz = new JLabel("Don't have an account? Sign up!");
xyz.setBounds(10,0,390,30);
xyz.setFont(new Font("Lucida Grande", Font.BOLD, 20));
xyz.setLayout(new FlowLayout());
mainPanel.add(xyz);
b1 = new JButton("Create Account");
b1.setBounds(40,540,310,33);
b1.setFont(new Font("Comic San Ms", Font.BOLD , 16));
b1.setForeground(Color.white);
b1.setBackground(Color.blue);
mainPanel.add(b1);
return mainPanel;
}
public static void CreateAndShowGUI() {
JFrame frame = new JFrame("Romaverse ONLINE! REGISTRATION");
Container c = frame.getContentPane();
MyGUI demo = new MyGUI();
c.add(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(480,700);
frame.setVisible(true);
frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Admin\\Desktop\\roma.jpg")));
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CreateAndShowGUI();
}
});
}
}
Here Is the part where i put the image
frame.setContentPane(newJLabel(newImageIcon("C:\\Users\\Admin\\Desktop\\roma.jpg"));
The image doesn't block buttons, it replaces them because you are calling setContentPane. Why are you doing this? You can simply add the image together with all other controls inside the createContentPane method. Note that the order in which controls are added may affect their Z-order.
Check out the Background Panel.
It shows two approaches:
Add the image to a JLabel and then add your components to the label
Do custom painting of the image on a JPanel and then add your components to the panel.
Edit:
Basic code using approach 1:
JLabel background = new JLabel( new ImageIcon(...) );
label.setLayout( new FlowLayout() );
label.add( new JButton("Hello") );
JFrame frame = new JFrame();
frame.add( background );
I asked a question before, on how to make a JTextField insert its text from beneath. Now I got some problem with the code. I edited a little bit, just for testing. Here is the code I'm using right now:
public class BaseTextAreaDemo {
private static JTextArea textArea;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("Base JTextArea App");
final JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
panel.setLayout(new BorderLayout());
JPanel textAreaPanel = getBaseTextArea();
JScrollPane scrollPane = new JScrollPane(textAreaPanel) {
public Dimension getPreferredSize() {
return new Dimension(300, 230);
}
};
panel.add(scrollPane, BorderLayout.SOUTH);
JTextField textField = new JTextField();
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
textArea.append(arg0.getActionCommand() + "\n");
}
});
frame.add(panel, BorderLayout.CENTER);
frame.add(textField, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getBaseTextArea() {
textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.append("bla bla bla\n");
textArea.append("new text here");
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(textArea.getBackground());
panel.setBorder(textArea.getBorder());
textArea.setBorder(null);
panel.add(textArea, BorderLayout.SOUTH);
return panel;
}
});
}
I just added a textField, because I also need one in the program I need this in, and it's useful to add more lines this way.
Now the problem is, when I run this program and I add lines until a vertical scrollbar appears, a horizontal comes out too. I already figured that you can just turn that off, but then some text falls out of the screen. Also, when you make the frame wider, and than return it to it's normal size, the horizontal scrollbar stays at the size from the widened window.
Another problem is that the speed of scrolling is very low in the JTextField.
Try to set the PreferedSize of the textArea to the same as ur JScrollPane:
textArea.setPreferedSize(Dimension(300, 230));
You can aswell just disable Horizontal Scrollbar:
scrollPane.setHorizonalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
You can set the Scrollspeed like this:
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
i could solved the problem: its the panel u are adding to the scrollpane. Add the JTextArea directly to the ScrollPane and the Horizonal Bar only appear if needed:
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
if you want to fully remove the horizontal scrollbar then I suggest you invoke this line of code on your JScrollPane:
scrollPane.setHorizonalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
I added my image straight onto the jframe but then if i add another panel the image disappears,
i have tried to add image to a label and added this to a panel but this doesn't work either here is my code used to get my image:
here is my updated program:
public class imgload extends JFrame implements ActionListener {
private JButton b1;
public imgload() {
makeframe();
}
public void makeframe() {
JFrame f = new JFrame();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JLabel lb = new JLabel();
b1 = new JButton("Confirm");
b1.addActionListener(this);
JTextArea q1 = new JTextArea();
ImageIcon icon = createImageIcon("sample.jpg");
lb.setIcon(icon);
q1.setLocation(10,10);
q1.setSize(50,50);
p2.add(q1);
b1.setLocation(100,105);
b1.setSize(80,30);
p2.add(b1);
f.add(p1.add(lb));
// f.add(p2);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,600);
f.setAlwaysOnTop(true);
f.setResizable(false);
}
public ImageIcon createImageIcon(String path) {
URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b1) {
System.exit(0);
}
}
public static void main(String[] args) {
new imgload();
}
}
You need to look into using layouts (BorderLayout, FlowLayout, GridLayout, GridBagLayout, etc) in Swing. By default, most things have a BorderLayout, and when you use add with no arguments, it places the item in the center. Subsequent calls just replace the item in the center.
I would like to know what code to insert and where to add a simple label that can just say the word "Label" and a input text box that I can enter a number.
public CalculateDimensions() {
JTabbedPane Tab = new JTabbedPane();
JPanel jplInnerPanel1 = createInnerPanel("First Tab");
Tab.addTab("One", jplInnerPanel1);
Tab.setSelectedIndex(0);
JPanel jplInnerPanel2 = createInnerPanel("Second Tab");
Tab.addTab("Two", jplInnerPanel2);
JPanel jplInnerPanel3 = createInnerPanel("Third Tab");
Tab.addTab("Three", jplInnerPanel3);
JPanel jplInnerPanel4 = createInnerPanel("Fourth Tab");
Tab.addTab("Four", jplInnerPanel4);
JPanel jplInnerPanel5 = createInnerPanel("Fifth Tab");
Tab.addTab("Five", jplInnerPanel5);
setLayout(new GridLayout(1, 1));
add(Tab);
}
protected JPanel createInnerPanel(String text) {
JPanel jplPanel = new JPanel();
JLabel jlbDisplay = new JLabel(text);
jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
jplPanel.setLayout(new GridLayout(1, 1));
jplPanel.add(jlbDisplay);
return jplPanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calculations");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.getContentPane().add(new CalculateDimensions(),
BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
The Swing tutorial is an excellent resource for building GUIs.
Take a look at the visual guide and click on the components you want for detailed how to guides for creating text boxes, and other items.
http://download.oracle.com/javase/tutorial/ui/features/components.html
in your public static void main() method you should not instantiate JFrame frame = new JFrame("Calculations");
This is where you are going wrong!
That line should read:
CalculateDimensions frame = new CalculateDimensions("Calculations");
You will also need to change the line says
public class CalculateDimensions {
(it's near the top) says
public class CalculateDimensions extends JFrame {
then inside the method called public class CalculateDimensions { you need to add a line after JPanel jplInnerPanel1 = createInnerPanel("First Tab"); which says
jplInnerPanel1.add(new JLabel("Label");