I wrote a program to randomly select an image and display it in the window every time a button is pressed. Mow I am trying to figure out how to make the "Roll Dice" button the default allowing enter press.
Driver:
public class MCobbM10A1 {
static int SCREEN_WIDTH = 500;
static int SCREEN_HEIGHT = 600;
static WidgetPanel widget;
static GraphicPanel myPanel;
public static void main(String[] args) {
JFrame myFrame = new JFrame("Dice Roller");
JFrame.setDefaultLookAndFeelDecorated(true);
myPanel = new GraphicPanel();
myPanel.setBounds(0, 0, 500, 200);
myFrame.add(myPanel);
JPanel lastPanel = new JPanel();
myFrame.add(lastPanel);
widget = new WidgetPanel();
widget.setBounds(0, 250, 500, 300);
myFrame.add(widget);
widget.rollButton.addActionListener((ActionEvent newRoll) -> {
new MCobbM10A1().myNewRollButtonPressed();
});
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
myFrame.setBounds(0, 0, 500, 300);
}
private void myNewRollButtonPressed() {
myPanel.newRoll();
}
}
And here is the WidgetPanel:
public class WidgetPanel extends JPanel {
JButton rollButton;
WidgetPanel() {
this.setBackground(Color.WHITE);
this.setLayout(new BorderLayout());
rollButton = new JButton();
rollButton.setBounds(350, 200, 100, 25);
rollButton.setText("Roll Dice");
this.add(rollButton);
JLabel fixBug = new JLabel();
this.add(fixBug);
}
}
how to make the "Roll Dice" button the default allowing enter press.
You assign the default button to the JRootPane of your frame.
frame.getRootPane().setDefaultButton(…);
One way to do this is:
#Override
public void addNotify()
{
super.addNotify();
JFrame frame = (JFrame)SwingUtilities.windowForComponent( rollButton );
frame.getRootPane().setDefaultButton(rollButton);
}
The addNotify() method is invoked when a panel is added to the frame.
Unrelated to your question but why are you creating a new object for each roll?
widget.rollButton.addActionListener((ActionEvent newRoll) -> {
new MCobbM10A1().myNewRollButtonPressed(); // <--- new MCobbM10A1 object
});
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
myFrame.setBounds(0, 0, 500, 300);
}
private void myNewRollButtonPressed() {
myPanel.newRoll();
}
Why not just do this?
widget.rollButton.addActionListener((ae) ->
myPanel.newRoll());
Related
The program is to display 3 buttons on the JPanel. The program is compiled successfully. The GUI Window then appears and is empty. When I minimise the window and then maximise it again the Buttons appear. On doing this again another set of Buttons appear. The button keeps on appearing when the window is refreshed and the older data is kept intact.
JPanel Class
class MyJPanel extends JPanel {
JButton jb1, jb2, jb3;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
jb1 = new JButton();
jb2 = new JButton("Green");
jb3 = new JButton("Blue");
//g.drawString("Welcome!", 100, 100);
ImageIcon img = new ImageIcon("next.png");
jb1.setIcon(img);
jb1.setToolTipText("Button 1");
this.add(jb1);
this.add(jb2);
this.add(jb3);
}
}
JFrame Class
class MyJFrame extends JFrame {
MyJPanel mjp;
public MyJFrame(String title) {
super(title);
mjp = new MyJPanel();
Container ct = getContentPane();
ct.add(mjp);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Driver Class
class Gui5JButton {
public static void main(String[] args) {
MyJFrame mjf = new MyJFrame("Prakhar");
mjf.repaint();
}
}
paintComponent is called everytime your panel needs to be redraw, so everytime you minimize the window it will put the button again. If I understood what you want to do correctly, you need to remove the override and put this code :
jb1 = new JButton();
jb2 = new JButton("Green");
jb3 = new JButton("Blue");
//g.drawString("Welcome!", 100, 100);
ImageIcon img = new ImageIcon("next.png");
jb1.setIcon(img);
jb1.setToolTipText("Button 1");
this.add(jb1);
this.add(jb2);
this.add(jb3);
in the constructor of your MyJPanel class.
I need to make a GUI that asks the users for details and then save them in a linked list. I wanted to use the CardLayout to switch from one frame to another, which is something I'm doing for the first time. I have done probably less half of what I need to do and here I am quite lost in this part. The code below compiles and executes but when I click the buttons, the desired change does not happen . What could be wrong?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyDatabaseWindow extends JPanel{
public static final String FRONT_PAGE = "Front Page";
public static final String BROWSE_MEMORIES = "Browse Memories";
public static final String ADD_EDIT = "Add Edit";
public static final String VIEW_MEMORY = "View Memory";
public static void createAndShowGUI() {
final MyDatabaseWindow mdbw = new MyDatabaseWindow();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(null);
final JButton addButton = new JButton("Add");
final JButton editButton = new JButton("Edit");
final JButton deleteButton = new JButton("Delete");
final JButton browseButton = new JButton("Browse");
final JButton searchButton = new JButton("Search");
addButton.setBounds(100, 400, 100, 100);
editButton.setBounds(200, 400, 100, 100);
deleteButton.setBounds(300, 400, 100, 100);
browseButton.setBounds(400, 400, 100, 100);
searchButton.setBounds(500, 400, 100, 100);
buttonPanel.add(addButton);
buttonPanel.add(editButton);
buttonPanel.add(deleteButton);
buttonPanel.add(browseButton);
buttonPanel.add(searchButton);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToAddPage();
}
});
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToBrowse();
}
});
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToBrowse();
}
});
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToBrowse();
}
});
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToSearch();
}
});
JFrame frame = new JFrame("Memory Files");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 540);
frame.setLocation(250, 100);
frame.getContentPane().add(mdbw);
frame.getContentPane().add(buttonPanel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private CardLayout cardLayout = new CardLayout();
private JPanel cardShowingPanel = new JPanel(cardLayout);
public MyDatabaseWindow() {
Window1 win1 = new Window1();
cardShowingPanel.add(win1, FRONT_PAGE);
Window2 win2 = new Window2();
cardShowingPanel.add(win2, BROWSE_MEMORIES);
Window3 win3 = new Window3();
cardShowingPanel.add(win3, ADD_EDIT);
Window4 win4 = new Window4();
cardShowingPanel.add(win4, VIEW_MEMORY);
setLayout(new BorderLayout());
add(cardShowingPanel, BorderLayout.NORTH);
}
public void goToAddPage() {
cardLayout.first(cardShowingPanel);
}
public void goToBrowse() {
cardLayout.first(cardShowingPanel);
cardLayout.next(cardShowingPanel);
}
public void goToSearch() {
cardLayout.last(cardShowingPanel);
}
public void showCard(String key) {
cardLayout.show(cardShowingPanel, key);
}
}
class Window1 extends JPanel {
public Window1() {
init();
}
private void init() { //dummy details
JLabel title = new JLabel("Memory Files");
title.setBounds(0, 0, 500, 500);
add(title);
}
}
class Window2 extends JPanel {
public Window2() {
init();
}
private void init() { //dummy details
JLabel title = new JLabel("Memory Files");
title.setBounds(0, 0, 500, 500);
add(title);
}
}
class Window3 extends JPanel {
public Window3() {
init();
}
private void init() {//dummy details
JLabel title = new JLabel("Memory Files");
title.setBounds(0, 0, 500, 500);
add(title);
}
}
class Window4 extends JPanel {
public Window4() {
init();
}
private void init() {//dummy details
JLabel title = new JLabel("Memory Files");
title.setBounds(0, 0, 500, 500);
add(title);
}
}
The main problem is the use of null-layouts and these lines of code:
frame.getContentPane().add(mdbw);
frame.getContentPane().add(buttonPanel);
First you add the panel using the CardLayout to BorderLayout.CENTER, then you "overlay" it with your buttonPanel, which is using null-layout.
I would go with a simple FlowLayout (the default layout-manager for a JPanel) for the buttonPanel and add it to the BorderLayout.SOUTH of the contentPane. I would also strongly recommend reading this tutorial.
So remove the following lines of code:
buttonPanel.setLayout(null);
...
addButton.setBounds(100, 400, 100, 100);
editButton.setBounds(200, 400, 100, 100);
deleteButton.setBounds(300, 400, 100, 100);
browseButton.setBounds(400, 400, 100, 100);
searchButton.setBounds(500, 400, 100, 100);
and change frame.getContentPane().add(buttonPanel); to frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);.
Also forget about the null-layout / setBounds() in your Window-classes.
(Note that you still won't see the text change if you press a button because you always add a JLabel with the same text ("Memory Files") to your Windows.)
I am trying to create a UI for an imaginary vehicle that has both Automatic and Manual modes. When the user sets the vehicle into one of the modes, it should only display the controls relevant to that mode, and I've accomplished this using a CardLayout.
However, I'd also like to be able to specify the location of the various elements of the layout for each card manually - for a static layout I'd do something along the lines of mainPanel.setLayout(null), but this simply gives a blank window when used on a CardLayout (hence the two commented-out lines in the code below).
How would I achieve both of these things? My current code is below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UI extends JFrame implements ActionListener{
public UI() {
initUI();
}
private JPanel cardPanel;
private CardLayout cardLayout = new CardLayout();
public final void initUI() {
cardPanel = new JPanel();
cardPanel.setLayout(cardLayout);
JPanel manualPanel = new JPanel();
getContentPane().add(manualPanel);
//manualPanel.setLayout(null);
cardPanel.add(manualPanel, "manual");
JPanel autoPanel = new JPanel();
//autoPanel.setLayout(null);
cardPanel.add(autoPanel, "auto");
JButton startButton = new JButton("START/STOP");
startButton.setBounds(50, 150, 200, 50);
startButton.addActionListener(new startListener());
manualPanel.add(startButton);
autoPanel.add(startButton);
JButton autoButton = new JButton("SWITCH TO AUTO");
autoButton.setBounds(50, 250, 200, 50);
autoButton.addActionListener(new autoListener());
manualPanel.add(autoButton);
JButton upButton = new JButton("^");
upButton.setBounds(125, 320, 50, 50);
upButton.addActionListener(new returnListener());
manualPanel.add(upButton);
JButton downButton = new JButton("\\/");
downButton.setBounds(125, 380, 50, 50);
downButton.addActionListener(new returnListener());
manualPanel.add(downButton);
JButton ccwButton = new JButton("<-");
ccwButton.setBounds(55, 350, 50, 50);
ccwButton.addActionListener(new returnListener());
manualPanel.add(ccwButton);
JButton cwButton = new JButton("->");
cwButton.setBounds(195, 350, 50, 50);
cwButton.addActionListener(new returnListener());
manualPanel.add(cwButton);
JButton ngzButton = new JButton("SOMETHING ELSE");
ngzButton.setBounds(50, 450, 200, 50);
ngzButton.addActionListener(new returnListener());
manualPanel.add(ngzButton);
JButton manualButton = new JButton("SWITCH TO MANUAL");
manualButton.setBounds(50, 250, 200, 50);
manualButton.addActionListener(new manualListener());
autoPanel.add(manualButton);
JButton returnButton = new JButton("SOMETHING ELSE");
returnButton.setBounds(50, 350, 200, 50);
returnButton.addActionListener(new returnListener());
autoPanel.add(returnButton);
setTitle("UI");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(cardPanel, BorderLayout.NORTH);
}
public static void main(String[] args) {
UI ui = new UI();
ui.setVisible(true);
}
public void actionPerformed(ActionEvent e){
}
private class returnListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
}
}
private class autoListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
cardLayout.show(cardPanel, "auto");
}
}
private class startListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
}
}
private class manualListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
cardLayout.show(cardPanel, "manual");
}
}
}
In your example, you create a startButton, but you then attempt to add the same instance to two different panels. Because a component can only occupy one container, you'll need to create two buttons, one for each panel.
As an aside, instead of using a null layout, give each panel BorderLayout, add the buttons to a JPanel having the default FlowLayout, and add the button panel to the SOUTH. You can then nest your illustrations in the CENTER using whatever layout is appropriate.
Addendum: As #Frakcool comments, using a layout will improve the cross-platform appearance of your buttons. Invoke pack() on the enclosing window, and override getPreferredSize() on the nested illustration panel to give it the needed size. In this related example, the CENTER panel is used for drawing only; having no components, its layout then becomes irrelevant.
I am making a Log in window, so after enter username, password and click login button it will direct you to another frame, which is my GUI that use to insert, retrieve, update, and delete database. However, after click, it displayed nothing. Thank you! Here is my code:
It should redirect to GUI like this:
Login
public class Log extends JFrame {
public static void main(String[] args) {
Log frameTabel = new Log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
Log() {
super("Login Autentification");
setSize(300, 200);
setLocation(500, 280);
panel.setLayout(null);
txuser.setBounds(70, 30, 150, 20);
pass.setBounds(70, 65, 150, 20);
blogin.setBounds(110, 100, 80, 20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin() {
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if ( puname.equals("test") && ppaswd.equals("12345") ) {
CarSearch regFace = new CarSearch();
// regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,
"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
Here is the CarSearch
public class CarSearch {
public static void main(String[] args) {
MainPanel logoPanel = new MainPanel();
JFrame frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
First of all, I don't encourage the use of multiple frames, instead you should use a CardLayout, how ever. Your CarSearch class doesn't do anything, it only has static main method, which you never call.
I would change the class so it has a constructor which initialises the class and a method you can call so you can control when you want to the window shown
public class CarSearch {
private MainPanel logoPanel;
private JFrame frame;
public CarSearch() {
logoPanel = new MainPanel();
frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
}
public void show() {
frame.pack();
frame.setVisible(true);
}
}
Now, having said that, I'd strongly encourage you to use a CardLayout.
Start by creating a LoginPanel and a CarSearchPanel, then you can add each to the same frame and use the CardLayout to switch between them as needed
For (a slight over the top) example
If that is what you want to do then in your CarSearch class should be a JFrame and in your main method you should have CarSearch frame = new CarSearch("Cars Search") instead of JFrame frame = new JFrame("Cars Search"). Then introduce a method public void authenticated() which should contain the code for enabling the other tabs. Also your initialisation should have all the tabs other than the login tab disabled.
Now in your method public void actionlogin() in your validation condition if ( puname.equals("test") && ppaswd.equals("12345") ) you should have CarSearch frame = (CarSearch)getRootPane(); and after that you could call frame.authenticated(); which will disable the login tab and enable the other tabs.
I want to add a timer button to my main frame but it is in another class and I don't know how to use it in my main class.
I need a timer button in my frame but I can't make it without another class.
In that class I can't call my main frame.
This is my code:
class ButtonTimer extends Thread{
private JButton button = new JButton(" ");
private int count = 1;
public ButtonTimer() {
Timer time = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
button.setText(String.valueOf(count));
count++;
}
});
time.start();
JFrame frame1 = new JFrame();
frame1.add(button);
frame1.setBounds(0, 20, 100, 50);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.pack();
frame1.setVisible(true);
}
}
public class game {
public static void main(String[] args) {
JFrame frame2 = new JFrame();
frame2.setBounds(0, 0, 1000, 5000);
frame2.setVisible(true);
JLayeredPane jlp = new JLayeredPane();
jlp.setBounds(0, 0, 1000, 500);
frame2.add(jlp);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonTimer();
}
});
}
}
How can I do this?
You Could...
Create a custom JButton that wraps a Timer internally to it.
This allows you to self contain the button and timer into a single unit and reuse it where ever you want...
You Could...
Create a custom Timer which takes a reference to a JButton and updates the text automatically on each trigger...
You Could...
Create a custom ActionListener or even Action that takes a reference to a JButton and updates the text and then pass this into a Timer instance of your choice...
Have a try. Here we create a JButton in your main frame and then we set the text on actionPerformed of another class.
public class game1 {
private static JFrame frame2;
private static JButton button1=new JButton(" ");
public static void main(String[] args) {
frame2 = new JFrame();
frame2.setBounds(0, 0, 1000, 5000);
JLayeredPane jlp = new JLayeredPane();
jlp.setBounds(0, 0, 1000, 500);
jlp.add(button1);
frame2.add(jlp);
frame2.add(button1);
frame2.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonTimer();
}
});
}
private static class ButtonTimer {
private JButton button = new JButton(" ");
private int count = 1;
public ButtonTimer() {
javax.swing.Timer timer = new javax.swing.Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setText(String.valueOf(count));
button1.setText(String.valueOf(count));
count++;
}
});
timer.start();
JFrame frame1 = new JFrame();
frame1.add(button);
frame1.setBounds(0, 20, 100, 50);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.pack();
frame1.setVisible(true);
}
}
}