I'm trying to change content dynamically based on a JRadioButton selection... My simplified code looks something like this.
//import
public class Thing {
//
JPanel pnlMain, pnl1, pnl2, pnlRt, pnlLt;
JRadioBtn btn1, btn2;
//
Thing () {
//
//initialize panels, add to them, etc.
pnlMain.add(pnlLt);
pnlMain.add(pnl1);
pnlMain.add(pnlRt);
//
//Get it showing and stuff.
//
}
//
//One instance of this class connected to all radio buttons.
class Evt implements ActionListener {
public void actionImplemented (ActionEvent evt) {
//
pnlMain.remove(1);
//
if (evt.getActionCommand().equals("Radio 1"))
pnlMain.add(pnl1);
else pnlMain.add(pnl2);
//
pnlMain.validate();
//
}
}
//
public static void main (String[] args) {
new Thing();
}
//
}
This lets me change panels, but i cannot change back to a panel i had previously selected... I don't understand why. Please help!!!
You should be using CardLayout instead, as this is exactly what that is for. Check out the tutorial here.
Use a proper layout manager. In this scenario, I recommend using CardLayout. This enables the developer to delegate the "complexity" of panel exchanging to the layout manager, which is how it should be.
Related
I am new to swing programming. I have created a Jtabbedpane and added 4 jpanel to it.
all the button and labels in the 4 jpanel are in the same java class and is starting to look cluttered. I am using Intellij. It would be nice if I can put all the items and events related to one panel in its own class so 4 classes for 4 panels and just a reference to those classes in the main frame. Not sure how to do this as most of the code is generated by the IDE.
If there is a way to do this or a tutorial that does this please let me know.
Yes you can break this up rather easily. Anywhere the code generates a new panel, probably as a "build" method, you can pull that out and make in a structure in another class. An example would look something like this:
// New class file named testPanel.java
public class testPanel extends JPanel{
// Constructor
public textPanel(){
// Add an example button
JButton btn_exit = new JButton("Exit");
btn_exit.addActionListener(new ExitButtonListener());
buttons.add(btn_exit);
}
// Private inner class which does event handling for our example button
private class ExitButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
// Add whatever other code you like here or above or anywhere else :)
}
Then to use that panel in your main JFrame, you can aggregate it like this:
private testPanel pnl_test = new textPanel();
// You can place this in the constructor
// for your JFrame without the "MyJFrame."
// But for demonstration purposes I will include it
MyJFrame.add(pnl_test);
// Or if you were placing a panel inside of another panel,
// you can use the same method associated with a JPanel object
MyJPanel.add(pnl_test);
I'm making a simple conversion tool to convert dollars to euro's and vice versa.
The whole purpose is just to experiment and learn this cool tool, java.
I have a JLabel at the top with an icon of a euro to indicate the starting currency. I have a button bellow this that I want to use to change that icon to a dollar one.
I am currently plying around with an ActionListener and trying different variations of setIcon/setIconImage (every itteration I can think of seeing that nothing has worked thus far).
public class MoneyConverter extends JFrame implements ActionListener{
//add label and icon showing base conversion currency
JLabel startcur = new JLabel("<--- Starting Curency", new ImageIcon("C:\\Users\\Russel\\Desktop\\1euro.gif"), SwingConstants.CENTER);
JButton euro = new JButton("Swap to Euro");
JButton dollar = new JButton("Swap to Dollar");
I then set up a
public MoneyConverter(){}
method and add all my components to a grid layout and add ActionLister's to my convert buttons.
e.g.
dollar.addActionListener(this);
euro.addActionListener(this);
After the usual code (setVisible and the likes that I will omit for your sake as I don't see it interfering with this, please let me know if I should include it all)
public void ActionPerformed (ActionEvent e){
Object source = e.getSource();
if (source.equals(euro)){
startcur.setIcon(new ImageIcon("C:\\Users\\Russel\\Desktop\\1.gif"));
}
}
This part has been changed many times and is the main reason for this post, how do I change this icon in the JLabel? - I will also be setting the conversion rate in here depending if they choose to start with dollars or euros. (Rate won't be actual rate.)
First, create and store a new ImageIcon
ImageIcon image = new ImageIcon(getClass().getResource("/nameOfImage.jpg"));
Then put this in your Action Listener
label.setIcon(image);
label.setText("");
You have to make sure you have a resource folder set up for your project. You can read how to do that in IntelliJ or Eclipse
You are also declaring the actionPerformed() wrong. I suggest reading up on this You should be doing it like this.
#Override
public void actionPerformed(ActionEvent e)
{
}
Conventionally, in java, method names start with a lower case letter and Classes start with an upper case.
The whole purpose is just to experiment and learn this cool tool, java.
Then I'll show you how to improve this program in a number of ways.
//Don't make your Swing class implement Actionlistener and add it as a
//listener to itself in the constructor before it's fully initialized
public class MoneyConverter extends JFrame {
//These don't have to be loaded at runtime, so make them into constants
//Java variables and methods follow thisNamingConvention
private static final Icon euroIcon = new ImageIcon("C:\\Users\\Russel\\Desktop\\1euro.gif");
private static final Icon dollarIcon = new ImageIcon("C:\\Users\\Russel\\Desktop\\1dollar.gif");
//These you probably want to use later so save them as private class variables
//Make them final so you can access them in the ActionListeners below
private final JLabel currencyLabel;
private final JButton euroButton;
private final JButton dollarButton;
public MoneyConverter() {
//These are declared final and are are therefore usually set first in constructor
this.currencyLabel = new JLabel("<--- Starting Curency", euroIcon, SwingConstants.CENTER);
this.euroButton = new JButton("Swap to Euro");
this.dollarButton = new JButton("Swap to Dollar");
//Write your own separate ActionListener for each button
euroButton.addActionListener(new ActionListener() {
#Override
public void run() {
currencyLabel.setIcon(euroIcon);
//These two are required for you to see the effect
//This should also be the solution to your initial problem
currencyLabel.revalidate();
currencyLabel.repaint();
}
});
dollarButton.addActionListener(new ActionListener() {
#Override
public void run() {
currencyLabel.setIcon(dollarIcon);
currencyLabel.revalidate();
currencyLabel.repaint();
}
});
//Add your components here using whatever layout manager you want.
}
public static void main(String []args){
//Start new Swing applications like this to prevent it from
//clogging the rest of the program
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MoneyConverter();
}
});
}
}
I'm new to Java, and trying to figure out one last thing for my program.
This is the program that I have coded and with the layout it is perfectly fine no problem at all.
Now my program suppose highlight the buttons whenever to press it on the keyboard (NOT BY PRESSING THE BUTTON ON THE SCREEN)
I'm not sure what I have to use since the action that it needs to take is when they type it in the JTextArea. I'm trying to use KeyEvent with KeyPressed but not sure if that is the right thing to do since it doesn't really work.
I can't post my code at the moment here since this is an assignment and I don't want some of my classmate to google and use it if they found it here. (LOL)
As required here is my codes :)
import javax.swing.*; // import all javax.swing
import java.awt.*; // import all java.awt
import java.awt.event.*;
public class Sample extends JFrame implements KeyListener { // start of the
// class
private JTextArea field = new JTextArea(10,15); // create an instance of
// JTextField
private JPanel mainPanel = new JPanel(); // create an instance of JPanel
private JPanel TopFieldPan = new JPanel();
private JPanel MainBtnsPan = new JPanel();
private JPanel FifthRowPan = new JPanel();
JPanel fifthBtn = new JPanel();
private static JButton Space = new JButton("");
public Sample() { // start of the weather constructor
Space.setPreferredSize(new Dimension(280, 45));
fifthBtn.add(Space);
TopFieldPan.add(field);
FifthRowPan.setLayout(new BoxLayout(FifthRowPan, BoxLayout.X_AXIS));
FifthRowPan.add(fifthBtn);
MainBtnsPan.setLayout(new GridLayout(5, 5, 0, 0));
MainBtnsPan.add(FifthRowPan);
mainPanel.add(TopFieldPan);
mainPanel.add(MainBtnsPan);
this.add(mainPanel);
Space.setSelected(true);
field.addKeyListener(this); // important !!!
setTitle("Typing Tutor"); // set the title to the frame
setSize(300, 300); // set the fixed size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true); // make it visible
} // ends of the constructor
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
Space.setBackground(Color.green);
}
}
public void keyReleased(KeyEvent evt) {
Space.setBackground(null);
}
public void keyTyped(KeyEvent evt) {
// TODO Auto-generated method stub
if(evt.getKeyChar() == 'a' || evt.getKeyChar() == 'A')
{
Space.setBackground(Color.green);
}
else if(evt.getKeyChar() == 'b' || evt.getKeyChar() == 'B')
{
Space.setBackground(Color.red);
}
}
public static void main(String[] args) { // start of the main method
new Sample();
} // ends of main method
} // ends of class
I tried to simplified the code as much as I could and here is the final one.
So I'm trying to make it when I press a or A it should highlight that space JButton.
Create a map of your buttons and the keys they map to, like this:
Map<String, JButton> buttonMap = new HashMap<String, Button>();
Then, when you are adding the buttons, add them to the map, like this:
buttonMap.put(FirstRow[i].toLowerCase(), btn);
Then, add something like this into your KeyTyped:
public void keyTyped(KeyEvent evt) {
String keyPressed = new String(""+evt.getKeyChar()).toLowerCase();
JButton tmp = buttonMap.get(keyPressed);
if(null != tmp){
tmp.doClick();
}
}
I did this quickly to your code for row 1 and 2. You'll have to play around with it to get it to work for the special keys, but it should get you where you're trying to go.
I pasted it here, to keep the answer small.
http://pastebin.com/t1v8d6Hi
You're code looks okay for a first pass, you seem to have a basic mechanism in place that works with the KeyListener. You probably need to think about how to stop mouse clicks on the buttons, JButton.setEnabled(false) works but changes how the button is drawn so you may need to override the paint method. You probably only need to hook the keylistener up to one component, the window will get all events, the text area when it has focus. The main task you have is to work out how to map the key pressed events to the buttons, maybe use a hashmap or something to store the JButtons with the key being the character code?
I am having a bit of problem regarding Swing. I have a JFrame called FrameMain. Inside it is a JPanel called panelChoices.
When FrameMain is called/created, it fills up the panelChoices object with a number of PanelEntries objects, which is a JPanel with a number of JButtons in it (it is a different class that I wrote).
What I want to do is when I click one of the buttons inside the PanelEntries object, I want to destroy/remove FrameMain, along with the rest of it components (including the PanelEntries object that contains the JButton).
I've tried using super but it returns the JPanel (the PanelEntries object) that holds the JButton and not FrameMain that holds them all together. How can I achieve this?
EDIT: It seems that I am not clear enough, so here's a bit more information from my work. I don't have the actual code right now because I am on a different machine but I hope this will help elaborate my question.
public class FrameMain() {
private JFrame frameMain;
private JPanel panelChoices;
public FrameMain(args) {
createGUI();
loadData();
}
private void createGUI() {
JFrame frameMain = new JFrame();
JPanel panelChoices = new JPanel(new GridLayout(1,1));
frameMain.add(panel);
// removed formatting and other design codes since they are not important.
pack();
}
private void loadData() {
boolean available;
for (int i = 1; i <= 10; i++) {
// do some if/else and give value to boolean available
PanelEntries panel = new PanelEntries(i, available);
frameMain.add(panel);
// more code here to handle data.
}
}
}
public class PanelEntries() extends JPanel {
public PanelEntries(int num, boolean avb) {
JButton button = new JButton("Button Number " + num);
button.setEnabled(avb);
add(button);
// add action listener to created button so that it calls 'nextScreen()' when clicked.
// more code
pack();
}
private void nextScreen() {
// destroy/dispose MainFrame here.
// See Notes.
AnotherFrame anotherFrame = new AnotherFrame();
}
}
Notes:
All classes are inside their own .java file.
I need to know how to dispose FrameMain from the button inside the PanelEntries object, not just disposing a JFrame.
As per the given information,
If you want to exit the application, its not a big deal use System.exit(0); :)
If you mean to dispose the frame, jframe.dispose();
If you want to remove a componet / all components you can use .remove(Component) / .removeAll() etc
If this did not help, please re-write your question with more information.
I'm creating a small crypto app for the desktop using java.
I'm using JFrames (import javax.swing.JFrame) with Oracle
JDeveloper 11g under Linux.
I want to have a "welcome" form/frame where users can choose
their encryption method, and then on choosing the method,
I want to dynamically create the appropriate form for the
chosen encryption method and also destroy/free/dispose() of
the welcome form. When the user has finished their encrypting,
they should close the frame/form (either by clicking on the
x at the top right - or using the Exit button or by any
method) and the welcome frame should be dynamically recreated
and appear.
I've tried various things - btnEncode_actionPerformed(ActionEvent e)
then this.dispose() - and I've fiddled with this_windowClosed(WindowEvent e)
and dispose(), but nothing seems to work.
Even a workaround using setVisibl(true/false) would be acceptable at
this stage - this has been wrecking my head all day. It's very
easy to do in Delphi!
TIA and rgs,
Paul...
something like this usually does the trick: (Note I haven't tested this)
public class WelcomeMsg extends JFrame
.
.
.
public void btnContinue_actionPerformed(ActionEvent e)
{
this.dispose();
SwingUtilities.invokeLater(new Runnable(){ new JFrameAppropriateWindow(args) });
}
where btnContinue is the Continue button on your welcome form and JFrameAppropriateWindow is the next frame you would like to show depending on the user's choice. Args are any arguments you need to pass.
When you are ready, you can simply dispose the current frame and relaunch an instance of WelcomeMsg
I put together this simple example for creating and displaying a panel depending on a user choice.
public class Window extends JFrame {
public Window() {
this.setLayout(new BorderLayout());
JComboBox encryptionCombobox = new JComboBox();
encryptionCombobox.addItem("foo");
encryptionCombobox.addItem("bar");
//...
encryptionCombobox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// find choices and the correct panel
JPanel formPanel = new JPanel();
formPanel.setOpaque(true);
formPanel.setBackground(Color.RED);
//...
Window.this.add(formPanel, BorderLayout.CENTER);
Window.this.validate();
Window.this.repaint();
}
});
add(encryptionCombobox, BorderLayout.NORTH);
}
public static void main(String[] args) {
new Window().setVisible(true);
}
}
When I come to think about it, you should probably use a CardLayout instead, which allows you to switch between different panels (cards).