So i am trying to add an image to my program after a button is pressed with a certain value entered into a text field. I want the image to be blank until the button is pressed with the correct value. The only issue i seem to be having is making the photo appear, i know the output should be working. here is the code i have for adding the label.
photo = new JLabel();
photo.setBounds(425, 170, 400, 360);
contentPane.add(photo);
ImageIcon icon = new ImageIcon("AwsomeSauce.jpg");
here is the code for when the value is entered correctly
if (error) {
photo.setIcon(image);
}
now im still pretty new at this so go easy on me.
Here is simple example for you:
public class Frame extends JFrame {
private JLabel label;
public Frame() {
getContentPane().add(label = new JLabel(),BorderLayout.SOUTH);
JButton b = new JButton("show Icon");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
URL resource = getClass().getResource("/res/3_disc.png");
ImageIcon ico = new ImageIcon(resource);
label.setIcon(ico);
}
});
getContentPane().add(b,BorderLayout.NORTH);
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setTitle("This is a test");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
"/res/3_disc.png" - is my icon which is placed in my project in res folder.
Related
I have a specific problem I'm stuck on. My job is to have this pop up:
Here's the program I have so far:
import javax.swing.*;
import java.awt.event.*;
public class Assignment5 implements ActionListener
{
JFrame frame;
JPanel panel;
JLabel label1, label2, label3, label4;
JButton button;
JTextField text1, text2, text3;
public Assignment5()
{
frame = new JFrame();
frame.setVisible(true);
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1 = new JLabel("No. of Years: ");
text1 = new JTextField(20);
label2 = new JLabel("Rate of Interest: ");
text2 = new JTextField(20);
label3 = new JLabel("Principal Amount: ");
text3 = new JTextField(20);
button = new JButton("Calculate Simple Interest");
panel = new JPanel();
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(text1);
panel.add(text2);
panel.add(text3);
panel.add(button);
frame.add(panel);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int years = Integer.parseInt(text1.getText());
double rate = Double.parseDouble(text2.getText());
double amount = Double.parseDouble(text3.getText());
double simple = years*rate*amount;
label4 = new JLabel("Your Payable Amount Is: "+simple);
panel.add(label4);
}
public static void main(String[] args)
{
Assignment5 obj = new Assignment5();
}
}
Everything works so far, but my final label containing the actual result won't show up. I've tried a couple different things, each of which doesn't work, so I'm hoping you guys will be able to tell me a better way of doing this. Thanks.
Do you have any red errors showing up in any line of your code? I am not sure if it is the output code that is wrong. Try this:
label4.setText("Your payable amount is "+simple);
Try this:
JOptionPane.showMessageDialog(null,"Your payable amount is “+simple);
That will pop your message.
When i run the following Code and push Button "Push", more than once a time, i get browser error "simplePanel can only contain one child widget". How can i solve that problem? thank you in advance! Jogi
public class Projekt implements EntryPoint {
private RootPanel rootPanel;
public void onModuleLoad() {
rootPanel = RootPanel.get("gwtContainer");
rootPanel.setSize("1902", "868");
final AbsolutePanel boundaryPanel = new AbsolutePanel();
boundaryPanel.setStyleName("frame1");
boundaryPanel.setSize("1455px", "600px");
final Diagram diagram = new Diagram(boundaryPanel);
RootPanel.get().add(boundaryPanel, 446, 242);
final Connector con = new Connector(100, 300, 300, 500);
Button la = new Button("Push");
la.setSize("200", "200");
RootPanel.get().add(la);
Button la2 = new Button("Push2");
la2.setSize("200", "200");
RootPanel.get().add(la2);
final Image img = new Image("images/concrete.svg");
img.setSize("200", "200");
final Shape shapei = new Shape(img);
Image img2 = new Image("images/variable.svg");
img2.setSize("200", "200");
boundaryPanel.add(img2, 200,200);
final Shape shapei2 = new Shape(img2);
shapei2.showOnDiagram(diagram);
la.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
boundaryPanel.add(img, 100,100);
shapei.showOnDiagram(diagram);
}
});
la2.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
con.showOnDiagram(diagram);
}
});
diagram.addDiagramListener(new DiagramListenerAdapter() {
#Override
public void onElementConnect(ElementConnectEvent event) {
if (con.startEndPoint.isGluedToConnectionPoint()) {
Widget connected = con.startEndPoint.gluedConnectionPoint.parentWidget;
if(connected.equals(shapei.connectedWidget)){
Image logo = new Image("images/xor.svg");
logo.setSize("100", "100");
boundaryPanel.add(logo);
}
else if(connected.equals(shapei2.connectedWidget)){
Image logo2 = new Image("images/and.svg");
logo2.setSize("100", "100");
boundaryPanel.add(logo2);
};
}}
});
}}
RootPanel.get() is a SimplePanel. You try to add more than one child to it, resulting in this error.
Instead, you should add HTMLPanel, for example, to your RootPanel, and then add all the children to this HTMLPanel.
I suppose your Diagram extends GWT's SimplePanel
class? SimplePanel can contain only a single widget, have a look here:
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/SimplePanel.html
You could either extend a different class, or call the remove(Widget w) method to remove the existing widget before trying to add a new one.
I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Put the ActionListener into the sim class.
public void actionPerformed(ActionEvent e)
{
JButton clicked = (JButton)e.getSource();
if(clicked == button)
{
JOptionPane.showMessageDialog(null, "this team will win");
}
}
You need to decrees the amount of code to just amount needed you dont need to show us all the raidio
I am using JavaFX ColorPicker in my application. As per my requirements, I have mapped the default colors on the color picker to a number. I want this number to be displayed as tooltip on hover over the color instead of hex value of the color. How can I achieve this?
//Part of Code
public void handleNodes(Circle circularNode) {
final Delta offset = new Delta();
circularNode.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
((Circle)(event.getSource())).setCursor(Cursor.HAND);
}
});
circularNode.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(event.getButton().equals(MouseButton.SECONDARY)) {
System.out.println("Right click");
Circle parent = ((Circle)(event.getSource()));
final ContextMenu contextMenu = new ContextMenu();
MenuItem editLabel = new MenuItem("Edit Label");
editLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Edit Label");
final ColorPicker colorPicker = new ColorPicker();
colorPicker.setStyle("-fx-border-radius: 10 10 10 10;"
+ "-fx-background-radius: 10 10 10 10;");
colorPicker.setValue((Color) parent.getFill());
colorPicker.showingProperty().addListener((obs,b,b1)->{
if(b1){
PopupWindow popupWindow = getPopupWindow();
javafx.scene.Node popup = popupWindow.getScene().getRoot().getChildrenUnmodifiable().get(0);
popup.lookupAll(".color-rect").stream()
.forEach(rect->{
Color c = (Color)((Rectangle)rect).getFill();
Tooltip.install(rect.getParent(), new Tooltip("Custom tip for "+c.toString()));
});
}
});
panelMain.getChildren().add(colorPicker);
}
});
This is really a hacky answer.
The first problem: you have to find the popup node on the scene once it shows up. But you won't... since its not in the same window!
Having a deep look at how ScenicView does it, the trick is getting the list of windows at that moment, but using a deprectated method:
private PopupWindow getPopupWindow() {
#SuppressWarnings("deprecation") final Iterator<Window> windows = Window.impl_getWindows();
while (windows.hasNext()) {
final Window window = windows.next();
if (window instanceof PopupWindow) {
return (PopupWindow)window;
}
}
return null;
}
Once you have the popup window, we can now check for all the Rectangle nodes using lookupAll and the CSS selector color-rect, to get their color, and install the tooltip over its parent container:
#Override
public void start(Stage primaryStage) {
ColorPicker picker = new ColorPicker();
StackPane root = new StackPane(picker);
Scene scene = new Scene(root, 500, 400);
primaryStage.setScene(scene);
primaryStage.show();
picker.showingProperty().addListener((obs,b,b1)->{
if(b1){
PopupWindow popupWindow = getPopupWindow();
Node popup = popupWindow.getScene().getRoot().getChildrenUnmodifiable().get(0);
popup.lookupAll(".color-rect").stream()
.forEach(rect->{
Color c = (Color)((Rectangle)rect).getFill();
Tooltip.install(rect.getParent(), new Tooltip("Custom tip for "+c.toString()));
});
}
});
}
This is what it looks like:
Based on the code posted by the OP after my first answer, and due to the substancial changes in the problem addressed, I'm adding a new answer that covers both situations:
The ColorPicker is embedded in the main scene, as a regular node
The ColorPicker is embedded in a ContextMenu
In the second situation, the proposed solution for the first one is no longer valid, since the window found will be the one with the context menu.
A task is required to keep looking for windows until the one with the ComboBoxPopupControl is found.
This is a full runnable example:
public class ColorPickerFinder extends Application {
ExecutorService findWindowExecutor = createExecutor("FindWindow");
#Override
public void start(Stage primaryStage) {
AnchorPane panCircles = new AnchorPane();
Scene scene = new Scene(panCircles, 400, 400);
final Random random = new Random();
IntStream.range(0,5).boxed().forEach(i->{
final Circle circle= new Circle(20+random.nextInt(80),
Color.rgb(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
circle.setTranslateX(100+random.nextInt(200));
circle.setTranslateY(100+random.nextInt(200));
panCircles.getChildren().add(circle);
});
panCircles.setPrefSize(400, 400);
ColorPicker colorPicker = new ColorPicker();
panCircles.getChildren().add(colorPicker);
primaryStage.setScene(scene);
primaryStage.show();
// We add listeners AFTER showing the stage, as we are looking for nodes
// by css selectors, these will be available only after the stage is shown
colorPicker.showingProperty().addListener((obs,b,b1)->{
if(b1){
// No need for task in this case
getPopupWindow();
}
});
panCircles.getChildren().stream()
.filter(c->c instanceof Circle)
.map(c->(Circle)c)
.forEach(circle->{
circle.setOnMouseClicked(e->{
if(e.getButton().equals(MouseButton.SECONDARY)){
// We need a task, since the first window found is the ContextMenu one
findWindowExecutor.execute(new WindowTask());
final ColorPicker picker = new ColorPicker();
picker.setStyle("-fx-border-radius: 10 10 10 10;"
+ "-fx-background-radius: 10 10 10 10;");
picker.setValue((Color)(circle.getFill()));
picker.valueProperty().addListener((obs,c0,c1)->circle.setFill(c1));
final ContextMenu contextMenu = new ContextMenu();
MenuItem editLabel = new MenuItem();
contextMenu.getItems().add(editLabel);
editLabel.setGraphic(picker);
contextMenu.show(panCircles,e.getScreenX(),e.getScreenY());
}
});
});
}
private PopupWindow getPopupWindow() {
#SuppressWarnings("deprecation")
final Iterator<Window> windows = Window.impl_getWindows();
while (windows.hasNext()) {
final Window window = windows.next();
if (window instanceof PopupWindow) {
if(window.getScene()!=null && window.getScene().getRoot()!=null){
Parent root = window.getScene().getRoot();
if(root.getChildrenUnmodifiable().size()>0){
Node popup = root.getChildrenUnmodifiable().get(0);
if(popup.lookup(".combo-box-popup")!=null){
// only process ComboBoxPopupControl
Platform.runLater(()->{
popup.lookupAll(".color-rect").stream()
.forEach(rect->{
Color c = (Color)((Rectangle)rect).getFill();
Tooltip.install(rect.getParent(),
new Tooltip("Custom tip for "+c.toString()));
});
});
return (PopupWindow)window;
}
}
}
return null;
}
}
return null;
}
private class WindowTask extends Task<Void> {
#Override
protected Void call() throws Exception {
boolean found=false;
while(!found){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
found=(getPopupWindow()!=null);
}
return null;
}
}
private ExecutorService createExecutor(final String name) {
ThreadFactory factory = r -> {
Thread t = new Thread(r);
t.setName(name);
t.setDaemon(true);
return t;
};
return Executors.newSingleThreadExecutor(factory);
}
public static void main(String[] args) {
launch(args);
}
}
This will be the result after right clicking on a circle, and clicking on the color picker:
I'm working on a JFrame interface to interact easily with a large amount of data. The data is saved in a .txt file, and when a name is selected from the JList, my program reads the appropriate lines of data, converts them into an Object I've defined (CounterParty), and displays the appropriate fields of the objects in JLabels. This all works well. I've also written code to launch a new JPanel that edits the selected Object. The JPanel opens, already populated with the data, and when a button is clicked the existing information on the .txt file is deleted and replaced with the new, edited data. This also works well.
However, I would like to make this a bit more user-friendly. I want the JLabels where the information is initially displayed to convert into JTextFields populated with the data from the jLabels when the Edit button is clicked. This would remove needing to launch the new JPanel window altogether. I assume is would change the visibility to false of the JLabels and create new JTextField objects. I'm having trouble with this. Can JLabel objects be converted to JTextFields? Can I maybe have both objects in the exact same spot, but alternate visibility? I'm not sure how to go about this.
I'm using NetBeans.
Thank you for your help! Let me know if any additional information is needed.
This is one way to do that:
Assuming that JLabel is your label and textfield your JTextField
textfield = new JTextField(label.getText());
This will create a with the text of the JLabel.
You should place your JLabel in a dedicated JPanel, so you remove the JLabel from it and replace it with the JTextField, then repaint()/revalidate()
I created a small example which I think demonstrates what you want. It uses a button which when pressed will either remove the JTextField and add the JLabel and vice versa and then it will call revalidate() and repaint() to show changes to the frame after each button click:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JLabelToJTextField extends JFrame {
JLabel jLabel;
JTextField jTextField;
JButton jButton;
JPanel mainPanel;
public JLabelToJTextField() {
jLabel = new JLabel("Name");
jTextField = new JTextField(15);
jButton = new JButton("Edit");
mainPanel = new JPanel(new BorderLayout());
createUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JLabelToJTextField().setVisible(true);
}
});
}
private void createUI() {
setTitle("JLabel to JtextField");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPanel();
setLocationRelativeTo(null);
pack();
}
private void addComponentsToPanel() {
mainPanel.add(jLabel, BorderLayout.CENTER);
mainPanel.add(jButton, BorderLayout.SOUTH);
addActionListeners();
getContentPane().add(mainPanel);
}
private void addActionListeners() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
switch (jButton.getText()) {
case "Edit":
mainPanel.remove(jLabel);//remove component
mainPanel.add(jTextField, BorderLayout.CENTER);//add new component
jButton.setText("Done");
//refresh JFrame
revalidate();
repaint();
break;
case "Done":
mainPanel.remove(jTextField);//remove component
mainPanel.add(jLabel, BorderLayout.CENTER);//add new component
jButton.setText("Edit");//set button text to original
//refresh JFrame
revalidate();
repaint();
break;
}
}
});
}
}